本想简单写个demo程序,读取摄像头的rtsp视频流,将最新帧保存为jpg图片传给AI程序进行识别,结果网上针对linux下c++版读取视频流保存图片的资料,凌乱且各种错误。现将踩坑后成功执行的流程和代码整理出来,供有需之人参考。
1.linux下配置opencv开发环境
- 安装必要的库
[compiler] sudo apt-get install build-essential
[required] sudo apt-get install cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
[optional] sudo apt-get install python-dev python-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev - 下载opencv源码
https://opencv.org/,这里下载最新的opencv-4.2.0.zip。 - 编译源码,并安装
解压后进入opencv-4.2.0目录,mkdir build,进入build目录,然后执行
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local ..
make # 开始编译,等待编译完成
sudo make install # 安装
2.读取视频流并保存图片
编写demo文件,包含opencv_demo.cpp、CMakeLists.txt两个文件。
1. CMakeLists.txt内容
cmake_minimum_required(VERSION 2.8)
add_definitions(-std=c++11)
project(demo)
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
add_executable(demo opencv_demo.cpp)
target_link_libraries(demo ${OpenCV_LIBS})
2. opencv_demo.cpp
#include <string>
#include <iostream>
#include <time.h>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
void Video_to_Image(Mat& frame);
int main()
{
//string filename = "Wildlife.wmv";
string filename = "rtsp://admin:12345@192.168.1.120/ch1/stream1";
Mat frame;
VideoCapture cap;
cap.open(filename);
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;
time_t start_time = time(NULL);
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);
// 每隔2s保存图片
time_t end_time = time(NULL);
if ((end_time - start_time) >=2)
{
cout << "2s capture" << endl;
Video_to_Image(frame);
start_time = time(NULL);
}
if (waitKey(5) >= 0)
break;
}
cap.release();
return 0;
}
void Video_to_Image(Mat& frame)
{
char image_name[PATH_MAX];
sprintf(image_name, "%s%s", "test_image", ".jpg");
imwrite(image_name, frame);
}
3. 编译执行
cmake .
make
./demo