I would like to blit images from webcam to a screen of pygame. I'm using OS X. I know pygame currently supports only Linux and v4l2 cameras,but,then how can we use webcam with pygame?
-
Can you somehow get a stream of .PNG imags, or the camera-input as a MPEG1 encoded video?– KingsleyJan 28, 2020 at 22:08
-
Thanks for your comment!I could solve this problem by getting images from webcam with OpenCV, and added some codes that follows– beginner koFeb 2, 2020 at 10:40
-
frame = np.rot90(frame)– beginner koFeb 2, 2020 at 10:44
-
frame = pygame.surfarray.make_surface(frame)– beginner koFeb 2, 2020 at 10:45
-
screen.blit(frame, (0,0))– beginner koFeb 2, 2020 at 10:45
Add a comment
|
1 Answer
import cv2
import pygame
import numpy as np
pygame.init()
pygame.display.set_caption("OpenCV camera stream on Pygame")
surface = pygame.display.set_mode([1280,720])
#0 Is the built in camera
cap = cv2.VideoCapture(0)
#Gets fps of your camera
fps = cap.get(cv2.CAP_PROP_FPS)
print("fps:", fps)
#If your camera can achieve 60 fps
#Else just have this be 1-30 fps
cap.set(cv2.CAP_PROP_FPS, 60)
while True:
surface.fill([0,0,0])
success, frame = cap.read()
if not success:
break
#for some reasons the frames appeared inverted
frame = np.fliplr(frame)
frame = np.rot90(frame)
# The video uses BGR colors and PyGame needs RGB
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
surf = pygame.surfarray.make_surface(frame)
for event in pygame.event.get():
if event.type == pygame.KEYUP:
background_color = red
surface.fill(background_color)
pygame.display.update
end_time = self.time()
# Show the PyGame surface!
surface.blit(surf, (0,0))
pygame.display.flip()
-
Im using OS X as well. OPENCV and pygame dont go well together Im trying to find a different alternative. Its not good cause its very choppy and I dont know why.– ElpupperJun 16, 2020 at 10:33