我正在尝试从使用 pygame 加载的视频中提取特定帧
在这个问题给出了这个例子
import pygame
import cv2
video = cv2.VideoCapture("video.mp4")
success, video_image = video.read()
fps = video.get(cv2.CAP_PROP_FPS)
window = pygame.display.set_mode(video_image.shape[1::-1])
clock = pygame.time.Clock()
run = success
while run:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
success, video_image = video.read()
if success:
video_surf = pygame.image.frombuffer(
video_image.tobytes(), video_image.shape[1::-1], "BGR")
else:
run = False
window.blit(video_surf, (0, 0))
pygame.display.flip()
pygame.quit()
exit()
然而,这只是迭代视频中的所有帧。 有没有办法通过鼠标单击获取当前帧?
当我尝试获取第 15 帧时
video_image[15].tobytes()
我得到 TypeError: argument 2 must be sequence of length 2, not 1
有没有办法通过鼠标点击获取当前帧?
当
save_frame
事件发生时,设置 MOUSEBUTTONDOWN
变量。使用 pygame.image.save
: 将框架保存到文件中
frame_count = 0
run = success
while run:
clock.tick(fps)
save_frame = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.MOUSEBUTTONDOWN:
save_frame = True
success, video_image = video.read()
if success:
video_surf = pygame.image.frombuffer(
video_image.tobytes(), video_image.shape[1::-1], "BGR")
if save_frame:
pygame.image.save(video_surf, f"frame_{frame_count}.png")
else:
run = False
window.blit(video_surf, (0, 0))
pygame.display.flip()
frame_count += 1