在opencv中按指定键时是否可以倒带?我有以下内容,但它不倒带播放。
def run(self, filepath, fps, width, height, monochrome=False):
video_file = self.read_file(filepath)
previous_frame = None
while (video_file.isOpened()):
ret, frame = video_file.read()
if previous_frame is not None:
pass
previous_frame = frame
if ret:
frame = self.color(frame, monochrome)
final_frame = self.resolution(frame, width, height)
delaytime = self.frame_per_second(fps)
cv2.imshow('frame', final_frame)
key = cv2.waitKey(delaytime)
if key & 0xFF == ord("p"):
cv2.waitKey(234320)
if key & 0xFF == ord("r"):
cv2.set(cv2.CV_CAP_PROP_POS_FRAMES(2, previous_frame))
video_file.release()
cv2.destroyAllWindows()
上面的代码将其带到上一帧,但不播放。
最佳答案
理想的解决方案是设置视频暂停以实现倒带效果时需要播放的帧号。这可以通过video capture properties完成:
有用的示例可在“Jumping between frames in video files”上找到。
这是一个源代码示例,它会暂停视频并提供一些控制,使您可以倒退到上一帧或跳至零帧并重新启动视频:
import cv2
import sys
# load input video
cap = cv2.VideoCapture('TheMandalorian.mkv')
if (cap.isOpened() == False):
print("!!! Failed cap.isOpened()")
sys.exit(-1)
# retrieve the total number of frames
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# loop to read every frame of the video
while (cap.isOpened()):
# capture a frame
ret, frame = cap.read()
if ret == False:
print("!!! Failed cap.read()")
break
cv2.imshow('video', frame)
# check if 'p' was pressed and wait for a 'b' press
key = cv2.waitKey(int(frame_count/1000))
if (key & 0xFF == ord('p')):
# sleep here until a valid key is pressed
while (True):
key = cv2.waitKey(0)
# check if 'p' is pressed and resume playing
if (key & 0xFF == ord('p')):
break
# check if 'b' is pressed and rewind video to the previous frame, but do not play
if (key & 0xFF == ord('b')):
cur_frame_number = cap.get(cv2.CAP_PROP_POS_FRAMES)
print('* At frame #' + str(cur_frame_number))
prev_frame = cur_frame_number
if (cur_frame_number > 1):
prev_frame -= 1
print('* Rewind to frame #' + str(prev_frame))
cap.set(cv2.CAP_PROP_POS_FRAMES, prev_frame)
# check if 'r' is pressed and rewind video to frame 0, then resume playing
if (key & 0xFF == ord('r')):
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
break
# exit when 'q' is pressed to quit
elif (key & 0xFF == ord('q')):
break
# release resources
cap.release()
cv2.destroyAllWindows()
按键选项:
q
退出应用程序。 p
暂停。 p
可继续播放。 b
后退一帧。您必须按p
才能继续播放。 r
后退至第0帧并自动继续播放。