将图像从 pygame 转换为 PIL 图像 [英] Convert image from pygame to PIL image

查看:22
本文介绍了将图像从 pygame 转换为 PIL 图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用 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 下 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(webcamImage,"RGBA",False)
im = Image.frombytes("RGBA",(1280,720),pil_string_image)

这篇关于将图像从 pygame 转换为 PIL 图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆