4
votes

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

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 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 :-)

1
What is the actual type of the result of pygame.image.tostring()? In other words, what does type(pil_string_image).__name__ produce? If bytes, then the Pygame documentation is outdated. If str then I'll need more help to discern the encoding that Pygame is applying.Damian Yerrick
Hy @DamianYerrick, first of all: thank you for your gentle reply. We follow your suggest, so we do that: print(type(pil_string_image).__name__) and the result is bytes. So, what you suggest to do?Caronte Consulting
Ok, we answer ourself down here (:-D)Caronte Consulting

1 Answers

4
votes

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)