【问题标题】:How to get pixel coordinates if I know color(RGB)?如果我知道颜色(RGB),如何获得像素坐标?
【发布时间】:2018-12-12 08:47:24
【问题描述】:

我使用 Python、opencv 和 PIL。

image = cv2.imread('image.jpg')

color = (235, 187, 7)

如果我知道像素颜色,我如何获得像素坐标(x, y)?

【问题讨论】:

  • JPEG 有损。祝你好运。
  • 好吧,我用 PNG thx。需要像素搜索
  • 使用cv2.inRange(),例如参见here
  • 这个答案展示了如何简单快速地做到这一点......stackoverflow.com/a/51091479/2836621
  • @AlexanderReynolds cv2.inRange() 如果您想要特定范围内的像素,将会有所帮助。这里 OP 想要特定像素颜色的所有坐标。

标签: python python-3.x opencv python-imaging-library


【解决方案1】:

这是一个 numpythonic 解决方案。 Numpy 库尽可能加快操作速度。

  • 假设颜色为:color = (235, 187, 7)

indices = np.where(img == color)

  • 我使用 numpy.where() 方法检索两个数组的元组索引,其中第一个数组包含颜色像素的 x 坐标 (235, 187, 7),第二个数组包含 y 坐标这些像素。

现在indices 返回如下内容:

(array([ 81,  81,  81, ..., 304, 304, 304], dtype=int64),
 array([317, 317, 317, ..., 520, 520, 520], dtype=int64),
 array([0, 1, 2, ..., 0, 1, 2], dtype=int64))
  • 然后我使用 zip() 方法获取包含这些点的元组列表。

coordinates = zip(indices[0], indices[1])

  • 但如果您注意到这是一张具有三个通道的彩色图像,每个坐标将重复三次。我们必须只保留唯一的坐标。这可以使用set() 方法完成。

unique_coordinates = list(set(list(coordinates)))

【讨论】:

    【解决方案2】:

    尝试类似:

    color = (235, 187, 7)
    im = Image.open('image.gif')
    rgb_im = im.convert('RGB')
    for x in range(rgb_im.size()[0]):
        for y in range(rgb_im.size()[1]):
            r, g, b = rgb_im.getpixel((x, y))
            if (r,g,b) == colour:
                print(f"Found {colour} at {x},{y}!")
    

    但是getpixel can be slow,所以看看使用pixel access objects

    另请注意,返回的值可能取决于图像类型。例如,pix[1, 1] 返回单个值,因为 GIF 像素引用 GIF 调色板中的 256 个值之一。

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

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

    【讨论】:

      【解决方案3】:

      您可以使用以下内容:

          import numpy as np
      
          # for color image
          color = (75, 75, 75)
          pixels = np.argwhere(img == color)
      

      输出(它重复相同的坐标三次(颜色数)):

      [[   0   28    0]
       [   0   28    1]
       [   0   28    2]
       [   0   54    0]
       [   0   54    1]
       [   0   54    2]
       ................]
      

      为了避免它做以下事情(对不起代码可读性):

          pixels = pixels[::3][:, [0, 1]]
      

      输出:

      [[   0   28]
       [   0   54]
       ...........]
      

      对于灰度图像,它看起来更好:

          color = (75)
          pixels = np.argwhere(img == color)
      

      输出:

      [[   0   28]
       [   0   54]
       ...........]
      

      【讨论】:

        【解决方案4】:
        import PIL #The reason I use PIL and not opencv is that I find pillow 
        #(which is imported with 'PIL') a very useful library for image editing.
        
        image = PIL.Image.open('Name_image') #the image is opened and named image
        f = image.load() #I'm not sure what the load() operation exactly does, but it 
        # is necesarry.
        
        color = (235, 187, 7) # the Red Green Blue values that you want to find the 
        #coordinates of
        PixelCoordinates = [] # List in which all pixel coordinates that match 
        #requirements will be added.
        
        #The lines of code below check for each pixel in the image if the RGB-values 
        # are equal to (235, 187, 7)
        for x in image.size[0]:
            for y in image.size[1]:
                if f[x,y] == color:
                    PixelCoordinates.append([x,y])
        

        【讨论】:

        • 考虑添加一些代码解释。还有,题中用到了opencv,所以试着说一下为什么选择PIL。
        【解决方案5】:

        这是一个仅使用 cv2 库的解决方案

        import cv2
        
        blue = int(input("Enter blue value: "))
        green = int(input("Enter green value: "))
        red = int(input("Enter red value: "))
        path = str(input("Enter image path with image extension:"))
        img = cv2.imread(path)
        img= cv2.resize(img,(150,150))
        x,y,z = img.shape
        
        for i in range(x):
          for j in range(y):
            if img[i,j,0]==blue & img[i,j,1]==green & img[i,j,1]==red:
              print("Found color at ",i,j)
        

        【讨论】:

          猜你喜欢
          • 2021-06-22
          • 2020-12-22
          • 2020-12-22
          • 2017-04-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多