如何在pygame中显示图像?

11

我想从网络摄像头加载图像并在Pygame上显示,我正在使用VideoCapture。

from VideoCapture import Device
import pygame
import time
In=1
pygame.init()
w = 640
h = 480
size=(w,h)
screen = pygame.display.set_mode(size) 

while True:
    cam = Device()
    cam.saveSnapshot(str(In)+".jpg") 
    img=pygame.image.load(In)
    screen.blit(img,(0,0))
    In=int(In)+1
    In=str(In)

为什么这个代码无法正常工作,Pygame窗口打开但没有显示任何内容?


你的图片命名为1.jpg并且在同一个文件夹中吗? - Andy Ray
兄弟,如果你看代码,你会发现它保存快照的语句是 saveSnapshot(str(In)+".jpg")。 - Rasovica
你可以使用 pygame.camera 来拍照,并消除对 VideoCapture 的依赖。 - steffen
1个回答

17
你需要告诉pygame更新显示
在将图像绘制到屏幕后,在循环中添加以下行:
pygame.display.flip()

顺便说一句,你可能希望限制每秒拍摄的图像数量。可以使用time.sleeppygame clock


from VideoCapture import Device
import pygame
import time
In=1
pygame.init()
w = 640
h = 480
size=(w,h)
screen = pygame.display.set_mode(size) 
c = pygame.time.Clock() # create a clock object for timing

while True:
    cam = Device()
    filename = str(In)+".jpg" # ensure filename is correct
    cam.saveSnapshot(filename) 
    img=pygame.image.load(filename) 
    screen.blit(img,(0,0))
    pygame.display.flip() # update the display
    c.tick(3) # only three images per second
    In += 1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接