如何在OpenCV中捕获图像并以pgm格式保存? [英] How do I capture images in OpenCV and saving in pgm format?
问题描述
我通常对编程是全新的,并且正在从事一个项目,该项目需要从我的网络摄像头(可能使用OpenCV)捕获图像,并将图像另存为pgm文件.
I am brand new to programming in general, and am working on a project for which I need to capture images from my webcam (possibly using OpenCV), and save the images as pgm files.
最简单的方法是什么? Willow Garage提供了以下用于图像捕获的代码:
What's the simplest way to do this? Willow Garage provides this code for image capturing:
http://opencv.willowgarage.com/wiki/CameraCapture
使用此代码作为基础,我如何将其修改为:
Using this code as a base, how might I modify it to:
- 每2秒从实时摄像头捕获一次图像
- 将图像保存为pgm格式的文件夹
非常感谢您可以提供的任何帮助!
Thanks so much for any help you can provide!
推荐答案
首先,请使用较新的网站- opencv.org .使用过时的引用会导致连锁效应,当新用户看到旧的引用,阅读旧的文档并再次发布旧的链接时.
First of all, please use newer site - opencv.org. Using outdated references leads to chain effect, when new users see old references, read old docs and post old links again.
实际上没有理由使用旧的C API.取而代之的是,您可以使用较新的C ++接口,该接口除其他功能外还可以优雅地处理视频捕获.这是 VideoCapture 上的文档的简化版示例:
There's actually no reason to use old C API. Instead, you can use newer C++ interface, which, among other things, handles capturing video gracefully. Here's shortened version of example from docs on VideoCapture:
#include "opencv2/opencv.hpp"
using namespace cv;
int main(int, char**)
{
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;
for(;;)
{
Mat frame;
cap >> frame; // get a new frame from camera
// do any processing
imwrite("path/to/image.png", frame);
if(waitKey(30) >= 0) break; // you can increase delay to 2 seconds here
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
此外,如果您是编程新手,请考虑对OpenCV- cv2 模块使用 Python接口.人们通常认为Python比C ++更简单,使用Python,您可以在交互式控制台中直接使用OpenCV函数.使用cv2
捕获视频看起来像这样(此处):
Also, if you are new to programming, consider using Python interface to OpenCV - cv2 module. Python is often considered simpler than C++, and using it you can play around with OpenCV functions right in an interactive console. Capturing video with cv2
looks something like this (adopted code from here):
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# do what you want with frame
# and then save to file
cv2.imwrite('path/to/image.png', frame)
if cv2.waitKey(30) & 0xFF == ord('q'): # you can increase delay to 2 seconds here
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
这篇关于如何在OpenCV中捕获图像并以pgm格式保存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!