PyGameExamplesAndAnswers

StackOverflow            reply.it reply.it


Camera and Video

Camera

Related Stack Overflow questions:

📁 Minimal example - OpenCV Camera capture

📁 Minimal example - Camera capture (pygame.camera)

📁 Minimal example - OpenCV Camera capture and release

The pygame.camera is only supported on linux:

Pygame currently supports only Linux and v4l2 cameras.

An alternative solution is to use the OpenCV VideoCapture. Install OpenCV for Python (cv2) (see opencv-python).

Opens a camera for video capturing:

capture = cv2.VideoCapture(0)

Grabs a camera frame:

success, camera_image = capture.read()

Convert the camera frame to a pygame.Surface object using pygame.image.frombuffer:

camera_surf = pygame.image.frombuffer(camera_image.tobytes(), camera_image.shape[1::-1], "BGR")

Video

Related Stack Overflow questions:

📁 Minimal example - Play video with MoviePy

📁 Minimal example - Play video

The pygame.movie is deprecated and not longer supported.

If you only want to show the video you can use MoviePy (see also How to be efficient with MoviePy):

import pygame
import moviepy.editor

pygame.init()
video = moviepy.editor.VideoFileClip("video.mp4")
video.preview()
pygame.quit()

An alternative solution is to use the OpenCV VideoCapture. Install OpenCV for Python (cv2) (see opencv-python). However, it should be mentioned that cv2.VideoCapture does not provide a way to read the audio from the video file. This is only a solution to view the video but no audio is played.

Opens a camera for video capturing:

video = cv2.VideoCapture("video.mp4")

Get the frames per second form the VideoCapture object:

fps = video.get(cv2.CAP_PROP_FPS)

Create a pygame.time.Clock:

clock = pygame.time.Clock()

Grabs a video frame and limit the frames per second in the application loop:

clock.tick(fps)
success, video_image = video.read()

Convert the camera frame to a pygame.Surface object using pygame.image.frombuffer:

video_surf = pygame.image.frombuffer(video_image.tobytes(), video_image.shape[1::-1], "BGR")