From Pygame Tutorials Camera Module Introduction:
Capturing a Live Stream The rest of this tutorial will be based around
capturing a live stream of images. For this, we will be using the
class below. As described, it will simply blit a constant stream of
camera frames to the screen, effectively showing live video. It is
basically what you would expect, looping get_image(), blitting to the
display surface, and flipping it. For performance reasons, we will be
supplying the camera with the same surface to use each time.
class Capture(object):
def __init__(self):
self.size = (640,480)
# create a display surface. standard pygame stuff
self.display = pygame.display.set_mode(self.size, 0)
# this is the same as what we saw before
self.clist = pygame.camera.list_cameras()
if not self.clist:
raise ValueError("Sorry, no cameras detected.")
self.cam = pygame.camera.Camera(self.clist[0], self.size)
self.cam.start()
# create a surface to capture to. for performance purposes
# bit depth is the same as that of the display surface.
self.snapshot = pygame.surface.Surface(self.size, 0, self.display)
def get_and_flip(self):
# if you don't want to tie the framerate to the camera, you can check
# if the camera has an image ready. note that while this works
# on most cameras, some will never return true.
if self.cam.query_image():
self.snapshot = self.cam.get_image(self.snapshot)
# blit it to the display surface. simple!
self.display.blit(self.snapshot, (0,0))
pygame.display.flip()
def main(self):
going = True
while going:
events = pygame.event.get()
for e in events:
if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
# close the camera safely
self.cam.stop()
going = False
self.get_and_flip()
Since get_image() is a blocking call that could take quite a bit of
time on a slow camera, this example uses query_image() to see if the
camera is ready. This allows you to separate the framerate of your
game from that of your camera. It is also possible to have the camera
capturing images in a separate thread, for approximately the same
performance gain, if you find that your camera does not support the
query_image() function correctly.