I would like to convert a PNG image to a 2 dimensional array where each array holds a list of the RGB values of that specific pixel. How could one create a program to read-in a *.png file and convert to this type of data structure?
If you have PIL
installed then you can create an image with Image.open
and get the colors like so:
data = [image.getpixel((x, y)) for x in range(image.width) for y in range(image.height)]
You can use the existing pygame
module. Import a file into a Surface
using pygame.image.load
. You can then access the bit array from this using pygame.surfarray.array2d
. Please see the Pygame docs for more information.
You can use wand
for such basic tasks. The syntax is very easy to read unlike other ImageMagik libs. Basically you'd do something like:
from wand.image import Image
from wand.display import display
array = []
with Image(filename='yourfile.png') as img:
array.append(img.channel_images) # this is most likely wrong, but it should be something similar
It will be along those lines. Once I leave the office I will try this out.
来源:https://stackoverflow.com/questions/31252360/converting-png-file-to-bitmap-array-in-python