在liunx系统下,如何用opencv调用摄像头显示画面,并在按下p键后将当前画面储存到指定的/home/20204367路径下并根据保存顺序从photo1开始进行命名,直到按q键后关闭摄像头窗口。请进行程序编写并给出makefile文件
时间: 2023-05-29 08:01:27 浏览: 97
opencv调用摄像头并截图保存
程序代码如下:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
#include <sys/stat.h>
using namespace cv;
using namespace std;
int main()
{
VideoCapture cap(0);
if(!cap.isOpened())
{
cout << "Could not open camera!" << endl;
return -1;
}
namedWindow("Camera", WINDOW_NORMAL);
int photoNum = 1;
while(true)
{
Mat frame;
cap >> frame;
imshow("Camera", frame);
char c = waitKey(30);
if(c == 'p')
{
string path = "/home/20204367/photo" + to_string(photoNum) + ".jpg";
imwrite(path, frame);
cout << "Photo " << photoNum << " saved at " << path << endl;
photoNum++;
}
else if(c == 'q')
{
break;
}
}
destroyAllWindows();
cap.release();
return 0;
}
```
makefile文件如下:
```makefile
opencvCapture: opencvCapture.cpp
g++ -o opencvCapture opencvCapture.cpp `pkg-config --cflags --libs opencv`
clean:
rm opencvCapture
```
将以上代码保存为opencvCapture.cpp与makefile,在终端中进入代码所在目录,输入make命令编译并生成可执行文件opencvCapture,运行可执行文件即可调用摄像头显示画面并按p键储存照片。
阅读全文