Python Pygame blit. 如何显示图像

2 投票
1 回答
8375 浏览
提问于 2025-04-17 08:08

我正在尝试通过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能用的格式,但我不太确定。

如果有人能帮忙,我会非常感激。谢谢。

-Alex

好的,这是新的代码: 这个可以工作,因为它把图片保存到了当前文件夹。我弄明白了为什么之前的那个不行。屏幕还是黑的,虽然=\

# 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()

1 个回答

1

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

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

这是在 pygame文档的这一页上介绍的做法。


在查看 pygame.camera的API页面时,我发现了两件可能有帮助的事情。首先,

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

实验性!: 这个API可能会在以后的pygame版本中改变或消失。如果你使用这个,代码很可能会在下一个pygame版本中出错。

当你想知道为什么会出现意外错误时,请记住这一点。

不过,积极一点说...你可以尝试调用 camera.get_raw() 并打印结果。它应该是一个包含原始图像数据的字符串。如果你得到的是空字符串、None,或者一些无意义的文本,请在这里分享给我们。这将告诉我们你是否从相机获取到了任何东西。

从相机获取一张图像,返回的是相机本地像素格式的字符串。这对于与其他库的集成很有用。

撰写回答