代码之家  ›  专栏  ›  技术社区  ›  Josh Hunt bstahlhood

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

  •  106
  • Josh Hunt bstahlhood  · 技术社区  · 18 年前

    如果我用 open("image.jpg") ,假设我有像素的坐标,如何获得像素的RGB值?

    那么,我怎样才能做相反的事情呢?从空白图形开始,“写入”具有特定RGB值的像素?

    如果我不需要下载任何额外的库,我会更喜欢。

    13 回复  |  直到 7 年前
        1
  •  236
  •   Matthew Smith Anupam Hayat Shawon    8 年前

    可能最好使用 Python Image Library

    最简单的方法是通过 load() method on the Image object 它返回一个像素访问对象,可以像数组一样操作该对象:

    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。

        2
  •  44
  •   Martin Thoma    6 年前

    使用 Pillow

    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

    #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]
        3
  •  24
  •   martineau    10 年前

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

    下面介绍如何使用 PyPNG module :

    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()
    

    PIL 是一个更全面的图像库,但它也明显更重。

        4
  •  13
  •   Matthew Smith Anupam Hayat Shawon    8 年前

    正如戴夫·韦伯所说:

    下面是我的工作代码片段,它从一个 图片:

    import os, sys
    import Image
    
    im = Image.open("image.jpg")
    x = 3
    y = 4
    
    pix = im.load()
    print pix[x,y]
    
        5
  •  7
  •   Peter V loislo    10 年前
    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
    
        6
  •  3
  •   Greg Hewgill    18 年前

    图像处理是一个复杂的话题,如果你 做 gdmodule

        7
  •  3
  •   Jon Cage    18 年前

    在wiki.wxpython.org上有一篇非常好的文章,题为 Working With Images . 本文提到了使用wxWidgets(wxImage)、PIL或PythonMagick的可能性。就我个人而言,我使用过PIL和wxWidgets,它们都使图像处理相当容易。

        8
  •  3
  •   3 revs<br/>Ozgur Sonmez&#13;    17 年前

    你可以用 pygame

    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
    

    我希望你能有所帮助。最后一句话:屏幕在screenpix的生命周期内被锁定。

        9
  •  3
  •   KalamariKing Idan Rotbart    5 年前

    使用一个名为Pillow的库,您可以将其变成一个函数,以便于以后在程序中使用,并且如果您必须多次使用它的话。 该函数只需获取图像的路径和要“抓取”的像素的坐标。它打开图像,将其转换为RGB颜色空间,并返回请求像素的R、G和B。

    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
    

    *注意:我不是该代码的原始作者;没有任何解释。由于解释起来相当容易,我只是简单地提供了上述解释,以防有人不理解。

        10
  •  2
  •   user3423024    12 年前

    import PIL
    import Image
    FILENAME='fn.gif' #image can be in gif jpeg or png format 
    im=Image.open(FILENAME).convert('RGB')
    pix=im.load()
    w=im.size[0]
    h=im.size[1]
    for i in range(w):
      for j in range(h):
        print pix[i,j]
    
        11
  •  2
  •   chenlian    9 年前

    您可以使用Tkinter模块,这是TKGUI工具包的标准Python接口,不需要额外下载。看见 https://docs.python.org/2/library/tkinter.html .

    以下是如何设置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(" ")))
    
        12
  •  1
  •   Rob    9 年前
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    
    img=mpimg.imread('Cricket_ACT_official_logo.png')
    imgplot = plt.imshow(img)
    
        13
  •  1
  •   Matthew Smith Anupam Hayat Shawon    8 年前

    如果您希望以RGB颜色代码的形式显示三位数字,则以下代码应能做到这一点。

    i = Image.open(path)
    pixels = i.load() # this is not a list, nor is it list()'able
    width, height = i.size
    
    all_pixels = []
    for x in range(width):
        for y in range(height):
            cpixel = pixels[x, y]
            all_pixels.append(cpixel)
    

    这可能对你有用。