Summarize the basic read and write operations of OpenCV in C++ language.
Header imports and CMakeLists.txt
#include<opencv2/opencv.hpp>
#include<iostream>
Note that you need to introduce the namespace cv, otherwise you need to add cv:: when using open cv
using namespace cv;
CMakeLists.txt writes like this
CMAKE_MINIMUM_REQUIRED(VERSION 2.8.12)
PROJECT(hh_tsr_track)
SET(CMAKE_CXX_STANDARD 11)
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
add_executable(myopencv main.cpp)
target_link_libraries(myopencv ${OpenCV_LIBS})
picture reading
cv::Mat image = cv::imread("/home/xxx/image/abc.png");
picture save
//创建白色图片
Mat image = Mat(Size(1366, 768), CV_8UC3, Scalar(255, 255, 255));
imwrite("/home/xxx/image/white.png", image);
video reading
VideoCapture capture;
capture.open("/home/xxx/myvideo/abc.mp4");
if(!capture.isOpened()){
cout<<"Error! Cannot open video!"<<endl;
}
while (true){
Mat frame;
capture >> frame;
imshow("videodemo", frame);
waitKey(30);
}
//也可以这样
Mat frame;
while (capture.read(frame)) {
imshow("videodemo", frame);
writer.write(frame);
char c = waitKey(30);
waitKey(30);
}
//获取视频文件的一些信息
int width = capture.get(CV_CAP_PROP_FRAME_WIDTH); //帧宽度
int height = capture.get(CV_CAP_PROP_FRAME_HEIGHT); //帧高度
int totalFrames = capture.get(CV_CAP_PROP_FRAME_COUNT); //总帧数
int frameRate = capture.get(CV_CAP_PROP_FPS); //帧率
camera reading
VideoCapture capture(0);
if(!capture.isOpened()){
cout<<"Error! Cannot open camera!"<<endl;
}
while (true){
Mat frame;
capture >> frame;
imshow("camerademo", frame);
waitKey(30);
}
video writing
//注意 fourcc和文件名要匹配,('M', 'J', 'P', 'G')对应.avi,('X', 'V', 'I', 'D')对应.mp4
VideoWriter writer("/home/xxx/myvideo/output.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'),30, cv::Size(1366, 768));
for (int i = 0; i < 1000; ++i){
writer.write(frame);
//或者用<<写入
writer << frame;
}
writer.release();
Real-time picture display
imshow("demo", frame);
waitKey(30);
image zoom
Size dest_size = Size(1366, 768);
resize(original_image, resized_image, dest_size, 0, 0, INTER_AREA);