1--Turn on the camera
Key code statement:
① VideoCapture cam(0);
② cam.read(img);
③ imshow("cam", img);
# include<opencv2/opencv.hpp>
# include<cstdio>
using namespace cv;
using namespace std;
int main(int argc, char *argv[]){
// 打开摄像头
VideoCapture cam(0);
if (!cam.isOpened()){
cout << "cam open failed!" << endl;
getchar();
return -1;
}
cout << "cam open success!" << endl;
namedWindow("cam");
Mat img;
for(;;){
cam.read(img); // 读帧
if (img.empty()) break;
imshow("cam", img); // 显示每一帧
if (waitKey(5) == 'q') break; // 键入q停止
}
return 0;
}
2--Save camera video
key code:
①VideoWriter vw
②vw.open(): Fourcc specifies the encoding format ( common encoding method ), fps specifies the frame rate, and Size specifies the size
③vw.write()
# include<opencv2/opencv.hpp>
# include<cstdio>
using namespace cv;
using namespace std;
int main(int argc, char *argv[]){
// 打开摄像头
VideoCapture cam(0);
if (!cam.isOpened()){
cout << "cam open failed!" << endl;
getchar();
return -1;
}
cout << "cam open success!" << endl;
namedWindow("cam");
Mat img;
VideoWriter vw;
int fps = cam.get(CAP_PROP_FPS); // 获取原视频的帧率
if (fps <= 0) fps = 25;
vw.open("./out1120.avi",
VideoWriter::fourcc('X', '2', '6', '4'),
fps,
Size(cam.get(CAP_PROP_FRAME_WIDTH),
cam.get(CAP_PROP_FRAME_HEIGHT))
);
if (!vw.isOpened()){ // 判断VideoWriter是否正常打开
cout << "videoWriter open failed!" << endl;
getchar();
return -1;
}
cout << "videoWriter open sucess!" << endl;
for(;;){
cam.read(img); // 读帧
if (img.empty()) break;
imshow("cam", img); // 展示当前帧
/*
这里可以添加对当前帧的处理操作
*/
vw.write(img); // 保存当前帧
if (waitKey(5) == 'q') break; // 键入q停止
}
return 0;
}
Note: Executing the above code on Windows may report the following error:
Solution: Download the corresponding version of the library file from the output URL , and place it in the same directory as the executable file .exe, or add the path of the dll file to the system variable path.
Result: The generated out1120.avi can be played normally;