如何在OpenCV中捕获图像并以pgm格式保存?

rob*_*bot 2 opencv capture pgm

我是一般的编程新手,我正在开发一个项目,我需要从我的网络摄像头捕获图像(可能使用OpenCV),并将图像保存为pgm文件.

最简单的方法是什么?Willow Garage提供此代码用于图像捕获:

http://opencv.willowgarage.com/wiki/CameraCapture

使用此代码作为基础,我如何将其修改为:

  1. 每2秒从实时摄像头捕获一个图像
  2. 将图像保存为pgm格式的文件夹

非常感谢您提供的任何帮助!

ffr*_*end 6

首先,请使用更新的网站 - opencv.org.当新用户查看旧引用,阅读旧文档并再次发布旧链接时,使用过时的引用会导致链式效应.

实际上没有理由使用旧的C API.相反,您可以使用更新的C++接口,除其他外,它可以优雅地处理视频捕获.以下是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;
}
Run Code Online (Sandbox Code Playgroud)

另外,如果您不熟悉编程,请考虑使用Python接口来实现OpenCV - cv2模块.Python通常被认为比C++更简单,使用它可以在交互式控制台中使用OpenCV函数.捕获视频cv2看起来像这样(从这里采用的代码):

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()
Run Code Online (Sandbox Code Playgroud)