【问题标题】:Get pixel's RGB using PIL使用 PIL 获取像素的 RGB
【发布时间】:2012-06-19 08:33:36
【问题描述】:

是否可以使用 PIL 获取像素的 RGB 颜色? 我正在使用此代码:

im = Image.open("image.gif")
pix = im.load()
print(pix[1,1])

但是,它只输出一个数字(例如 01)而不是三个数字(例如 60,60,60 用于 R、G、B)。我想我不了解该功能。我想要一些解释。

非常感谢。

【问题讨论】:

    标签: python image python-imaging-library rgb pixel


    【解决方案1】:

    是的,这样:

    im = Image.open('image.gif')
    rgb_im = im.convert('RGB')
    r, g, b = rgb_im.getpixel((1, 1))
    
    print(r, g, b)
    (65, 100, 137)
    

    您之前使用 pix[1, 1] 获得单个值的原因是 GIF 像素引用 GIF 调色板中的 256 个值之一。

    另请参阅此 SO 帖子:Python and PIL pixel values different for GIF and JPEG,此 PIL Reference page 包含有关 convert() 函数的更多信息。

    顺便说一句,您的代码可以很好地处理.jpg 图像。

    【讨论】:

    • 这可以在电脑屏幕上完成,而不仅仅是一个图像文件吗?
    • Image.getpixel() 是基于 0 还是基于 1?我的意思是,最左上角的像素是 (0,0) 还是 (1, 1)?
    • @NimaBavari 是从 0 开始的。
    【解决方案2】:

    GIF 将颜色存储为调色板中 x 种可能的颜色之一。阅读gif limited color palette。所以 PIL 给你的是调色板索引,而不是调色板颜色的颜色信息。

    编辑:删除了一个有错字的博客文章解决方案的链接。其他答案没有错别字。

    【讨论】:

      【解决方案3】:

      转换图像的另一种方法是从调色板创建一个 RGB 索引。

      from PIL import Image
      
      def chunk(seq, size, groupByList=True):
          """Returns list of lists/tuples broken up by size input"""
          func = tuple
          if groupByList:
              func = list
          return [func(seq[i:i + size]) for i in range(0, len(seq), size)]
      
      
      def getPaletteInRgb(img):
          """
          Returns list of RGB tuples found in the image palette
          :type img: Image.Image
          :rtype: list[tuple]
          """
          assert img.mode == 'P', "image should be palette mode"
          pal = img.getpalette()
          colors = chunk(pal, 3, False)
          return colors
      
      # Usage
      im = Image.open("image.gif")
      pal = getPalletteInRgb(im)
      

      【讨论】:

        【解决方案4】:

        不是 PIL,但 imageio.imread 可能仍然很有趣:

        import imageio
        im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
        im = imageio.imread('Figure_1.png', pilmode='RGB')
        print(im.shape)
        

        给予

        (480, 640, 3)
        

        就是这样(高度、宽度、通道)。所以(x, y)位置的像素是

        color = tuple(im[y][x])
        r, g, b = color
        

        过时

        scipy.misc.imreaddeprecated in SciPy 1.0.0(感谢提醒,fbahr!)

        【讨论】:

        • PSA:scipy.misc.imread 已弃用! imread 在 SciPy 1.0.0 中已弃用,并将在 1.2.0 中删除。请改用imageio.imread
        • 感谢您的提醒,fbahr! (实际上我参与了弃用它 - github.com/scipy/scipy/issues/6242?)
        【解决方案5】:

        使用 numpy :

        im = Image.open('image.gif')
        im_matrix = np.array(im)
        print(im_matrix[0][0])
        

        给出位置(0,0)像素的RGB向量

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-05
          • 2020-09-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多