Pygame 简明教程
Pygame - Using Camera Module
1.9.6 之前的早期版 Pygame 包含 pygame.camera 模块。该模块包含在游戏窗口捕获摄像头馈送并从中获取图像所需的功能。可以通过 list_cameras() 方法返回的列表枚举系统可用的摄像头设备。
Earlier versions of Pygame upto 1.9.6 contain pygame.camera module. This module contains functionality to capture camera feed on the game window and grab an image from it. The camera devices available to the system are enumerated in a list returned by list_cameras() method.
pygame.camera.list_cameras()
要初始化摄像头对象,请使用摄像头 ID、分辨率和格式参数。
To initialize a camera object, use camera id, resolution and format arguments.
pygame.camera.Camera(device, (width, height), format)
默认格式是 RGB。宽度和高度参数默认为 640x480。
The default format is RGB. Width and height parameters are by default 640x480.
摄像头模块在摄像头类中定义了下列方法。
The camera module has following methods defined in Camera class.
pygame.camera.Camera.start() |
opens, initializes, and starts capturing |
pygame.camera.Camera.stop() |
stops, uninitializes, and closes the camera |
pygame.camera.Camera.get_controls() |
gets current values of user controls |
pygame.camera.Camera.set_controls() |
changes camera settings if supported by the camera |
pygame.camera.Camera.get_size() |
returns the dimensions of the images being recorded |
pygame.camera.Camera.query_image() |
checks if a frame is ready |
pygame.camera.Camera.get_image() |
captures an image as a Surface |
pygame.camera.Camera.get_raw() |
returns an unmodified image as a string |
Example
以下程序捕获来自计算机默认网络摄像头的实时馈送。
Following programs captures live feed from computer’s default web camera.
import pygame
import pygame.camera
pygame.init()
gameDisplay = pygame.display.set_mode((640,480))
pygame.camera.init()
print (pygame.camera.list_cameras())
cam = pygame.camera.Camera(0)
cam.start()
while True:
img = cam.get_image()
gameDisplay.blit(img,(0,0))
pygame.display.update()
for event in pygame.event.get() :
if event.type == pygame.QUIT :
cam.stop()
pygame.quit()
exit()
请注意,在 Windows 操作系统上,你可能需要安装 Videocapture 模块。
Please note that on Windows OS, you may have to install Videocapture module.
pip3 install VideoCapture