根据颜色比较找到两个区域之间的匹配

时间:2019-09-22 09:41:39

标签: python opencv python-imaging-library

我正在编写代码,以根据参考图像颜色元组的红色,绿色,蓝色成分(特定颜色用作比较参考,例如(128,128,128),公差),将参考图像颜色与特定区域中的实际图像颜色进行比较每个RGB分量可能与参考颜色相距多远,仍被认为是该区域内的match(8,8,8)和平坦度,例如与实际图像的wrt的90%

1。我的第一个任务是计算测试的平均r,g,b颜色分量 区域

  

(1251,532,589,82)

为此,我在下面编写了伪代码, 我的输出为

  

(217,15,28)

enter image description here

import cv2
from PIL import Image
import math
import numpy as np

class CompareColor(object):
  ''' loop through each pixel and average rgb '''
  def __init__(self, imageName):
      self.pic = Image.open(imageName)
      # load image data
      self.imgData = self.pic.load()
      pixel_values = list(self.pic.getdata())
      print(pixel_values)

  def color(self):
      r, g, b = 0, 0, 0
      count = 0
      for x in range(self.pic.size[0]):
          for y in range(self.pic.size[1]):
              tempr,tempg,tempb = self.imgData[x,y]
              r += tempr
              g += tempg
              b += tempb
              count += 1
      # calculate averages
      return math.ceil(r/count), math.ceil(g/count), math.ceil(b/count)

class ColorTest:
    def __init__(self):
        self.actualImgPath = "/home/color/youtube.png"
        self.includedAreas = (1251, 532, 589, 82)


    def findActualRGBComponent(self):
        actualImg = cv2.imread(self.actualImgPath)
        Y1 = self.includedAreas[1]
        Y2 = Y1 + self.includedAreas[3]
        X1 = self.includedAreas[0]
        X2 = X1 + self.includedAreas[2]
        crop_image = actualImg[Y1:Y2, X1:X2].copy()
        status = cv2.imwrite('//home//color//crop.png', crop_image)
        img_file = '//home//color//crop.png'
        pc = CompareColor(img_file)
        print('color', pc.color())

if __name__ == "__main__":
    colTest = ColorTest()
    colTest.findActualRGBComponent()
  1. 我的第二个任务是找到颜色的平坦度,这意味着颜色的平坦度-感兴趣区域的范围是否在0-100范围内有很大变化,其中100是完美的单色,但我无法弄清楚了解如何实现此逻辑。谁能帮助我

1 个答案:

答案 0 :(得分:0)

您应该检查有关图像主要颜色的答案,因为在该特定图片上找到平均值没有实际意义,因此该图片的任何位置均不存在该平均值:How to find the average colour of an image in Python with OpenCV?

使用完主导色后,您就可以轻松回答关于// Click Enter Enter pressed from A // now click on toggle component button // Click Enter again Enter pressed from A 或其他问题的第二个问题-因为到目前为止,您发现的平均色在图片上不存在,因此flatness可以是不存在的颜色的任意数字。