猿问

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

如果我打开图像open("image.jpg"),我怎么能得到一个像素的RGB值,假设我有像素的坐标?

然后,我该怎么做呢?从空白图形开始,“写入”具有特定RGB值的像素?

如果我不必下载任何其他库,我更愿意。


UYOU
浏览 2994回答 3
3回答

慕哥6287543

最好使用Python Image Library来执行此操作,我担心这是一个单独的下载。执行所需操作的最简单方法是通过Image对象上的load()方法,该方法返回一个像数组一样可以操作的像素访问对象:from PIL import Imageim = 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 overprint pix[x,y]  # Get the RGBA Value of the a pixel of an imagepix[x,y] = value  # Set the RGBA Value of the image (tuple)im.save('alive_parrot.png')  # Save the modified pixels as .png或者,查看ImageDraw,它为创建图像提供了更丰富的API。

慕妹3242003

使用Pillow(适用于Python 3.X以及Python 2.7+),您可以执行以下操作:from PIL import Imageim = Image.open('image.jpg', 'r')width, height = im.sizepixel_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
随时随地看视频慕课网APP

相关分类

Python
我要回答