使用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