Converting PNG file to bitmap array in Python

六月ゝ 毕业季﹏ 提交于 2019-12-08 02:56:06

问题


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?


回答1:


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



回答2:


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.




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!