在opencv下,对摄像头进行调用显示画面,在按下p键后对当前画面进行压缩保存到路径/root/20204367yyh并从photo1开始命名,并在视频画面左上角显示“当前已保存的图片数量”,最后在按下q键后退出画面。同时给出相应的Makefile文件,注意opencv的路径为/root/opencv-4.5.1,并给出使用方法
时间: 2023-05-28 19:02:57 浏览: 146
代码如下:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
using namespace cv;
using namespace std;
int main()
{
VideoCapture cap(0);
if(!cap.isOpened())
{
cout << "Failed to open camera!" << endl;
return -1;
}
namedWindow("Camera", WINDOW_NORMAL);
int count = 0;
char key = -1;
while(key != 'q')
{
Mat frame;
cap >> frame;
imshow("Camera", frame);
if(key == 'p')
{
count++;
string filename = "/root/20204367yyh/photo" + to_string(count) + ".jpg";
imwrite(filename, frame);
}
putText(frame, "Current photo count: " + to_string(count), Point(10, 30), FONT_HERSHEY_PLAIN, 2, Scalar(0, 0, 255), 2);
imshow("Camera", frame);
key = waitKey(1);
}
return 0;
}
```
Makefile文件如下:
```makefile
CC = g++
CFLAGS = -Wall -g -std=c++11 -I/root/opencv-4.5.1/include
LDFLAGS = -L/root/opencv-4.5.1/lib -lopencv_core -lopencv_highgui -lopencv_imgcodecs -lopencv_videoio
.PHONY: all clean
all: camera
camera: camera.cpp
$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS)
clean:
rm -rf camera
```
使用方法:
1. 将代码保存为camera.cpp,Makefile保存为Makefile;
2. 在终端中进入代码所在目录,执行make命令编译生成可执行文件camera;
3. 执行./camera命令启动程序,按下p键保存当前画面到指定路径下,按下q键退出程序。
阅读全文