你只能blit
a pygame.Surface
。因此,您必须从相机中逐帧获取并将其转换为pygame.Surface
object.
抓住相机框架:
success, camera_image = capture.read()
将相机帧转换为pygame.Surface对象使用pygame.image.frombuffer:
camera_surf = pygame.image.frombuffer(
camera_image.tobytes(), camera_image.shape[1::-1], "BGR")
在函数中这样做draw_window
:
def draw_window():
# background color
WINDOW.fill((color))
# display object onto the surface (screen)
success, camera_image = camera.read()
if success:
camera_surf = pygame.image.frombuffer(camera_image.tobytes(), camera_image.shape[1::-1], "BGR")
WINDOW.blit(camera_surf, (0, 0))
# update the display
pygame.display.update()
另请参阅python pygame.camera.init() 没有 vidcapture and PyGameExamplesAndAnswers - 相机和视频
替代但最小的例子:
import pygame
import cv2
capture = cv2.VideoCapture(0)
success, camera_image = capture.read()
window = pygame.display.set_mode(camera_image.shape[1::-1])
clock = pygame.time.Clock()
run = success
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
success, camera_image = capture.read()
if success:
camera_surf = pygame.image.frombuffer(
camera_image.tobytes(), camera_image.shape[1::-1], "BGR")
else:
run = False
window.blit(camera_surf, (0, 0))
pygame.display.flip()
pygame.quit()
exit()