[英]python pygame blit. Getting an image to display
我正在嘗試讓我的網絡攝像頭通過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()
嘗試創建一個像這樣的相機。
cam = pygame.camera.Camera(camlist[0],(640,480))
這就是在pygame文檔的此頁面上完成的操作。
在pygame.camera
的API頁面上,我發現有兩點可能有所幫助。 第一,
Pygame當前僅支持Linux和v4l2攝像機。
實驗!:此api在以后的pygame版本中可能會更改或消失。 如果使用此功能,則您的代碼很可能會在下一個pygame版本中中斷。
想知道為什么這出人意料地失敗時,請記住這一點。
另外,您可以嘗試調用camera.get_raw()
並打印結果。 它應該是帶有原始圖像數據的字符串。 如果您得到一個空字符串, None
或一些無意義的文本:請在此處與我們分享。 它會告訴您相機是否有東西。
從攝像機獲取的圖像作為字符串以攝像機的本機像素格式顯示。 與其他庫集成很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.