Skip to content

Instantly share code, notes, and snippets.

@snim2
Created December 13, 2009 00:00
Show Gist options
  • Save snim2/255151 to your computer and use it in GitHub Desktop.
Save snim2/255151 to your computer and use it in GitHub Desktop.
Display the output of a webcam using Python and Pygame
import pygame
import pygame.camera
from pygame.locals import *
DEVICE = '/dev/video0'
SIZE = (640, 480)
FILENAME = 'capture.png'
def camstream():
pygame.init()
pygame.camera.init()
display = pygame.display.set_mode(SIZE, 0)
camera = pygame.camera.Camera(DEVICE, SIZE)
camera.start()
screen = pygame.surface.Surface(SIZE, 0, display)
capture = True
while capture:
screen = camera.get_image(screen)
display.blit(screen, (0,0))
pygame.display.flip()
for event in pygame.event.get():
if event.type == QUIT:
capture = False
elif event.type == KEYDOWN and event.key == K_s:
pygame.image.save(screen, FILENAME)
camera.stop()
pygame.quit()
return
if __name__ == '__main__':
camstream()
@shilan
Copy link

shilan commented Aug 26, 2020

Hi, Thanks for the code. Do you know how can I get try: stream = io.BytesIO() for _ in camera.capture_continuous( stream, format='jpeg', use_video_port=True): stream.seek(0) image = Image.open(stream).convert('RGB').resize((width, height), Image.ANTIALIAS)
this work with pygame? I mean I need to get a stream bytes and capture an image.

@snim2
Copy link
Author

snim2 commented Aug 26, 2020

I suspect this code is far too old to work with Python 3! PyGame now has a camera module though:

https://www.pygame.org/docs/tut/CameraIntro.html

@shilan
Copy link

shilan commented Aug 26, 2020

I am not a python expert but this code was written for picamera. However I need to do something similar with pygame.
I need to continously capture an image from camera stream.
https://github.com/tensorflow/examples/blob/master/lite/examples/image_classification/raspberry_pi/classify_picamera.py#L76

@snim2
Copy link
Author

snim2 commented Aug 26, 2020

The link I posted to the PyGame website contains an example of this.

@shilan
Copy link

shilan commented Aug 26, 2020

thanks :) I am reading it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment