4

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

Community
  • 1
  • 1
  • 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 Feb 17 '16 at 17:35
  • 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 Feb 17 '16 at 18:00
  • Ok, we answer ourself down here (:-D) – Caronte Consulting Feb 17 '16 at 18:06

1 Answers1

4

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)
Chris Combs
  • 519
  • 5
  • 12
  • what is `img`? Perhaps it should be `pil_string_image = pygame.image.tostring(webcamImage,"RGBA",False)`? – KansaiRobot Feb 01 '17 at 00:30
  • 1
    our **img** is what you call **webcamImage**. Thank you for your answer but we solved 1 year ago our question. – Caronte Consulting Feb 02 '17 at 10:45
  • It was a great question and answer. I upvoted both. By the way do you know how to show those PIL images (in the raspberry)? – KansaiRobot Feb 02 '17 at 23:59
  • Hello, our needs were to acquire an image and save it into a file. You can try these lines of code (warning: we don't try that code): from PIL import Image | img = Image.open('test.png') | img.show() – Caronte Consulting Feb 07 '17 at 09:40