python处理rgb_如何在Python中读取给定像素的RGB值?
使用Pillow(適用于Python 3.X以及Python 2.7+),您可以執(zhí)行以下操作:
from PIL import Image
im = Image.open('image.jpg', 'r')
width, height = im.size
pixel_values = list(im.getdata())
現(xiàn)在您擁有所有像素值。如果是RGB或其他模式可以讀取im.mode。然后你可以得到像素(x, y):
pixel_values[width*y+x]
或者,您可以使用Numpy并重塑數(shù)組:
>>> pixel_values = numpy.array(pixel_values).reshape((width, height, 3))
>>> x, y = 0, 1
>>> pixel_values[x][y]
[ 18 18 12]
一個(gè)完整,簡(jiǎn)單易用的解決方案
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
與50位技術(shù)專(zhuān)家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的python处理rgb_如何在Python中读取给定像素的RGB值?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C++字符串完全指引之一(Win32 字
- 下一篇: ATL offsetofclass 的工