如何解决使用开放式CV Python进行模板匹配
我正在使用OpenCV进行模板匹配,效果很好,但遇到了一些问题。
-
过度检测::有时,它会多次检测对象。
-
耗时:该程序实际上使用500个模板,并尝试与简单图像匹配。这意味着,如果我要匹配1000张图像,那么它将尝试匹配至少500 x 1000次。
-
留下一些未被检测到的图像(我相信这是一次内存崩溃,因为它一次处理很多图像)。
有什么办法可以避免这个问题?
以下是随附的代码:
def matchtemplatetiff(tifffile,file,outdir):
img = np.array(PIL.Image.open(tifffile))
tmp = np.array(PIL.Image.open(file))
w,h,c = tmp.shape
res = cv2.matchTemplate(img,tmp,cv2.TM_CCOEFF_NORMED)
# Adjust this threshold value to suit you,you may need some trial runs (critical!)
threshold = 0.4
loc = np.where(res >= threshold)
# create empty lists to append the coord of the
lspoint = []
lspoint2 = []
count = 0
font = cv2.FONT_HERSHEY_SIMPLEX
for pt in zip(*loc[::-1]):
# check that the coords are not already in the list,if they are then skip the match
if pt[0] not in lspoint and pt[1] not in lspoint2:
# draw a yellow boundary around a match
rect = cv2.rectangle(img,pt,(pt[0] + h,pt[1] + w),(0,255),3)
size =w * h * (2.54/400) *( 2.54/400)
cv2.putText(rect,"{:.1f}cm^2".format(size),font,4,3)
# data rows of csv file
rows = 0
rows = [ [tifffile,w,pt[0] + h,pt[1] + w,size]]
# name of csv file
filename = "records.csv"
# writing to csv file
with open(filename,'a',newline='') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)
# writing the fields
csvwriter.writerow(fields)
# writing the data rows
csvwriter.writerows(rows)
for i in range(((pt[0]) - 9),((pt[0]) + 9),1):
# append the x cooord
lspoint.append(i)
for k in range(((pt[1]) - 9),((pt[1]) + 9),1):
# append the y coord
lspoint.append(k)
# count the number of matches
count += 1
else:
continue
print("total objects found ",count)
PIL.Image.fromarray(img,'RGB').save(os.path.join(outdir,os.path.basename(tifffile)))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。