ubuntu22.04@laptop OpenCV Get Started: 002_reading_writing_videos

2024-02-13 16:52

本文主要是介绍ubuntu22.04@laptop OpenCV Get Started: 002_reading_writing_videos,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

ubuntu22.04@laptop OpenCV Get Started: 002_reading_writing_videos

  • 1. 源由
  • 2. Read/Display/Write应用Demo
  • 3 video_read_from_file
    • 3.1 C++应用Demo
    • 3.2 Python应用Demo
    • 3.3 重点过程分析
      • 3.3.1 读取视频文件
      • 3.3.2 读取文件信息
      • 3.3.3 帧读取&显示
  • 4 video_read_from_image_sequence
    • 4.1 C++应用Demo
    • 4.2 Python应用Demo
    • 4.3 重点过程分析
  • 5 video_read_from_webcam
    • 5.1 C++应用Demo
    • 5.2 Python应用Demo
    • 5.3 重点过程分析
  • 6 video_write_from_webcam
    • 6.1 C++应用Demo
    • 6.2 Python应用Demo
    • 6.3 重点过程分析
      • 6.3.1 获取视频参数
      • 6.3.2 设置保存视频参数
      • 6.3.3 保存视频文件
  • 7 video_write_to_file
    • 7.1 C++应用Demo
    • 7.2 Python应用Demo
    • 7.3 重点过程分析
  • 8. 总结
  • 9. 参考资料
  • 10. 补充

1. 源由

在OpenCV中对视频的读写操作与图像的读写操作非常相似。视频不过是一系列通常被称为帧的图像。所以,所需要做的就是在视频序列中的所有帧上循环,然后一次处理一帧。

接下来研读下:

  1. Read/Display/Write视频文件
  2. Read/Display/Write系列图片
  3. Read/Display/Write网络摄像头

2. Read/Display/Write应用Demo

002_reading_writing_videos是OpenCV读写、显示视频文件例程。

确认OpenCV安装路径:

$ find /home/daniel/ -name "OpenCVConfig.cmake"
/home/daniel/OpenCV/installation/opencv-4.9.0/lib/cmake/opencv4/
/home/daniel/OpenCV/opencv/build/OpenCVConfig.cmake
/home/daniel/OpenCV/opencv/build/unix-install/OpenCVConfig.cmake$ export OpenCV_DIR=/home/daniel/OpenCV/installation/opencv-4.9.0/lib/cmake/opencv4/

3 video_read_from_file

3.1 C++应用Demo

C++应用Demo工程结构:

002_reading_writing_videos/CPP/video_read_from_file$ tree .
.
├── CMakeLists.txt
├── Resources
│   └── Cars.mp4
└── video_read_from_file.cpp1 directory, 3 files

C++应用Demo工程编译执行:

$ cd video_read_from_file
$ mkdir build
$ cd build
$ cmake ..
$ cmake --build . --config Release
$ cd ..
$ ./build/video_read_from_file

3.2 Python应用Demo

Python应用Demo工程结构:

002_reading_writing_videos/Python$ tree . -L 2
.
├── requirements.txt
├── Resources
│   ├── Cars.mp4
│   └── Image_sequence
├── video_read_from_file.py
├── video_read_from_image_sequence.py
├── video_read_from_webcam.py
├── video_write_from_webcam.py
└── video_write_to_file.py2 directories, 7 files

Python应用Demo工程执行:

$ workoncv-4.9.0
$ python video_read_from_file.py

3.3 重点过程分析

3.3.1 读取视频文件

  • VideoCapture(path, apiPreference)

C++:

# Create a video capture object, in this case we are reading the video from a file
VideoCapture vid_capture("Resources/Cars.mp4");

Python:

# Create a video capture object, in this case we are reading the video from a file
vid_capture = cv2.VideoCapture('Resources/Cars.mp4')

3.3.2 读取文件信息

  • vid_capture.isOpened()
  • vid_capture.get()

C++:

if (!vid_capture.isOpened()){cout << "Error opening video stream or file" << endl;}
else{// Obtain fps and frame count by get() method and printint fps = vid_capture.get(5):cout << "Frames per second :" << fps;frame_count = vid_capture.get(7);cout << "Frame count :" << frame_count;}

Python:

if (vid_capture.isOpened() == False):print("Error opening the video file")
else:# Get frame rate informationfps = int(vid_capture.get(5))print("Frame Rate : ",fps,"frames per second")  # Get frame countframe_count = vid_capture.get(7)print("Frame count : ", frame_count)

3.3.3 帧读取&显示

  • vid_capture.read()
  • cv2.imshow()

C++:

while (vid_capture.isOpened())
{// Initialize frame matrixMat frame;// Initialize a boolean to check if frames are there or notbool isSuccess = vid_capture.read(frame);// If frames are present, show itif(isSuccess == true){//display framesimshow("Frame", frame);}// If frames are not there, close itif (isSuccess == false){cout << "Video camera is disconnected" << endl;break;}        
//wait 20 ms between successive frames and break the loop if key q is pressedint key = waitKey(20);if (key == 'q'){cout << "q key is pressed by the user. Stopping the video" << endl;break;}}

Python:

while(vid_capture.isOpened()):# vCapture.read() methods returns a tuple, first element is a bool # and the second is frameret, frame = vid_capture.read()if ret == True:cv2.imshow('Frame',frame)k = cv2.waitKey(20)# 113 is ASCII code for q keyif k == 113:breakelse:break

4 video_read_from_image_sequence

4.1 C++应用Demo

C++应用Demo工程结构:

002_reading_writing_videos/CPP/video_read_from_image_sequence$ tree . -L 2
.
├── CMakeLists.txt
├── Resources
│   └── Image_Sequence
└── video_read_from_image_sequence.cpp2 directories, 2 files

C++应用Demo工程编译执行:

$ cd video_read_from_image_sequence
$ mkdir build
$ cd build
$ cmake ..
$ cmake --build . --config Release
$ cd ..
$ ./build/video_read_is

4.2 Python应用Demo

Python应用Demo工程结构:

002_reading_writing_videos/Python$ tree . -L 2
.
├── requirements.txt
├── Resources
│   ├── Cars.mp4
│   └── Image_sequence
├── video_read_from_file.py
├── video_read_from_image_sequence.py
├── video_read_from_webcam.py
├── video_write_from_webcam.py
└── video_write_to_file.py2 directories, 7 files

Python应用Demo工程执行:

$ workoncv-4.9.0
$ python video_read_from_image_sequence.py

4.3 重点过程分析

读取系列照片文件

  • VideoCapture(path, apiPreference)

C++:

VideoCapture vid_capture("Resources/Image_sequence/Cars%04d.jpg");

Python:

vid_capture = cv2.VideoCapture('Resources/Image_sequence/Cars%04d.jpg')

注:Cars%04d.jpg: Cars0001.jpg, Cars0002.jpg, Cars0003.jpg, etc

5 video_read_from_webcam

5.1 C++应用Demo

C++应用Demo工程结构:

002_reading_writing_videos/CPP/video_read_from_webcam$ tree .
.
├── CMakeLists.txt
└── video_read_from_webcam.cpp0 directories, 2 files

C++应用Demo工程编译执行:

$ cd video_read_from_webcam
$ mkdir build
$ cd build
$ cmake ..
$ cmake --build . --config Release
$ cd ..
$ ./build/video_read_from_webcam

5.2 Python应用Demo

Python应用Demo工程结构:

002_reading_writing_videos/Python$ tree . -L 2
.
├── requirements.txt
├── Resources
│   ├── Cars.mp4
│   └── Image_sequence
├── video_read_from_file.py
├── video_read_from_image_sequence.py
├── video_read_from_webcam.py
├── video_write_from_webcam.py
└── video_write_to_file.py2 directories, 7 files

Python应用Demo工程执行:

$ workoncv-4.9.0
$ python video_read_from_webcam.py

5.3 重点过程分析

  • VideoCapture(path, apiPreference)

C++:

VideoCapture vid_capture(0);

Python:

vid_capture = cv2.VideoCapture(0)

注:cv2.CAP_DSHOW不要使用,有时会导致vid_capture.isOpened()返回false。

6 video_write_from_webcam

6.1 C++应用Demo

C++应用Demo工程结构:

002_reading_writing_videos/CPP/video_write_from_webcam$ tree .
.
├── CMakeLists.txt
└── video_write_from_webcam.cpp0 directories, 2 files

C++应用Demo工程编译执行:

$ cd video_write_from_webcam
$ mkdir build
$ cd build
$ cmake ..
$ cmake --build . --config Release
$ cd ..
$ ./build/video_write_from_webcam

6.2 Python应用Demo

Python应用Demo工程结构:

002_reading_writing_videos/Python$ tree . -L 2
.
├── requirements.txt
├── Resources
│   ├── Cars.mp4
│   └── Image_sequence
├── video_read_from_file.py
├── video_read_from_image_sequence.py
├── video_read_from_webcam.py
├── video_write_from_webcam.py
└── video_write_to_file.py2 directories, 7 files

Python应用Demo工程执行:

$ workoncv-4.9.0
$ python video_write_from_webcam.py

6.3 重点过程分析

6.3.1 获取视频参数

  • vid_capture.get()

C++:

// Obtain frame size information using get() method
Int frame_width = static_cast<int>(vid_capture.get(3));
int frame_height = static_cast<int>(vid_capture.get(4));
Size frame_size(frame_width, frame_height);
int fps = 20;

Python:

# Obtain frame size information using get() method
frame_width = int(vid_capture.get(3))
frame_height = int(vid_capture.get(4))
frame_size = (frame_width,frame_height)
fps = 20

6.3.2 设置保存视频参数

  • VideoWriter(filename, apiPreference, fourcc, fps, frameSize[, isColor])
  • filename: pathname for the output video file
  • apiPreference: API backends identifier
  • fourcc: 4-character code of codec, used to compress the frames fourcc
  • fps: Frame rate of the created video stream
  • frame_size: Size of the video frames
  • isColor: If not zero, the encoder will expect and encode color frames. Else it will work with grayscale frames (the flag is currently supported on Windows only).

C++:

//Initialize video writer object
VideoWriter output("Resources/output.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'),frames_per_second, frame_size);

Python:

# Initialize video writer object
output = cv2.VideoWriter('Resources/output_video_from_file.avi', cv2.VideoWriter_fourcc('M','J','P','G'), 20, frame_size)

保存视频文件格式可以选择:

  • AVI: cv2.VideoWriter_fourcc(‘M’,‘J’,‘P’,‘G’)
  • MP4: cv2.VideoWriter_fourcc(*‘XVID’)

6.3.3 保存视频文件

  • output.write()

C++:

while (vid_capture.isOpened())
{// Initialize frame matrixMat frame;// Initialize a boolean to check if frames are there or notbool isSuccess = vid_capture.read(frame);// If frames are not there, close itif (isSuccess == false){cout << "Stream disconnected" << endl;break;}// If frames are presentif(isSuccess == true){//display framesoutput.write(frame);// display framesimshow("Frame", frame);// wait for 20 ms between successive frames and break        // the loop if key q is pressedint key = waitKey(20);if (key == ‘q’){cout << "Key q key is pressed by the user. Stopping the video" << endl;break;}}}

Python:

while(vid_capture.isOpened()):# vid_capture.read() methods returns a tuple, first element is a bool # and the second is frameret, frame = vid_capture.read()if ret == True:# Write the frame to the output filesoutput.write(frame)else:print(‘Stream disconnected’)break

7 video_write_to_file

7.1 C++应用Demo

C++应用Demo工程结构:

002_reading_writing_videos/CPP/video_write_to_file$ tree -L 2
.
├── CMakeLists.txt
├── Resources
│   └── Cars.mp4
└── video_write_to_file.cpp1 directory, 4 files

C++应用Demo工程编译执行:

$ cd video_write_to_file
$ mkdir build
$ cd build
$ cmake ..
$ cmake --build . --config Release
$ cd ..
$ ./build/video_write_to_file

7.2 Python应用Demo

Python应用Demo工程结构:

002_reading_writing_videos/Python$ tree . -L 2
.
├── requirements.txt
├── Resources
│   ├── Cars.mp4
│   └── Image_sequence
├── video_read_from_file.py
├── video_read_from_image_sequence.py
├── video_read_from_webcam.py
├── video_write_from_webcam.py
└── video_write_to_file.py2 directories, 7 files

Python应用Demo工程执行:

$ workoncv-4.9.0
$ python video_write_to_file.py

7.3 重点过程分析

整合了以下章节重点过程:

    1. video_read_from_file
    1. video_write_from_webcam

8. 总结

主要通过以下三个函数API实现:

  1. videoCapture():获取数据源
  2. read():读取数据
  3. imshow():显示图像
  4. write():保存数据

其他API函数:

  • isOpened() - 数据源打开是否成功过
  • get() - 获取数据源相关信息

9. 参考资料

【1】ubuntu22.04@laptop OpenCV Get Started
【2】ubuntu22.04@laptop OpenCV安装
【3】ubuntu22.04@laptop OpenCV定制化安装

10. 补充

学习是一种过程,这里关于《ubuntu22.04@laptop OpenCV Get Started》的记录也是过程。因此,很多重复的代码或者注释,就不会展开讨论,甚至提及。

有兴趣了解更多的朋友,请从[《ubuntu22.04@laptop OpenCV Get Started》](ubuntu22.04@laptop OpenCV Get Started)开始,一个章节一个章节的了解,循序渐进。

这篇关于ubuntu22.04@laptop OpenCV Get Started: 002_reading_writing_videos的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/706083

相关文章

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

opencv 滚动条

参数介绍:createTrackbar( trackbarname , "hello" , &alpha_slider ,alpha_max ,  on_trackbar )  ;在标签中显示的文字(提示滑动条的用途) TrackbarName创建的滑动条要放置窗体的名字 “hello”滑动条的取值范围从 0 到 alpha_max (最小值只能为 zero).滑动后的值存放在

android-opencv-jni

//------------------start opencv--------------------@Override public void onResume(){ super.onResume(); //通过OpenCV引擎服务加载并初始化OpenCV类库,所谓OpenCV引擎服务即是 //OpenCV_2.4.3.2_Manager_2.4_*.apk程序包,存

JavaSE-易错题集-002

1. 下面有关java基本类型的默认值和取值范围,说法错误的是? A 字节型的类型默认值是0,取值范围是-2^7—2^7-1 B boolean类型默认值是false,取值范围是true\false C 字符型类型默认是0,取值范围是-2^15 —2^15-1 D long类型默认是0,取值范围是-2^63—2^63-1 答案:C 题解:注意字符型(char) char 占16位,

OpenCV结构分析与形状描述符(11)椭圆拟合函数fitEllipse()的使用

操作系统:ubuntu22.04 OpenCV版本:OpenCV4.9 IDE:Visual Studio Code 编程语言:C++11 算法描述 围绕一组2D点拟合一个椭圆。 该函数计算出一个椭圆,该椭圆在最小二乘意义上最好地拟合一组2D点。它返回一个内切椭圆的旋转矩形。使用了由[90]描述的第一个算法。开发者应该注意,由于数据点靠近包含的 Mat 元素的边界,返回的椭圆/旋转矩形数据

树莓派5_opencv笔记27:Opencv录制视频(无声音)

今日继续学习树莓派5 8G:(Raspberry Pi,简称RPi或RasPi)  本人所用树莓派5 装载的系统与版本如下:  版本可用命令 (lsb_release -a) 查询: Opencv 与 python 版本如下: 今天就水一篇文章,用树莓派摄像头,Opencv录制一段视频保存在指定目录... 文章提供测试代码讲解,整体代码贴出、测试效果图 目录 阶段一:录制一段

Verybot之OpenCV应用三:色标跟踪

下面的这个应用主要完成的是Verybot跟踪色标的功能,识别部分还是居于OpenCV编写,色标跟踪一般需要将图像的颜色模式进行转换,将RGB转换为HSV,因为对HSV格式下的图像进行识别时受光线的影响比较小,但是也有采用RGB模式来进行识别的情况,这种情况一般光线条件比较固定,背景跟识别物在颜色上很容易区分出来。         下面这个程序的流程大致是这样的:

Verybot之OpenCV应用二:霍夫变换查找圆

其实我是想通过这个程序来测试一下,OpenCV在Verybot上跑得怎么样,霍夫变换的原理就不多说了,下面是程序: #include "cv.h"#include "highgui.h"#include "stdio.h"int main(int argc, char** argv){cvNamedWindow("vedio",0);CvCapture* capture;i

Verybot之OpenCV应用一:安装与图像采集测试

在Verybot上安装OpenCV是很简单的,只需要执行:         sudo apt-get update         sudo apt-get install libopencv-dev         sudo apt-get install python-opencv         下面就对安装好的OpenCV进行一下测试,编写一个通过USB摄像头采

Ubuntu22.04回退系统内核

文章目录 起因回退操作卸载内核禁止内核升级 起因 最近因为系统内核自动升级,导致显卡驱动检测不到,炼丹环境被破坏。无奈只能重装驱动,于是跟着手册操作发现驱动要求的是内核版本是5.15.0-25-generic,而我通过uname -r发现这时候的内核版本是6.8.0-40-generic,看来只能回退了。 我搜索了网上很多的文章,没有一篇文章能够完全解决这个问题,所以在我多次尝