如何在匹配多个模板时加速cv.matchTemplate?

2024-05-23 15:00:45 发布

您现在位置:Python中文网/ 问答频道 /正文

Im使用openCV进行模板匹配。我计划使用它来检测来自实时提要的模板。目前,我正在使用63个模板,一幅图像的匹配平均总时间约为9ms。这对于我心目中的应用程序来说太慢了

我迄今为止所做的工作:

  1. 灰度一切
  2. 裁剪源图像
  3. 对所有内容进行下采样

我还可以试着缩短时间吗?我认为feed的速度大约为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,None, fx=scale, fy=scale, 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

任何和所有的帮助将不胜感激


Tags: importimgtimetopvalshopleftcv