如果您想一遍又一遍地重新启动视频(也就是循环播放),您可以通过使用 if 语句来确定帧数何时达到cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT),然后将帧数重置cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, num)为相同的值。我正在使用 OpenCV 2.4.9 和 Python 2.7.9,下面的示例不断为我循环播放视频。
import cv2
cap = cv2.VideoCapture('path/to/video')
frame_counter = 0
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
frame_counter += 1
#If the last frame is reached, reset the capture and the frame_counter
if frame_counter == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
frame_counter = 0 #Or whatever as long as it is the same as next line
cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, 0)
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)
它还可以重新捕获视频而不是重置帧数:
if frame_counter == cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT):
frame_counter = 0
cap = cv2.VideoCapture(video_name)
Run Code Online (Sandbox Code Playgroud)
关闭当前捕获并再次打开:
// play video in a loop
while (1)
{
CvCapture *capture = cvCaptureFromAVI("video.avi");
if(!capture)
{
printf("!!! cvCaptureFromAVI failed (file not found?)\n");
return -1;
}
IplImage* frame = NULL;
char key = 0;
while (key != 'q')
{
frame = cvQueryFrame(capture);
if (!frame)
{
printf("!!! cvQueryFrame failed: no frame\n");
break;
}
cvShowImage("window", frame);
key = cvWaitKey(10);
}
cvReleaseImage(&frame);
cvReleaseCapture(&capture);
}
Run Code Online (Sandbox Code Playgroud)
此代码不完整且未经测试。它仅用于说明目的。
| 归档时间: |
|
| 查看次数: |
21974 次 |
| 最近记录: |