0

I am currently doing reinforcement learning research based on Pygame where I need to pass images of Pygame(screenshots) to my CNN neural network. I searched on google but pygame.image.save is for saving it to a file. Is there a memory-efficient method to save the screenshot to a variable?

(Please don't act smart closing my post, the question you linked to is for saving to a file, NOT saving to a variable which I have stated in my original post!)

  • 1
    I think you could use a combination of [`pygame.surfarray.array3d`](https://www.pygame.org/docs/ref/surfarray.html#pygame.surfarray.array3d) and [`PIL.Image.fromarray`](https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.fromarray) to do that (or if you need only the array then use just `surfarray.array3d`, or if it is enough `surfarray.array2d`), or just use [`PIL.ImageGrab.grab`](https://pillow.readthedocs.io/en/stable/reference/ImageGrab.html#PIL.ImageGrab.grab) – Matiiss Jan 01 '22 at 00:48
  • 4
    You could use `pygame.image.save()`, except you pass it an instance of [`io.BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO) instead of a file object. – MattDMo Jan 01 '22 at 00:57
  • @MattDMo Could you give me an code example of using pygame.image.save() to save the image to a variable in Python please? From what I see, it can only be used for saving to a file to local computer. –  Jan 01 '22 at 19:02
  • 1
    See my answer [here](https://stackoverflow.com/a/68985992/1426065) for an example that writes to a PDF in-memory instead of an image, but the concept is exactly the same. – MattDMo Jan 01 '22 at 19:35

0 Answers0