3 回答

TA贡献1831条经验 获得超10个赞
最好使用Python Image Library来执行此操作,我担心这是一个单独的下载。
执行所需操作的最简单方法是通过Image对象上的load()方法,该方法返回一个像数组一样可以操作的像素访问对象:
from PIL import Image
im = Image.open('dead_parrot.jpg') # Can be many different formats.
pix = im.load()
print im.size # Get the width and hight of the image for iterating over
print pix[x,y] # Get the RGBA Value of the a pixel of an image
pix[x,y] = value # Set the RGBA Value of the image (tuple)
im.save('alive_parrot.png') # Save the modified pixels as .png
或者,查看ImageDraw,它为创建图像提供了更丰富的API。

TA贡献1824条经验 获得超6个赞
使用Pillow(适用于Python 3.X以及Python 2.7+),您可以执行以下操作:
from PIL import Image
im = Image.open('image.jpg', 'r')
width, height = im.size
pixel_values = list(im.getdata())
现在您拥有所有像素值。如果是RGB或其他模式可以读取im.mode。然后你可以得到像素(x, y):
pixel_values[width*y+x]
或者,您可以使用Numpy并重塑数组:
>>> pixel_values = numpy.array(pixel_values).reshape((width, height, 3))
>>> x, y = 0, 1
>>> pixel_values[x][y]
[ 18 18 12]
一个完整,简单易用的解决方案
def get_image(image_path):
"""Get a numpy array of an image so that one can access values[x][y]."""
image = Image.open(image_path, 'r')
width, height = image.size
pixel_values = list(image.getdata())
if image.mode == 'RGB':
channels = 3
elif image.mode == 'L':
channels = 1
else:
print("Unknown mode: %s" % image.mode)
return None
pixel_values = numpy.array(pixel_values).reshape((width, height, channels))
return pixel_values
添加回答
举报