问题描述
我们正在使用 Raspberry Pi + Python 3.4 + PyGame 从特定的USB网络摄像头捕获图像.我们使用以下简单代码捕获(可以正常运行):
we are using a Raspberry Pi + Python 3.4 + PyGame to capture an image from a specific USB webcam. We use this simple code to capture (it works ok):
pygame.camera.init()
cam = pygame.camera.Camera(pygame.camera.list_cameras()[0],(1280,720))
cam.start()
time.sleep(1)
webcamImage = cam.get_image()
问题来了:我们必须将此 webcamImage 转换为PIL图像.我们遵循此链接,但不幸的是,该功能Image.fromstring()不再存在.因此,我们不能这样做:
The problem comes here: we have to convert this webcamImage into a PIL image. We follow this link but unfortunately the function Image.fromstring() not exists anymore. So, we can't do that:
pil_string_image = pygame.image.tostring(webcamImage, "RGBA",False)
pil_image = Image.fromstring("RGBA",(1280,720),pil_string_image)
PIL表示不建议使用Image.fromstring(),并建议使用函数 Image.frombytes().显然,我们没有找到将webcamImage转换为字节数组的等效pygame.image函数.所以我们被困在这里:请您能帮我们吗?谢谢:-)
PIL says that Image.fromstring() is deprecated, and suggests to use the function Image.frombytes(). Clearly we not found the equivalent pygame.image function that convert the webcamImage into an array of bytes. So we are stucked here: can you help us, please?Thank you :-)
推荐答案
根据Damian Yerrick的评论,在Python 3下,尽管方法的名称是bytes
,但pygame.image.tostring()
的结果仍是bytes
.因此,我们可以使用以下简单代码摆脱这种情况:
As per Damian Yerrick's comment, under Python 3 the result of pygame.image.tostring()
is a bytes
, despite the method's name. Thus we can go out of this situation with this simple code:
pygame.camera.init()
cam = pygame.camera.Camera(pygame.camera.list_cameras()[0],(1280,720))
cam.start()
time.sleep(1)
webcamImage = cam.get_image()
pil_string_image = pygame.image.tostring(img,"RGBA",False)
im = Image.frombytes("RGBA",(1280,720),pil_string_image)
这篇关于将图像从pygame转换为PIL图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!