【问题标题】:Use matchTemplate with colored images OpenCV使用带有彩色图像 OpenCV 的 matchTemplate
【发布时间】:2019-04-24 11:24:26
【问题描述】:

我正在尝试在桌面屏幕截图中检测某些彩色图像,其中我有形状相同但颜色不同的模板(这些模板在使用普通 matchTemplate 方法时并没有区别,因为它是用灰度图像完成的)这里是主要的检测代码:

     template = cv2.imread(template_path,1)
    #template_hsv = cv2.cvtColor(template, cv2.COLOR_RGB2HSV)
    #template_B, template_G, template_R = cv2.split(template)
    #scr_B, scr_G, scr_R = cv2.split(screenshot)
    scr_B = screenshot[:, :, 0]
    scr_G = screenshot[:, :, 1]
    scr_R = screenshot[:, :, 2]
    template_B = template[:, :, 0]
    template_G = template[:, :, 1]
    template_R = template[:, :, 2]
    #cv2.imwrite('./sc4.png', scr_R)
    #cv2.imwrite('./template.png', template)

    resB = cv2.matchTemplate(scr_B, template_B, cv2.TM_CCOEFF_NORMED)
    resG = cv2.matchTemplate(scr_G, template_G, cv2.TM_CCOEFF_NORMED)
    resR = cv2.matchTemplate(scr_R, template_R, cv2.TM_CCOEFF_NORMED)

    res = resB + resG + resR

    #res = cv2.matchTemplate(screenshot, template_G, cv2.TM_CCOEFF_NORMED)
    matches = np.where(res >= 3*threshold)
    print(matches)
    return matches

如您所见,我尝试拆分 rgb 屏幕截图图像的通道,然后与同样拆分的模板图像进行比较。正如您在注释代码中看到的那样,我还尝试使用 HSV 通道执行此操作。 然而这并没有奏效,尽管看到在单通道图像中存在视觉上的颜色差异,但程序并没有区分它们(我还尝试与模板和屏幕截图的每个单独通道进行比较)。

欢迎所有建议,甚至尝试使用其他任何方法来实现我的目标。先感谢您。

【问题讨论】:

  • TM_CCOEFF_NORMED 不适用于恒定彩色图像,因为分母实际上包含标准偏差,对于恒定图像,标准偏差为零。

标签: python opencv colors matchtemplate


【解决方案1】:

我用TM_CCOEFF_NORMED 方法尝试过,但没有用......不知何故,它给出了所有的1.0(所有最大值)......但使用TM_SQDIFF_NORMED 方法实际上给出了一些合理的东西。

让我们从创建一个示例图像开始,我是按如下方式进行的:

import numpy as np
import cv2

randVal = lambda : np.random.randint(0,high=255, dtype=np.uint8)
randomColor = lambda : (randVal(), randVal(), randVal())
targetColor = randomColor()

width = 500
height = 500
x = 20
y = 20
img = np.zeros((height, width,3), dtype=np.uint8)
target = np.full((100, 100,3), targetColor, dtype=np.uint8)
while y < height-100:
  x  = 20
  while x < width-100:
    img[y:y+100, x:x+100] = randomColor()
    x += 120
  y += 120

img[20:120, 20:120] = targetColor

这将创建 2 个图像,imgtarget,它们都是随机的,在我的测试中它给出了这样的结果:

图片:

目标:

现在,我按原样使用模板匹配,因为在文档中说它可能需要 1 或 3 个通道并且它会正确执行,但使用其他方法

res = cv2.matchTemplate(img[:,:,0], target[:,:,0], cv2.TM_SQDIFF_NORMED )
threshold = 0.00001
loc = np.where( res <= threshold )
img_rgb = img.copy()
for pt in zip(*loc[::-1]):
    cv2.rectangle(img_rgb, pt, (pt[0] + 100, pt[1] + 100), (0,0,255), 2)

这给了我以下结果:

我希望这会有所帮助...我需要测试您在另一个版本中使用的方法,看看它是否是我的版本中的问题或者是这组图像的特定问题...

【讨论】:

    猜你喜欢
    • 2018-12-25
    • 2017-11-25
    • 2015-11-07
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    相关资源
    最近更新 更多