基于OpenCV实现视频的循环播放

本文将介绍基于OpenCV实现视频的循环播放。

有以下三个步骤:

  • 首先设置一个frame的设置参数frame_counter,值为0
  • 在读帧时间,将每次加一
  • 当 frame_counter 达到视频总帧数时,将当前的帧设置为 0

视频总帧数:CAP_PROP_FRAME_COUNT
设置当前的帧:CAP_PROP_POS_FRAMES

VideoCaptureProperties通用属性标识符参考地址

1.Python+OpenCV实现

import cv2

cap = cv2.VideoCapture("001.mp4")
frame_counter = 0

while (cap.isOpened()):
   ret, frame = cap.read()

   frame_counter += 1
   if frame_counter == int(cap.get(cv2.CAP_PROP_FRAME_COUNT)):
      frame_counter = 0
      cap.set(cv2.CAP_PROP_POS_FRAMES, 0)

   cv2.imshow("frame", frame)
   key = cv2.waitKey(1)
   # ESC
   if key == 27:
      break
cap.release()
cv2.destroyAllWindows()

2.C++ + OpenCV实现

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

int main() {
 
    cv::Mat frame;
    cv::VideoCapture cap("001.mp4");   
      
    int frame_counter = 0;
    while (true)
    {
      cap >> frame;
      if (!frame.data)
      {
         printf("Image not loaded");
         return -1;
      }
      
      frame_counter += 1;
      if (frame_counter == int(cap.get(cv::CAP_PROP_FRAME_COUNT))){
          frame_counter = 0;
          cap.set(cv::CAP_PROP_POS_FRAMES, 0);
      }

      cv::imshow("demo", frame);
      char(key)=(char)cv::waitKey(1);
      if(key==27)
          break;
     }

 
    return 0;
}

参考目录

https://medium.com/ching-i/%E5%BD%B1%E7%89%87%E6%8C%81%E7%BA%8C%E6%92%AD%E6%94%BE-python-c-3e0cfdd39269

上一篇:image “pyimage2“ doesn‘t exist


下一篇:Python中的魔法方法