我的工作我的OpenCV的第一个项目。我需要找到所有的箭头并保存方向在列表中。
我用模板匹配找到所有箭头。这工作,因为所有的箭都彼此相似。我周围形成每个箭头的矩形框。但是,当我试着算这些矩形它不给我预期的结果。我无法弄清楚发生了什么。
image = cv2.imread('input.png')
img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)#Converted to grayscale
###read the templates
right = cv2.imread('Images/arrow_right.png',0)
wr, hr = right.shape[::-1]
left=cv2.imread('Images/arrow_left.png',0)
wl, hl = left.shape[::-1]
slf=cv2.imread('Images/self_arrow.jpg',0)
ws, hs = slf.shape[::-1]
###Template Matching
res = cv2.matchTemplate(img_gray,right,cv2.TM_CCOEFF_NORMED)
res1= cv2.matchTemplate(img_gray,left,cv2.TM_CCOEFF_NORMED)
res2= cv2.matchTemplate(img_gray,slf,cv2.TM_CCOEFF_NORMED)
###To get multiple instances set a threshold
threshold = 0.85
loc = np.where(res >= threshold)
pp = pprint.PrettyPrinter(indent=4)
loc1=np.where(res1 >= threshold)
loc2 = np.where( res2 >= threshold)
count=0
###Draw rectangles around each instance in the image
for pt in zip(*loc[::-1]):
cv2.rectangle(image, pt, (pt[0] + wr, pt[1] + hr), (0,0,255), 1)
pp.pprint(pt)
count+=1
print(count)
for pt in zip(*loc1[::-1]):
cv2.rectangle(image, pt, (pt[0] + wl, pt[1] + hl), (0,255,0), 1)
for pt in zip(*loc2[::-1]):
cv2.rectangle(image, pt, (pt[0] + ws, pt[1] + hs), (255,0,0), 1)
###Save the image
cv2.imwrite('arrow_extracted.jpg',image)
在现实中,你已经找到63分匹配器,因为它们的存在。其原因是重叠的框,你可以看到绘制一条线的宽度和比较,您的边框宽度,发现有多个箱子那里。现在,我们可以纠正这一点,简单的答案是,一个办法是提高门槛,但我不会建议,因为你可能会错过一些箭头,我们可以cv2.minMaxLoc()
去,但只能检测一个发生。 tl;dr;
我们能做的最好的是一个算法,称为非最大抑制。
总之它需要所有的箱子,并且如果它们重叠大于给定的阈值区域更进行比较,并且然后能够抑制重叠太多使得它们可以被包围同一个对象的框。
该代码可以在此git repository找到。它的解释是this post可用。
如果你不遵守评论楼下。