0% found this document useful (0 votes)
3 views

Pygame Tutorials - Camera Module Introduction — pygame v2.0.0.dev5 documentation

This document is an introduction to the camera module in Pygame, detailing how to capture images and streams from connected cameras. It provides code examples for initializing the camera, capturing images, and performing basic computer vision tasks such as color thresholding. The tutorial emphasizes the experimental nature of the camera module and its compatibility with various platforms, focusing primarily on native support for Linux using v4l2.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Pygame Tutorials - Camera Module Introduction — pygame v2.0.0.dev5 documentation

This document is an introduction to the camera module in Pygame, detailing how to capture images and streams from connected cameras. It provides code examples for initializing the camera, capturing images, and performing basic computer vision tasks such as color thresholding. The tutorial emphasizes the experimental nature of the camera module and its compatibility with various platforms, focusing primarily on native support for Linux using v4l2.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

15/04/2020 Pygame Tutorials - Camera Module Introduction — pygame v2.0.0.

dev5 documentation

Accueil Pygame || Contenu de l'aide || Index de référence


chercher
Trucs les plus utiles : Couleur |
affichage | dessiner | événement | police | image | clé | locaux | mélangeur |
souris | Rect | Surface | temps | musique | pygame
Trucs avancés : curseurs | joystick | masque | sprite | transformer |
documentation pygame BufferProxy | freetype | gfxdraw | midi | Superposition | PixelArray |
pixelcopy | sndarray | surfarray | math
Autre : appareil photo | cdrom | exemples | débris | tests | toucher | version

Introduction au module de caméra


Auteur: par Nirav Patel
Contact: nrp @ eclecti . cc
Pygame 1.9 est livré avec un support pour les caméras d'interface, vous permettant de capturer des
images fixes, de regarder des flux en direct et de faire une vision par ordinateur simple. Ce didacticiel
couvrira tous ces cas d'utilisation, fournissant des exemples de code sur lesquels vous pouvez baser votre
application ou votre jeu. Vous pouvez vous référer à l' API complète.reference documentation
Remarque: Depuis Pygame 1.9, le module de caméra offre une prise en charge native des caméras qui
utilisent la v4l2 sous Linux. Il existe un support pour d'autres plates-formes via Videocapture ou OpenCV,
mais ce guide se concentrera sur le module natif. La plupart du code sera valide pour d'autres plates-
formes, mais certaines choses comme les contrôles ne fonctionneront pas. Le module est également
marqué comme EXPERIMENTAL , ce qui signifie que l'API pourrait changer dans les versions ultérieures.

Importer et initialiser
import pygame
import pygame.camera
from pygame.locals import *

pygame.init()
pygame.camera.init()

Comme le module de caméra est facultatif, il doit être importé et initialisé manuellement comme indiqué ci-
dessus.

Capturer une seule image


Maintenant, nous allons passer en revue le cas le plus simple d'ouvrir une caméra et de capturer un cadre
en tant que surface. Dans l'exemple ci-dessous, nous supposons qu'il y a une caméra sur / dev / video0 sur
l'ordinateur et l'initialisons avec une taille de 640 x 480. La surface appelée image est celle que la caméra
voyait lorsque get_image () a été appelée.
cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
image = cam.get_image()

Liste des caméras connectées


Vous vous demandez peut-être, si nous ne connaissons pas le chemin exact de la caméra? Nous pouvons
demander au module de fournir une liste de caméras connectées à l'ordinateur et initialiser la première
caméra de la liste.
camlist = pygame.camera.list_cameras()
if camlist:
cam = pygame.camera.Camera(camlist[0],(640,480))

https://www.pygame.org/docs/tut/CameraIntro.html 1/6
15/04/2020 Pygame Tutorials - Camera Module Introduction — pygame v2.0.0.dev5 documentation

Utilisation des commandes de la caméra


La plupart des appareils photo prennent en charge des commandes telles que retourner l'image et modifier
la luminosité. set_controls () et get_controls () peuvent être utilisés à tout moment après avoir utilisé start ().
cam.set_controls(hflip = True, vflip = False)
print camera.get_controls()

Capture d'un flux en direct


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.

Basic Computer Vision


By using the camera, transform, and mask modules, pygame can do some basic computer vision.

Colorspaces

https://www.pygame.org/docs/tut/CameraIntro.html 2/6
15/04/2020 Pygame Tutorials - Camera Module Introduction — pygame v2.0.0.dev5 documentation

When initializing a camera, colorspace is an optional parameter, with 'RGB', 'YUV', and 'HSV' as the
possible choices. YUV and HSV are both generally more useful for computer vision than RGB, and allow
you to more easily threshold by color, something we will look at later in the tutorial.
self.cam = pygame.camera.Camera(self.clist[0], self.size, "RGB")

self.cam = pygame.camera.Camera(self.clist[0], self.size, "YUV")

self.cam = pygame.camera.Camera(self.clist[0], self.size, "HSV")

Thresholding
Using the threshold() function from the transform module, one can do simple green screen like effects, or
isolate specifically colored objects in a scene. In the below example, we threshold out just the green tree
and make the rest of the image black. Check the reference documentation for details on the threshold
function.

https://www.pygame.org/docs/tut/CameraIntro.html 3/6
15/04/2020 Pygame Tutorials - Camera Module Introduction — pygame v2.0.0.dev5 documentation

self.thresholded = pygame.surface.Surface(self.size, 0, self.display)


self.snapshot = self.cam.get_image(self.snapshot)
pygame.transform.threshold(self.thresholded,self.snapshot,(0,255,0),(90,170,170),(0,0,0),2)

Of course, this is only useful if you already know the exact color of the object you are looking for. To get
around this and make thresholding usable in the real world, we need to add a calibration stage where we
identify the color of an object and use it to threshold against. We will be using the average_color() function
of the transform module to do this. Below is an example calibration function that you could loop until an
event like a key press, and an image of what it would look like. The color inside the box will be the one that
is used for the threshold. Note that we are using the HSV colorspace in the below images.
def calibrate(self):
# capture the image
self.snapshot = self.cam.get_image(self.snapshot)
# blit it to the display surface
self.display.blit(self.snapshot, (0,0))
# make a rect in the middle of the screen
crect = pygame.draw.rect(self.display, (255,0,0), (145,105,30,30), 4)
# get the average color of the area inside the rect
self.ccolor = pygame.transform.average_color(self.snapshot, crect)
# fill the upper left corner with that color
self.display.fill(self.ccolor, (0,0,50,50))
pygame.display.flip()

pygame.transform.threshold(self.thresholded,self.snapshot,self.ccolor,(30,30,30),(0,0,0),2)

https://www.pygame.org/docs/tut/CameraIntro.html 4/6
15/04/2020 Pygame Tutorials - Camera Module Introduction — pygame v2.0.0.dev5 documentation

You can use the same idea to do a simple green screen/blue screen, by first getting a background image
and then thresholding against it. The below example just has the camera pointed at a blank white wall in
HSV colorspace.
def calibrate(self):
# capture a bunch of background images
bg = []
for i in range(0,5):
bg.append(self.cam.get_image(self.background))
# average them down to one to get rid of some noise
pygame.transform.average_surfaces(bg,self.background)
# blit it to the display surface
self.display.blit(self.background, (0,0))
pygame.display.flip()

pygame.transform.threshold(self.thresholded,self.snapshot,(0,255,0),(30,30,30),(0,0,0),1,self.background)

Utilisation du module de masque


Les éléments ci-dessus sont excellents si vous souhaitez simplement afficher des images, mais avec le ,
vous pouvez également utiliser un appareil photo comme périphérique d'entrée pour un jeu. Par exemple,
https://www.pygame.org/docs/tut/CameraIntro.html 5/6
15/04/2020 Pygame Tutorials - Camera Module Introduction — pygame v2.0.0.dev5 documentation

pour revenir à l'exemple du seuillage d'un objet spécifique, nous pouvons trouver la position de cet objet et
l'utiliser pour contrôler un objet à l'écran.mask module
def get_and_flip(self):
self.snapshot = self.cam.get_image(self.snapshot)
# threshold against the color we got before
mask = pygame.mask.from_threshold(self.snapshot, self.ccolor, (30, 30, 30))
self.display.blit(self.snapshot,(0,0))
# keep only the largest blob of that color
connected = mask.connected_component()
# make sure the blob is big enough that it isn't just noise
if mask.count() > 100:
# find the center of the blob
coord = mask.centroid()
# draw a circle with size variable on the size of the blob
pygame.draw.circle(self.display, (0,255,0), coord, max(min(50,mask.count()/400),5))
pygame.display.flip()

Ceci est juste l'exemple le plus élémentaire. Vous pouvez suivre plusieurs gouttes de couleur différentes,
trouver les contours des objets, avoir une détection de collision entre la vie réelle et les objets de jeu,
obtenir l'angle d'un objet pour permettre un contrôle encore plus fin, et plus encore. S'amuser!

Modifier sur GitHub

documentation de pygame v2.0.0.dev5 » précédent | suivant | modules | indice

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

You might also like