How do I capture images in OpenCV and saving in pgm format?

前端 未结 5 1341
一生所求
一生所求 2020-12-20 04:28

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 f

5条回答
  •  星月不相逢
    2020-12-20 04:57

    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.

    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;
    }
    

    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()
    

提交回复
热议问题