我有两个Numpy数组(3维uint8)从PIL图像转换而来。
我想找出第一个图像是否包含第二个图像,如果包含,则找出第一个图像中匹配的左上角像素的坐标。
有没有一种方法可以在Numpy中以足够快的方式做到这一点,而不是使用(4!非常慢)纯Python循环?
2D示例:
a = numpy.array([
[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]
])
b = numpy.array([
[2, 3],
[6, 7]
])
怎么做这样的事情呢?
position = a.find(b)
那么position
就是(0, 2)
了。
发布于 2015-02-15 18:04:40
实际上,您可以使用如下实现所示的regex
将此问题简化为简单的字符串搜索-接受两个PIL.Image
对象并在haystack
中查找needle
的坐标。这比使用逐个像素的搜索快大约127倍。
def subimg_location(haystack, needle):
haystack = haystack.convert('RGB')
needle = needle.convert('RGB')
haystack_str = haystack.tostring()
needle_str = needle.tostring()
gap_size = (haystack.size[0] - needle.size[0]) * 3
gap_regex = '.{' + str(gap_size) + '}'
# Split b into needle.size[0] chunks
chunk_size = needle.size[0] * 3
split = [needle_str[i:i+chunk_size] for i in range(0, len(needle_str), chunk_size)]
# Build regex
regex = re.escape(split[0])
for i in xrange(1, len(split)):
regex += gap_regex + re.escape(split[i])
p = re.compile(regex)
m = p.search(haystack_str)
if not m:
return None
x, _ = m.span()
left = x % (haystack.size[0] * 3) / 3
top = x / haystack.size[0] / 3
return (left, top)
发布于 2020-08-19 20:53:02
import cv2
import numpy as np
img = cv2.imread("brows.PNG") #main image
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
template = cv2.imread("websearch.PNG", cv2.IMREAD_GRAYSCALE) #subimage
w,h = template.shape[::-1]
result = cv2.matchTemplate(gray_img,template, cv2.TM_CCOEFF_NORMED)
loc = np.where(result >= 0.9)
for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt,(pt[0] + w,pt[1] +h), (0,255,0),3)
cv2.imshow("img",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
https://stackoverflow.com/questions/7670112
复制相似问题