0

我使用 openCV 进行模板匹配。我打算用它来检测实时提要中的模板。目前我正在使用 63 个模板,并且图像匹配平均值的总时间约为 9 毫秒。这对于我想到的应用程序来说太慢了。

到目前为止我已经完成的优化:

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

我还能尝试什么来缩短时间?我认为提要大约是 20 fps,并且我会在此运行更多的 CV 内容,因此 1 毫秒之类的将是最佳目标。

到目前为止,这是我的代码:

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

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

4

0 回答 0