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

189
如果我使用open(“image.jpg”)打开图像,假设我有像素的坐标,怎样才能获得该像素的RGB值?
然后,我该如何反向操作?从一个空白的图形开始,'写入'具有特定RGB值的像素?
我希望不必下载任何其他库。
13个回答

251

最好使用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。


1
幸运的是,在Linux和Windows中安装PIL非常简单(不知道Mac怎么样)。 - heltonbiker
7
我通过 pip 安装了 PIL,这件事情相当简单。 - michaelliu
1
我在我的Mac上使用了这个(Pypi):easy_install --find-links http://www.pythonware.com/products/pil/ Imaging - Mazyod
27
对于未来的读者:pip install pillow 将会成功并且相当快地安装PIL(如果不在虚拟环境中,可能需要使用 sudo)。 - Christopher Shroba
https://pillow.readthedocs.io/en/latest/installation.html#windows-installation 在Windows安装步骤中显示了bash命令。不太确定如何继续操作。 - Musixauce3000
显示剩余2条评论

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

一种完整、易于使用的解决方案是

# Third party modules
import numpy
from PIL import Image


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


image = get_image("gradient.png")

print(image[0])
print(image.shape)

代码烟雾测试

你可能不确定宽度/高度/通道的顺序。因此,我创建了这个渐变图像:

enter image description here

该图像的宽度为100px,高度为26px。颜色渐变从#ffaa00(黄色)到#ffffff(白色)。输出结果如下:

[[255 172   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 171   5]
 [255 171   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 171   5]
 [255 172   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 171   5]
 [255 172   4]
 [255 172   5]
 [255 171   5]
 [255 171   5]
 [255 172   5]]
(100, 26, 3)

需要注意的事项:

  • 形状为 (宽度, 高度, 通道数)
  • image[0],即第一行,有 26 个三元组颜色

1
Pillow在macOS上支持Python 2.7,而我只发现PIL支持Python 2.5。谢谢! - Kangaroo.H
6
注意,'reshape'参数列表应为(height, width, channels)。对于RGBA图像,您可以使用channels = 4,同时包括image.mode = RGBA。 - gmarsi
@gmarsi提到的关于宽度和高度的观点是否正确?两者都是有效的吗?您需要了解数据的输出方式,以便知道输出数组的形状以及图像的行和列像素数据在哪里。 - Kioshiki
@Kioshiki,我在我的答案中添加了一个“冒烟测试”部分,这样更容易看出来。 - Martin Thoma
2
例子很令人困惑。如果它是行,那么不应该有100个数据点吗?如果“行”实际上是图片的列,那么它的值不应该改为#fff吗? - d9ngle
@d9ngle 是的,问题出在reshape上,应该是pixel_values = numpy.array(pixel_values).reshape((height, width, channels)) - Chifrijo

24

PyPNG - 轻量级PNG解码器/编码器

虽然问题提到了JPG,但我希望我的回答对一些人有用。

以下是使用PyPNG模块读写PNG像素的方法:

import png, array

point = (2, 10) # coordinates of pixel to be painted red

reader = png.Reader(filename='image.png')
w, h, pixels, metadata = reader.read_flat()
pixel_byte_width = 4 if metadata['alpha'] else 3
pixel_position = point[0] + point[1] * w
new_pixel_value = (255, 0, 0, 0) if metadata['alpha'] else (255, 0, 0)
pixels[
  pixel_position * pixel_byte_width :
  (pixel_position + 1) * pixel_byte_width] = array.array('B', new_pixel_value)

output = open('image-with-red-dot.png', 'wb')
writer = png.Writer(w, h, **metadata)
writer.write_array(output, pixels)
output.close()

PyPNG是一个单一的纯Python模块,包括测试和注释在内不到4000行。

PIL是一个更全面的图像库,但相对来说更加笨重。


13

正如Dave Webb所说:

以下是我工作的代码片段,用于打印图像中的像素颜色:

import os, sys
import Image

im = Image.open("image.jpg")
x = 3
y = 4

pix = im.load()
print pix[x,y]

当我运行Lachlan Phillips的代码并输入print(pix[10,200])时,为什么会返回4个值 (156, 158, 157, 255)?为什么会这样? - just_learning
1
这可能是因为您的图像支持 alpha 透明度并且采用 rgba 格式,这意味着第四个值表示该像素的透明度。 - Nicholas Zolton
为什么会出现这个错误??? raise UnidentifiedImageError( PIL.UnidentifiedImageError: 无法识别图像文件 'test_images/test_UAV.tif'``` - just_learning

9
photo = Image.open('IN.jpg') #your image
photo = photo.convert('RGB')

width = photo.size[0] #define W and H
height = photo.size[1]

for y in range(0, height): #each pixel has coordinates
    row = ""
    for x in range(0, width):

        RGB = photo.getpixel((x,y))
        R,G,B = RGB  #now you can use the RGB value

7
使用一个名为Pillow的库,你可以将这个过程封装成一个函数,以便于在程序中重复使用。
这个函数接受一个图片路径和需要获取像素的坐标作为输入参数。它会打开图片,将其转换为RGB色彩空间,并返回请求的像素的红、绿、蓝三种颜色数值。请保留HTML标记。
from PIL import Image
def rgb_of_pixel(img_path, x, y):
    im = Image.open(img_path).convert('RGB')
    r, g, b = im.getpixel((x, y))
    a = (r, g, b)
    return a

*注意:我不是这段代码的原作者;它没有解释就被留下了。由于它很容易解释,我只是提供了解释,以防后面有人不理解。


2
虽然这段代码片段可能是解决方案,但包括解释真的有助于提高您的帖子质量。请记住,您正在回答未来读者的问题,而这些人可能不知道您的代码建议原因。 - Narendra Jadhav

3

图像处理是一个复杂的主题,最好使用库进行处理。我可以推荐gdmodule,它可以在Python中轻松访问许多不同的图像格式。


有人知道这个被踩的原因吗?是libgd有什么已知问题吗?(我从未看过它,但知道有一个替代PiL总是不错的) - Peter Hanley

3

在wiki.wxpython.org上有一篇非常好的文章,标题为“使用图像”。该文章提到了使用wxWidgets(wxImage)、PIL或PythonMagick的可能性。就我个人而言,我已经使用过PIL和wxWidgets,它们都使图像处理变得相当简单。


3
你可以使用pygame 的surfarray模块。该模块具有一个称为pixels3d(surface)的3D像素数组返回方法。我在下面展示了用法:
from pygame import surfarray, image, display
import pygame
import numpy #important to import

pygame.init()
image = image.load("myimagefile.jpg") #surface to render
resolution = (image.get_width(),image.get_height())
screen = display.set_mode(resolution) #create space for display
screen.blit(image, (0,0)) #superpose image on screen
display.flip()
surfarray.use_arraytype("numpy") #important!
screenpix = surfarray.pixels3d(image) #pixels in 3d array:
#[x][y][rgb]
for y in range(resolution[1]):
    for x in range(resolution[0]):
        for color in range(3):
            screenpix[x][y][color] += 128
            #reverting colors
screen.blit(surfarray.make_surface(screenpix), (0,0)) #superpose on screen
display.flip() #update display
while 1:
    print finished

我希望能够帮到您。最后一句话:屏幕像素的寿命内,屏幕将被锁定。

3
你可以使用Tkinter模块,它是Python标准的Tk GUI工具包接口,无需额外下载。请参见https://docs.python.org/2/library/tkinter.html。(对于Python 3,Tkinter被重命名为tkinter)以下是如何设置RGB值:
#from http://tkinter.unpythonic.net/wiki/PhotoImage
from Tkinter import *

root = Tk()

def pixel(image, pos, color):
    """Place pixel at pos=(x,y) on image, with color=(r,g,b)."""
    r,g,b = color
    x,y = pos
    image.put("#%02x%02x%02x" % (r,g,b), (y, x))

photo = PhotoImage(width=32, height=32)

pixel(photo, (16,16), (255,0,0))  # One lone pixel in the middle...

label = Label(root, image=photo)
label.grid()
root.mainloop()

并获得RGB:

#from http://www.kosbie.net/cmu/spring-14/15-112/handouts/steganographyEncoder.py
def getRGB(image, x, y):
    value = image.get(x, y)
    return tuple(map(int, value.split(" ")))

1
完美,不需要任何安装,而且运行得非常好。您还可以使用 PhotoImage(file="image.png") 加载现有图像。 - mathieures

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接