2

我试图让我的网络摄像头通过 pygame 显示视频。这是代码:

# import the relevant libraries
import time
import pygame
import pygame.camera
from pygame.locals import *
# this is where one sets how long the script
# sleeps for, between frames.sleeptime__in_seconds = 0.05
# initialise the display window
pygame.init()
pygame.camera.init()

screen = pygame.display.set_mode((640, 480), 0, 32)

# set up a camera object
cam = pygame.camera.Camera(0)
# start the camera
cam.start()

while 1:

    # sleep between every frame
    time.sleep( 10 )
    # fetch the camera image
    image = cam.get_image()
    # blank out the screen
    screen.fill((0,0,2))
    # copy the camera image to the screen
    screen.blit( image, ( 0, 0 ) )
    # update the screen to show the latest screen image
    pygame.display.update()

当我尝试这个时,我从 screen.blit( image, ( 0, 0 ) ) 部分得到一个错误

Traceback (most recent call last):
  File "C:\Python32\src\webcam.py", line 28, in <module>
    screen.blit( image, ( 0, 0 ) )
TypeError: argument 1 must be pygame.Surface, not None

我认为这是因为我没有将图像转换为任何适用于 pygame 的图像,但我不知道。

任何帮助将不胜感激。谢谢。

-亚历克斯

好的,这是新代码:这个代码有效,因为它将图片保存到当前文件夹。弄清楚为什么最后一个有效。屏幕还是黑的虽然=\

# import the relevant libraries
import time
import pygame
import pygame.camera
from pygame.locals import *
# this is where one sets how long the script
# sleeps for, between frames.sleeptime__in_seconds = 0.05
# initialise the display window
pygame.init()
pygame.camera.init()
# set up a camera object
size = (640,480)
screen = pygame.display.set_mode(size,0)


surface = pygame.surface.Surface(size,0,screen)

cam = pygame.camera.Camera(0,size)
# start the camera
cam.start()

while 1:

    # sleep between every frame
    time.sleep( 10 )
    # fetch the camera image
    pic = cam.get_image(surface)
    # blank out the screen
    #screen.fill((0,0,0))
    # copy the camera image to the screen
    screen.blit(pic,(0,0))
    # update the screen to show the latest screen image
    p=("outimage.jpg")

    pygame.image.save(surface,p)
    pygame.display.update()
4

1 回答 1

1

尝试像这样创建一个相机。

cam = pygame.camera.Camera(camlist[0],(640,480))

这就是在 pygame 文档的这个页面上完成的。


查看API 页面pygame.camera我发现了两件事可能会有所帮助。第一的,

Pygame 目前仅支持 Linux 和 v4l2 相机。

实验性的!:此 api 可能会在以后的 pygame 版本中更改或消失。如果你使用它,你的代码很可能会在下一个 pygame 版本中中断。

当想知道为什么这出人意料地失败时,请记住这一点。

在一个更乐观的音符上......您可以尝试调用camera.get_raw()并打印结果。它应该是带有原始图像数据的字符串。如果您收到一个空字符串、None或一些无意义的文本:请在此处与我们分享。它会告诉你是否从相机中得到任何东西。

从相机获取图像作为相机本机像素格式的字符串。对于与其他库的集成很有用。

于 2011-12-11T02:41:56.567 回答