在opencv中拍摄多张照片

时间:2014-11-24 23:05:18

标签: c++ opencv

这看起来相当简单,但对于我的生活,我无法弄清楚为什么这不起作用。我有类似的代码,每次读取图像时都会写入图像,并且可以很好地保存最后看到的图像。我很担心为什么这会将同一图像保存到img0和img1。如果你们能够发光,那将是惊人的!非常感谢您花时间阅读本文。

#include "highgui.hpp"
#include "imgproc.hpp"
#include "opencv.hpp"
#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;
using namespace cv;

int main(){
    VideoCapture stream(0);
    if(!stream.isOpened()){
        cout << "No camera :(\n";
    }
    stream.set(CV_CAP_PROP_FRAME_WIDTH, 640);
    stream.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
    int img_num = 0; 
    int num_pics;
    cout << "How many images do you want to take?\n";
    cin >> num_pics;
    Mat image;
    while(img_num < num_pics){
        cout << "Picture in...\n";
        cout << "3...\n";
        sleep(1);   
        cout << "2...\n";
        sleep(1);
        cout << "1...\n";
        sleep(1);

        stream.read(image);
        imshow("pic",image);
        imwrite(format("img_%d.jpg",img_num),image);
        waitKey(3000);
        img_num += 1;
    }
    return 0;
}

编辑以添加简单代码以保存捕获的每个帧(进入同一文件,因此最终应该是最后看到的图像):

#include "/home/sarah/opencv-2.4.9/modules/highgui/include/opencv2/highgui/highgui.hpp"
#include "/home/sarah/opencv-2.4.9/modules/imgproc/include/opencv2/imgproc/imgproc.hpp"
#include "/home/sarah/opencv-2.4.9/include/opencv2/opencv.hpp"
#include <iostream>
using namespace std;
using namespace cv;

int main(){
    VideoCapture stream(0);
    //stream.set(CV_CAP_PROP_FPS,1);
    if(!stream.isOpened()){
        cout << "No camera :(\n";
    }
    cout << "After\n";
    stream.set(CV_CAP_PROP_FRAME_WIDTH, 640);
    stream.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
    Mat cameraFrame;
    while(1){
        stream.read(cameraFrame);
        imshow("camera",cameraFrame);
        imwrite("img.jpg",cameraFrame);
        if(waitKey(30) == 13){
            break;  
        }
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

这是罪魁祸首:

imwrite(filename,image);

atm,它会将任何图像保存为相同的文件名(因此会覆盖任何普遍的文件)。你想要的可能更像是:

imwrite( format("img_%d.jpg",img_num) ,image );