0

I'm trying to extract a specific frame from a video loaded with pygame

In this question this example is given

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()

However this just iterates over all frames in the video. Is there a way to get the current frame on mouse click?

When I try to get for example the 15th frame video_image[15].tobytes() I get TypeError: argument 2 must be sequence of length 2, not 1

Ivan Yosifov
  • 59
  • 1
  • 6

1 Answers1

1

Is there a way to get the current frame on mouse click?

Set a save_frame variable when the the MOUSEBUTTONDOWN event occurse. Save the frame to a file with pygame.image.save:

farme_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
        if 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_{farme_count}.png")

    else:
        run = False
        
    window.blit(video_surf, (0, 0))
    pygame.display.flip()
    farme_count += 1
Rabbid76
  • 202,892
  • 27
  • 131
  • 174