我目前正在构建一个类似搜索引擎和画廊的网络漫画平台,专注于引用来源并为作者提供信用。
我正在尝试找到一种方法来搜索图像以查找其中的人物。
例如:
假设我将红色角色和绿色角色保存为红衣人和绿衣人,那么如何确定图片是否包含其中之一。
这不需要完全识别或其他什么,因为这只是我想要创建的一种附加功能,但我不知道从哪里开始。我已经尝试了很多关于图像识别的谷歌搜索,但没有找到太有用的内容。
值得一提的是,我希望使用Python完成此项任务。
我目前正在构建一个类似搜索引擎和画廊的网络漫画平台,专注于引用来源并为作者提供信用。
我正在尝试找到一种方法来搜索图像以查找其中的人物。
例如:
假设我将红色角色和绿色角色保存为红衣人和绿衣人,那么如何确定图片是否包含其中之一。
这不需要完全识别或其他什么,因为这只是我想要创建的一种附加功能,但我不知道从哪里开始。我已经尝试了很多关于图像识别的谷歌搜索,但没有找到太有用的内容。
值得一提的是,我希望使用Python完成此项任务。
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 columns and rows
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
cv2.imwrite('result.png', img_rgb)
(注:我更改和修复了原始代码中的一些“错误”)
结果:
(翻译:)对于未来可能遇到这个问题的任何人。
这可以通过模板匹配完成。简而言之,模板匹配是寻找一个图像在另一个图像中的精确匹配。
以下是如何在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)
cv2.matchtemplate(large_image, small_image, method)
。此外,这里还有另一个良好的关于Python中模板匹配信息的资源。 - devonbleibtreyfrom cv2 import cv
会引发 ImportError: cannot import name 'cv'
错误,而 import cv2
却可以正常工作... - jeromejsudo apt-get install python3-opencv
才能使其正常工作。 - brewmanz重要提示:matchTemplate甚至能够检测调整大小和旋转的模板。以下是代码和输出。
import matplotlib.pyplot as plt
import numpy as np
import cv2
image = cv2.imread('/content/picture.png')
template = cv2.imread('/content/penguin.png')
heat_map = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
h, w, _ = template.shape
y, x = np.unravel_index(np.argmax(heat_map), heat_map.shape)
cv2.rectangle(image, (x,y), (x+w, y+h), (0,0,255), 5)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
详细解释在这里(我的博客):simple-ai.net/find-and-replace-in-image
OpenCV有一个Python接口,您可以查看。如果字符不会改变太多,您可以尝试使用matchTemplate函数。
这里是官方的教程(该教程使用C++接口编写,但您应该能够从中获得如何在Python中使用该函数的好主意)。