OpenCV Python:重新启动视频



我是OpenCV和Python的新手,我正在尝试创建一个简单的程序,该程序将读取名为"SixtyFPS.mov"的视频文件,并在视频结束时重播视频。理想情况下,我希望连续播放视频。我无法在网上找到解决方案,但是我看到的大多数答案都涉及使用 cap.set(cv2。CAP_PROP_POS_FRAMES,1(或类似性质的东西,以便重置帧。如果有人可以向我解释如何使用cap.set功能以重新启动视频,将不胜感激。

# The video 'SixtyFPS.mov' was recorded on an iPhone 7 at 60 FPS
# The video has a length of roughly 4 seconds long and so the total number
# of frames should be ~240, however my number_of_frames variable is equal to 115
# I am looking for a way to restart the video once it has reached its end but 
# I have not yet discovered a good method for doing so. Any advice would be 
# greatly appreciated. I am using Python 3.6.4 and OpenCV 3.3.1
# I needed to rotate the video so that it would be viewed in portrait 
# orientation rather than landscape

import cv2
import numpy as np
# Load in the video
video_cap = cv2.VideoCapture('SixtyFPS.mov')
# display the total number of frames. Should be ~240 and not 115
number_of_frames = int(video_cap.get(cv2.CAP_PROP_FRAME_COUNT))
print("The total number of frames is: " + str(number_of_frames))
# Check if video opened successfully
if (video_cap.isOpened() == False):
    print("Error opening video file")
frame_counter = 0
# Read until video is completed
while(video_cap.isOpened()):
    # Capture frame-by-frame
    ret, frame = video_cap.read()
    if ret == True:
        frame_counter += 1
        # resize the window
        resized_vid = cv2.resize(frame, (720, 1280))
        # Convert the video to grayscale
        grayscale_vid = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        # Change the orientation from landscape to portrait by rotating
        (h, w) = grayscale_vid.shape[:2]
        center = (w / 2, h / 2)
        M = cv2.getRotationMatrix2D(center, 270, 1.0)
        rotated_video = cv2.warpAffine(grayscale_vid, M, (w, h))
        # Display the rotated video
        cv2.imshow('Pitch', rotated_video)
        # trying to restart the video when the frame_counter
        # reaches its maximum value of 110
        if frame_counter >= 110:
            # here is where I think I need to restart the video
            # by setting the current frame to zero 

        # Press Q on keyboard to exit
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    # Break the loop
    else: 
        break
# When everything done, release the video capture object
video_cap.release()
# Closes all the frames
cv2.destroyAllWindows()

这个问题发布已经有一段时间了,但以防万一有人偶然发现了这个答案,这个带有cap.set()的代码片段对我有用。我依赖于可以在这里(cpp(和这里(python(找到的文档。

import cv2
# Get video handle.
cap = cv2.VideoCapture("path/to/video")
if not cap.isOpened():
  print("Cannot initialize cap.")
  exit()
# Get length of the video.
video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# Initialize count.
count = 0
# Frames loop.
while True:
  # Check length of the video.
  if count == video_length:
    # Reset to the first frame. Returns bool.
    _ = cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
    count = 0
  
  # Get the frame.
  success, image = cap.read()
  if not success:
    print("Cannot read frame.")
    break
  # do something with the image.
  cv2.imshow("Frame", image)
  # Quit by pressing 'q'.
  if cv2.waitKey(1) & 0xFF == ord('q'):
    break
  count += 1
# Post loop.
cap.release()
cv2.destroyAllWindows()

我使用上述内容通过结合cap.get()cap.set()来回退一些n帧数。

这是将视频大小调整为480 x 800(高 x 宽(并循环播放的一般方法。

import cv2
# Change this path to your video location
path = "path_to_your_video"
cap = cv2.VideoCapture(path)
while True:
    ret, img = cap.read()
    if not ret:
        cap = cv2.VideoCapture(path)
        ret, img = cap.read()
    img = cv2.resize(img, (800, 480))
    cv2.imshow("Video", img)
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break
cap.release()
cv2.destroyAllWindows()

最新更新