如何找到包含在图像中的图像?

2024-06-07 17:01:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在建立一个基本上相当于一个搜索引擎和一个网络漫画画廊的交叉点,重点是引用来源和给予作者信誉。

我正试图找出一种方法来搜索一个图像,找到其中的字符。

例如:

cyanide and happiness

假设我将红色字符和绿色字符保存为红色人和绿色人,如何确定图像是否包含其中一个。

这不需要100%的识别率,或者这是我想要创建的一个附加功能,我只是不知道从哪里开始。我在谷歌上做了很多图像识别的工作,但是没有发现有什么帮助。

就其价值而言,我更喜欢使用Python。


Tags: 方法图像网络重点来源作者画廊字符
3条回答

因为Moshe's answer只覆盖匹配给定图片中只包含一次的模板。以下是如何同时匹配多个:

import cv2
import numpy as np

img_rgb = cv2.imread('mario.png')
template = cv2.imread('mario_coin.png')
w, h = template.shape[:-1]

res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED)
threshold = .8
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):  # Switch collumns and rows
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)

cv2.imwrite('result.png', img_rgb)

(注意:我修改并修正了原始代码中的一些错误)

结果:

detect mario coins (before/after)

来源:https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_template_matching/py_template_matching.html

对于任何在未来遇到这种情况的人。

这可以通过template matching完成。总而言之(我的理解),模板匹配寻找一个图像在另一个图像中的精确匹配。

下面是一个如何在Python中实现的示例:

import cv2

method = cv2.TM_SQDIFF_NORMED

# Read the images from the file
small_image = cv2.imread('small_image.png')
large_image = cv2.imread('large_image.jpeg')

result = cv2.matchTemplate(small_image, large_image, method)

# We want the minimum squared difference
mn,_,mnLoc,_ = cv2.minMaxLoc(result)

# Draw the rectangle:
# Extract the coordinates of our best match
MPx,MPy = mnLoc

# Step 2: Get the size of the template. This is the same size as the match.
trows,tcols = small_image.shape[:2]

# Step 3: Draw the rectangle on large_image
cv2.rectangle(large_image, (MPx,MPy),(MPx+tcols,MPy+trows),(0,0,255),2)

# Display the original image with the rectangle around the match.
cv2.imshow('output',large_image)

# The image is only displayed if we call this
cv2.waitKey(0)

OpenCV有一个可以查看的Python接口。如果是字符,不要更改太多,可以尝试使用matchTemplate函数。

Here是他们的官方教程(教程是用C++接口编写的,但是你应该能从Python中找到函数的用法。

相关问题 更多 >

    热门问题