基于opencv的RTSP(rtsp)流读取和保存(C++可cmake编译-附带py方法)
因其工作需要使用C++读取rtsp流,本文将针对linux下c++版读取视频流保存视频,凌乱且各种错误。现将将其成功执行的流程和代码记录,顺带也写了一份python读取rtsp方法,供自己使用及有需之人参考。本文分三部分,第一部分呈现CMakeLists.txt与rtsp_video源码;第二部分插图给出使用方法;第三部分顺带给出python方法的源码。
一.CMakeLists.txt与rtsp_video源码
CMakeLists.txt
cmake_minimum_required(VERSION 2.6) project(rtsp) find_package( OpenCV REQUIRED ) include_directories( ${OpenCV_INCLUDE_DIRS} ) add_executable(rtsp_demo rtsp_video.cpp) target_link_libraries( rtsp_demo ${OpenCV_LIBS} )
rtsp_video.cpp
#include <iostream> #include <opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; int main() { std::string rtspPath = "rtsp://admin:Vrc123456@192.168.2.226:554"; VideoCapture cap; cap.open(rtspPath); if (!cap.isOpened()) { cout << "cannot open video!" << endl; return 0; } VideoWriter writer = VideoWriter("./rtsp-video.avi",//path and filename (int)cap.get(CAP_PROP_FOURCC), (int)cap.get(CAP_PROP_FPS), Size((int)cap.get(CAP_PROP_FRAME_WIDTH), (int)cap.get(CAP_PROP_FRAME_HEIGHT)), true//colorfull pic ); if (!writer.isOpened()) { cout << "create vedio failed!" << endl; return 0; } while (1) { cv::Mat frame; cap >> frame; if (frame.empty()) { cout << "frame is empty!" << endl; break; } cv::Mat img = frame; //cv::imshow("frame", img); writer<<img; //waitKey(1); } return 0; }
注:opencv安装参考网络方法
二.使用方法
步骤1:
打开rtsp_video.cpp文件修改流接口:
std::string rtspPath = "rtsp://admin:Vrc123456@192.168.2.226:554";
步骤2:
将整个文件夹传入需编译服务器,文件内容包括红框内容:
以下类似编译过程
步骤3:执行
cmake .
make
可出现rtsp_demo,以下红框
无需录视频,执行 ctrl+c 按键
保存视频为rtsp-video.avi
三.python方法的源码
import cv2 cap = cv2.VideoCapture('rtsp://admin:Vrc123456@192.168.2.226:554') fourcc = cv2.VideoWriter_fourcc(*'XVID') size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) out = cv2.VideoWriter('./rtsp_video.avi', fourcc,10.0, size) while True: ret, frame = cap.read() out.write(frame) cv2.imshow('frame', frame) cv2.waitKey(1) cap.release() out.release() cv2.destroyAllWindows()