当前位置: 首页 > article >正文

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. 参考资料

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.cpp

1 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.py

2 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 print
    int 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 information
 
  fps = int(vid_capture.get(5))
  print("Frame Rate : ",fps,"frames per second")  
 
  # Get frame count
  frame_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 matrix
        Mat frame;
        // Initialize a boolean to check if frames are there or not
        bool isSuccess = vid_capture.read(frame);
        // If frames are present, show it
        if(isSuccess == true)
        {
            //display frames
            imshow("Frame", frame);
        }
 
        // If frames are not there, close it
        if (isSuccess == false)
        {
            cout << "Video camera is disconnected" << endl;
            break;
        }        
//wait 20 ms between successive frames and break the loop if key q is pressed
        int 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 frame
 
  ret, frame = vid_capture.read()
  if ret == True:
    cv2.imshow('Frame',frame)
    k = cv2.waitKey(20)
    # 113 is ASCII code for q key
    if k == 113:
      break
  else:
    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.cpp

2 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.py

2 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.cpp

0 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.py

2 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.cpp

0 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.py

2 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 matrix
        Mat frame;
 
          // Initialize a boolean to check if frames are there or not
        bool isSuccess = vid_capture.read(frame);
 
        // If frames are not there, close it
        if (isSuccess == false)
        {
            cout << "Stream disconnected" << endl;
            break;
        }
 
 
        // If frames are present
        if(isSuccess == true)
        {
            //display frames
            output.write(frame);
                  // display frames
                  imshow("Frame", frame);
 
                  // wait for 20 ms between successive frames and break        
                  // the loop if key q is pressed
                  int 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 frame
 
    ret, frame = vid_capture.read()
    if ret == True:
           # Write the frame to the output files
           output.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.cpp

1 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.py

2 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定制化安装


http://www.kler.cn/a/232237.html

相关文章:

  • [GXYCTF2019]BabyUpload--详细解析
  • 路漫漫其修远兮,吾将上下而求索---第一次使用github的过程记录和个人感受
  • C/C++静态库引用过程中出现符号未定义的处理方式
  • Android Osmdroid + 天地图 (二)
  • shell编程之变量与引用
  • AI 写作(九)实战项目二:智能新闻报道(9/10)
  • 【龙年大礼】| 2023中国开源年度报告!
  • 大模型2024规模化场景涌现,加速云计算走出第二增长曲线
  • 从Unity到Three.js(安装启动)
  • STM32输出PWM波控制180°舵机
  • VSCode 文件夹增加右键打开
  • 图数据库neo4j入门
  • ChatGPT在肾脏病学领域的专业准确性评估
  • (delphi11最新学习资料) Object Pascal 学习笔记---第4章第2.5节(重载和模糊调用)
  • Linux学习
  • C#调用WechatOCR.exe实现本地OCR文字识别
  • PostgreSQL 与 MySQL 相比,优势何在?
  • 基于蒙特卡洛的电力系统可靠性分析matlab仿真,对比EDNS和LOLP
  • 服务器性能监控管理方法及工具
  • 登山 ——最长上升子序列
  • 第9章 SpringBoot综合项目实战——个人博客系统
  • @PostMapping/ @GetMapping等请求格式
  • JavaScript基础第五天
  • vue使用Mars3d弹框嵌套video视频/实时视频(m3u8)使用hls.js
  • 实例分割论文阅读之:《Mask Transfiner for High-Quality Instance Segmentation》
  • ubuntu系统下c++ cmakelist vscode debug(带传参的debug)的详细示例