问题描述
我使用 openCV 做模板匹配。我打算用它来检测来自实时提要的模板。目前我使用 63 个模板,匹配图像的平均总时间约为 9 毫秒。这对于我想到的应用程序来说太慢了。
到目前为止我做过的优化:
- 灰度一切
- 裁剪源图像
- 对所有内容进行下采样
我还能尝试缩短什么时间?我认为提要大约为 20fps,而且我会有更多的 CV 内容在此运行,所以像 1ms 这样的东西将是最佳目标.
这是我目前的代码:
import cv2 as cv
import numpy as np
import os
import time as time
scale=0.8
#load needles
directory = r"FOLDER_OF_NEEDLES"
needleList = []
for fails in os.listdir(directory):
path = os.path.join(directory,fails)
img = cv.imread(path,cv.IMREAD_GRAYSCALE)
img_resized = cv.resize(img,None,fx=scale,fy=scale,interpolation = cv.INTER_AREA)
needleList.append(img_resized)
#load haystack
haystack_img = cv.imread('haystack_IMAGE',cv.IMREAD_UNCHANGED)
haystack_img_gray = cv.cvtColor(haystack_img,cv.COLOR_BGR2GRAY)
shop_haystack = haystack_img_gray[668:768,125:900]
shop_haystack = cv.resize(shop_haystack,interpolation = cv.INTER_AREA)
#debugging stuff
how_many_matches = 0
timeStart = time.time()
threshold = 0.85
#matching loop
for needle in needleList:
result = cv.matchTemplate(shop_haystack,needle,cv.TM_CCOEFF_norMED)
min_val,max_val,min_loc,max_loc = cv.minMaxLoc(result)
#debugging stuff
#print('Best match top left position: %s' % str(max_loc))
#print('Best match confidence: %s' % max_val)
#draw rectangles on matches
if max_val >= threshold:
how_many_matches+=1
needle_h = int(needle.shape[0]/scale)
needle_w = int(needle.shape[1]/scale)
top_left = max_loc
top_left = (
int(top_left[0]/scale+125),int(top_left[1]/scale+668))
bottom_right = (top_left[0] + needle_w,top_left[1] + needle_h)
cv.rectangle(
haystack_img,top_left,bottom_right,color = (0,255,0),thickness = 2,lineType = cv.LINE_4)
print(time.time()-timeStart)
print(how_many_matches,'matches')
cv.imshow('slowboi',haystack_img)
cv.waitKey()
我在这里提供了针头:https://failiem.lv/u/t6sqtx7tv
这里还有几个干草堆:https://failiem.lv/u/bttrwy6mc
任何和所有帮助将不胜感激!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)