【问题标题】:Finding an image inside of an image (using CV2)在图像内部查找图像(使用 CV2)
【发布时间】:2019-09-20 15:02:05
【问题描述】:

我正在使用 CV2,我想检测图像中的图像。情况如下:

我有这个基本图像,我正在尝试检测当前显示的字符。游戏中有大约 30 个角色,所以我正在考虑为每个角色(character1.png、character2.png 等)制作一个 png,这样我就可以找到用户正在玩的当前角色。以下是 character1.png 模板的示例:

我想将模板与图像的那个区域相匹配。问题是,如果游戏中有多个人在玩同一个角色,他们的角色也会被检测到。但是,我只希望检测到客户的角色。客户的角色将始终位于游戏的左下角。

这是我的代码:

import cv2
import numpy as np

img_bgr = cv2.imread('base.png')
img_gry = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)

template = cv2.imread('search.png', 0)

w, h = template.shape[::-1]

res = cv2.matchTemplate(img_gry, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res >= threshold)

for pt in zip(*loc[::-1]):
    cv2.rectangle(img_bgr, pt, (pt[0]+w, pt[1]+h), (0,255,255), 2)

cv2.imshow('detected', img_bgr)

到目前为止,它的功能与我想要的差不多。它在字符周围放置黄色矩形:

但是,如果有多个具有相同角色的人,其他人的角色也会被检测到。我想知道 cv2 中是否存在仅在基本图像的某个区域(客户角色所在的左下区域)内搜索的功能。此外,我不需要显示黄色矩形,这只是作为测试。所以,我想知道如果在该区域中找到模板,是否可以让 cv2 说“检测到字符 1”、“检测到字符 2”等。

所以,基本上,我希望我的程序循环遍历 characters(1-30).png,一旦找到客户端正在播放的正确字符,它就会说“你正在播放字符 N (n=1 -30). 我想知道这是否是检测客户性格的有效方法。

【问题讨论】:

  • 对于每个图标,您可以使用模板匹配来检测字符是否存在。如果有多个检测(多个轮廓/模板匹配),那么您可以将imutils.sort_contours()left-to-rightbottom-to-top 轮廓排序参数一起使用。排序后,第一个轮廓将是您检测到的字符图标

标签: python opencv


【解决方案1】:

您可以选择角色所在区域的 ROI(感兴趣区域)。然后检查模板是否只在这个区域找到:

import cv2
import numpy as np

img_bgr = cv2.imread('base.png')
img_gry = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)

template = cv2.imread('search.png', 0)

w, h = template.shape[::-1]
roi_start = (430, 550) # top left corner of the selected area
roi_end = (526,651) # bottom right corner of the selected area

roi = img_gry[roi_start[1]: roi_end[1], roi_start[0]: roi_end[0]]
res = cv2.matchTemplate(roi, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
    if pt is not None:
        print("character found")
        break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    相关资源
    最近更新 更多