本文将介绍基于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;
}