opencv摄像头获取连续图像(一) :单目获取图像

利用摄像头获取连续图像

1.设置帧数为30fps

2.读取摄像头5秒视频

2.将读取到的视频以每5帧采取一幅图像,共计30张,并保存。

源代码如下:

#include 
#include 

using namespace std;
using namespace cv;

int main()
{
	VideoCapture cap(0);//开启电脑摄像头
	if (cap.isOpened())
	  cout << "camera is opened"<< endl;
	else 
	  cout << "camera is not opened" << endl;
	

    bool stop = false;
	Mat frame;

	
	//设置摄像头分辨率640*480 帧率30fps
	cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);
	cap.set(CV_CAP_PROP_FRAME_WIDTH, 640);
	cap.set(CV_CAP_PROP_FPS, 30.0);

	//保存视频格式为avi, 编码为MJPG
	VideoWriter writer("test0.avi",CV_FOURCC('M', 'J', 'P', 'G'),30, Size(640,480),true);

	//通过总帧数控制拍摄时间,如果为5s的视频,循环5*30次;
	Mat videoPlay;
	int count = 150;
	namedWindow("videoplay", WINDOW_NORMAL);
	while (count)
	{
		cap >> videoPlay;
		writer << videoPlay;
		imshow("videoplay", videoPlay);
		waitKey(30);
		count --;
	}

	VideoCapture cap0("test0.avi");
	if(!cap0.isOpened())
		cout << "no video" << endl;
	Mat frame0;
	int num = 1;
	string filename;
	char temp_file[5];
	string path = "C:\\Users\\Administrator\\Desktop\\my\\pic";//can change the path
	for (int i = 1; ;i++)
	{
		cap0 >> frame0;
		if(frame0.empty())
			break;
		if(i % 5 == 0)
		{
		   _itoa_s(num, temp_file, 4, 10);
		   filename = temp_file;
		   filename = path + filename + ".jpg";
		   num ++;
		  imwrite (filename,frame0);
		}
	   }
	cap0.release();

	//system("pause");

	return 0;

}


 
 

你可能感兴趣的:(摄像头获取图像)