current position:Home>Win10 system C++ calls OpenCV to realize webcam recording and snapshot pictures

Win10 system C++ calls OpenCV to realize webcam recording and snapshot pictures

2022-09-23 09:32:57comeling

1 前言

The previous article introduced inWIN10系统上,分别用C++和Python调用OpenCV接口,Play local and webcam videos.本篇我们来看一下,用C++如何调用OpenCV接口,Open webcam video,Videotape it,并抓拍图片.

视频来源

视频格式/协议

参数

网络摄像头

RTSP

rtsp://admin:[email protected]:554/Streaming/Channels/101

Below we use HikvisionIPCamera for testing,表格中的rtsp地址,It's a Hikvision cameraURL格式,其它品牌(大华、宇视)与之类似.

rtsp://admin:[email protected]:554/Streaming/Channels/101

rtsp:表示采用RTSPThe protocol takes the stream from the camera

admin:Camera web page login user name

123456:The login password of the camera web page

192.168.1.104:摄像机IP地址

554:RTSP默认端口

输出文件

格式

文件名称

录像文件

mp4

output.mp4

Capture picture files

bmp

picture_x.bmp

2 Key interface description

在测试程序中,主要用到了OpenCV以下接口:

录制视频

VideoWriterWrite video file class,Used when recording video files.

测试程序中,Use the overloaded constructor of this class,原型如下:

CV_WRAP VideoWriter(const String& filename, int fourcc, double fps,
                Size frameSize, bool isColor = true);

参数说明:

filename:The path and name of the saved video file

fourcc指定视频编码器,特别注意,在OpenCV3种,This parameter is called as followsCV_FOURCC('M','P','4','2').在OpenCV4中,The parameter calling method has been changed,See the code behind for details.要不然编译不过

fps:Saved video frame rate

frameSizeVideo file video resolution size,That is, the width and height of the video screen

isColorIndicates whether the video is recorded in color or black and white,默认ture,彩色画面

抓拍图片

函数原型:

CV_EXPORTS_W bool imwrite( const String& filename, InputArray img,
              const std::vector<int>& params = std::vector<int>());

参数说明:

filename:The saved snapshot image file path and name

imgCaptured video frame,其类型为Mat

paramsUsed to set the parameters of the corresponding image format,Generally, these image formats are compressed,Here is to set these compression parameters to control the quality of the picture.该参数是一个vector<int>类型,stored separatelyparamId_1, paramValue_1, paramId_2, paramValue_2, ... That is to say, store a pair of attribute values.如果不设置该参数的话,The program will automatically adopt a default parameter according to the saved image format.

3 创建测试项目

创建测试项目、配置开发环境,For details, please refer to the previous article,这里就不多说了

Win10+OpenCV4.6.0之开发环境(VS2022)配置入门_Come to Ling's blog-CSDN博客

The name of the test project this timevideo_record,VS2022A screenshot of the created project

将下列代码编辑到video_record.cpp文件里

#include <opencv2\opencv.hpp>
#include <iostream>
#include <string>
using namespace cv;
using namespace std;

//Open webcam recording
bool OpenCameraAndRecord(const std::string& url)
{
	cout << "The video file is about to be played,Press the space bar to end playback" << endl;

	VideoCapture capture;
	bool result = capture.open(url);

	//检查是否成功打开
	if (!capture.isOpened())
	{
		cout << "Failed to open the text camera,url:" << url << endl;
		return result;
	}

	//Print video parameters:宽、高、每秒传输帧数
	int videoWidth = capture.get(CAP_PROP_FRAME_WIDTH);
	int videoHeight = capture.get(CAP_PROP_FRAME_HEIGHT);
	int videoFps = capture.get(CAP_PROP_FPS);

	cout << "视频分辨率为:" << videoWidth << "x" << videoHeight << ",fps:" << videoFps << endl;

	//下边是OpenCV3中的调用方式,OpenCV4Adjusted the second parameter interface
	//VideoWriter vedio("./record/output.mp4", CV_FOURCC('M', 'J', 'P', 'G'), videoFps, Size(videoWidth, videoHeight));

	VideoWriter recorder("./record/output.mp4", CAP_OPENCV_MJPEG, videoFps, Size(videoWidth, videoHeight), true);

	try
	{
		Mat frame;
		char pictureName[256] = { 0 };
		int pictureIndex = 1;
		while (true)
		{
			capture >> frame;						//读取视频帧
			if (true == frame.empty())
			{
				cout << "Get video frame is empty,退出播放" << endl;
				break;
			}

			//If only the video is recorded in the background,Playback is not implemented,把imshow注释掉
			imshow("Camera live video", frame);		//在名称为“视频文件”display the video in the window

			recorder << frame;						//Write video frames to the video file

			int key = waitKey(1);
			if (32 == key)							//Press the space bar to exit the display of each frame of the video
			{
				snprintf(pictureName, sizeof(pictureName), "./picture/picture_%d.bmp", pictureIndex++);
				cv::imwrite(pictureName, frame);
			}
			else if (27 == key)						//按下ESCkey to exit video playback and recording
			{
				cout << "按下空格键,Exit playback and recording" << endl;
				break;
			}
			else {}
		}
	}
	catch (const std::exception& e)
	{
		cout << "exception:" << e.what() << endl;
	}

	capture.release();
	recorder.release();
	//If only the video is recorded in the background,Playback is not implemented,把destroyWindow注释掉
	destroyWindow("Camera live video");
	cout << "视频录制完成" << endl << endl;
	return result;
}

int main()
{
	cout << "使用OpenCV录制视频测试" << endl;

	//Turn on webcam playback
	//If you want to open the computer's local video file for recording,The following parameters can be passed in the path and name of the video file
	OpenCameraAndRecord("rtsp://admin:[email protected]:554/Streaming/Channels/101");

	cout << "完成测试" << endl;
	system("pause");
}

 The current directory of the test project project,新创建2个文件夹:recordpicture,They are used to save video files and snapshot picture files respectively

VSScreenshot of the code in

 4 效果截图

 录像文件

使用VLCopen play

抓拍图片

打开图片

 5 参考资料

 OpenCVHow to take pictures and record videos_top_geek_001的博客-CSDN博客_opencv 拍照

copyright notice
author[comeling],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/266/202209230927292318.html

Random recommended