在另一个图像中大致定位一个图像
Approximately locate an image within another
我有这个世界的形象:
这张欧洲的照片:
我可以使用什么技术在世界地图中大致定位欧洲的图像?
模板匹配是一种在较大图像中查找相似图像的技术,但它要求模板与子图像中的大小相同。在这个例子中 OpenCV was used, but it can also be done using scikit-image.
import cv2
from imageio import imread
img = imread("https://i.stack.imgur.com/OIsWn.png", pilmode="L")
template = imread("https://i.stack.imgur.com/fkNeW.png", pilmode="L")
# threshold images for equal colours
img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]
template = cv2.threshold(template, 127, 255, cv2.THRESH_BINARY)[1]
aspect_ratio = template.shape[1] / template.shape[0]
# estimate the width and compute the height based on the aspect ratio
w = 380
h = int(w / aspect_ratio)
# resize the template to match the sub-image as best as possible
template = cv2.resize(template, (w, h))
result = cv2.matchTemplate(img, template, cv2.TM_CCOEFF)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(img, top_left, bottom_right, 127, 3)
cv2.imwrite("europe_bounding_box.png", img)
结果:
尽管此示例使用了预先确定的估计宽度,但也可以测试可能的宽度范围并确定哪个值导致最佳匹配。
我有这个世界的形象:
模板匹配是一种在较大图像中查找相似图像的技术,但它要求模板与子图像中的大小相同。在这个例子中 OpenCV was used, but it can also be done using scikit-image.
import cv2
from imageio import imread
img = imread("https://i.stack.imgur.com/OIsWn.png", pilmode="L")
template = imread("https://i.stack.imgur.com/fkNeW.png", pilmode="L")
# threshold images for equal colours
img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]
template = cv2.threshold(template, 127, 255, cv2.THRESH_BINARY)[1]
aspect_ratio = template.shape[1] / template.shape[0]
# estimate the width and compute the height based on the aspect ratio
w = 380
h = int(w / aspect_ratio)
# resize the template to match the sub-image as best as possible
template = cv2.resize(template, (w, h))
result = cv2.matchTemplate(img, template, cv2.TM_CCOEFF)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(img, top_left, bottom_right, 127, 3)
cv2.imwrite("europe_bounding_box.png", img)
结果:
尽管此示例使用了预先确定的估计宽度,但也可以测试可能的宽度范围并确定哪个值导致最佳匹配。