1、此操作要确保opencv已经成功安装在Linux上
查看opencv版本:
pkg-config --modversion opencv
我的版本是:3.4.13
Linux安装 openCV3.4.13 在我上一篇文档
2、使用 C++ 编写代码
这里的代码为opencv3.4.13 API库VideoCapture里面的示例
新建vi opencv1.hpp
#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;
int main(int, char**)
{
Mat frame; //创建容器frame,用来存放照片滴
//--- INITIALIZE VIDEOCAPTURE
VideoCapture cap;
// open the default camera using default API
// cap.open(0);
// OR advance usage: select any API backend
int deviceID = 0; // 0 = open default camera
int apiID = cv::CAP_ANY; // 0 = autodetect default API
// open selected camera using selected API
cap.open(deviceID, apiID); //打开摄像头0
// check if we succeeded
if (!cap.isOpened()) {
cerr << "ERROR! Unable to open camera\n";
return -1;
}
//--- GRAB AND WRITE LOOP
cout << "Start grabbing" << endl
<< "Press any key to terminate" << endl;
for (;;) //for死循环
{
// wait for a new frame from camera and store it into 'frame'
cap.read(frame); //
// check if we succeeded
if (frame.empty()) {
cerr << "ERROR! blank frame grabbed\n";
break;
}
// show live and wait for a key with timeout long enough to show images
imshow("Live", frame); //图像展示
if (waitKey(5) >= 0) //等待函数毫秒级
break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
编译:
g++ opencv1.cpp -o cv1 `pkg-config --cflags --libs opencv`
运行:
./cv1
可能的问题:
1、运行后提示摄像头打开失败
到虚拟机设置,usb控制添加usb3.0
虚拟机选项,可移动设备添加HD摄像头,点击连接
2、编译错误
如果代码没问题,编译出错,那就是链库的问题
或者opencv安装没有成功
[这里有我编译安装opencv3.4.13的方法](https://editor.csdn.net/md/?articleId=116564938)