为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Python中读取给定像素的RGB值?

如何在Python中读取给定像素的RGB值?

UYOU 2019-08-31 10:47:38
如果我打开图像open("image.jpg"),我怎么能得到一个像素的RGB值,假设我有像素的坐标?然后,我该怎么做呢?从空白图形开始,“写入”具有特定RGB值的像素?如果我不必下载任何其他库,我更愿意。
查看完整描述

3 回答

?
慕哥6287543

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。


查看完整回答
反对 回复 2019-08-31
?
慕妹3242003

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


查看完整回答
反对 回复 2019-08-31
  • 3 回答
  • 0 关注
  • 2993 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信