欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多尺度模板匹配

程序员文章站 2022-04-01 09:39:12
...

效果特别差 只能用来识别简单的东西
仅供练手

import cv2
import numpy as np
import os
import time

cap=cv2.VideoCapture('Camera Roll/3.mp4')#视频加载 读摄像头就填0
temp=cv2.imread('Camera Roll/temp3.jpg') #模板

gray_temp=cv2.cvtColor(temp, cv2.COLOR_BGR2GRAY)

h_t,w_t,c_t=temp.shape[:]
cv2.imshow('gray-',gray_temp)

if cap.isOpened() !=True:#判断视频是否打开
    os._exit(-1)
counter=0 #计数初始化
while True:
    start =time.clock() 
    success,frame=cap.read()
    if success != True:
        break
    if counter%3==0:#隔三帧处理一次

        h, w, c = frame.shape[:]
        print('h,w',h,w)
        H=0.6*h
        W1=0.1*w
        W2=0.9*w
        dst = frame[int(H):h, int(W1):int(W2)]#视频剪裁 减少其他区域的误识别
        h_c,w_c,c_c=dst.shape[:]
        #print('h_c,w_c:',h_c,w_c)

        gray_frame = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)

        for r in np.linspace(1, 2,10 )[::-1]:
            # 根据尺度大小对模板图片进行缩放
            resized = cv2.resize(gray_temp, (0, 0), fx=r, fy=r, interpolation=cv2.INTER_NEAREST)
            # 匹配模板
            if resized.shape[0]> frame.shape[0] or resized.shape[1]> frame.shape[1]:
                print('模板比图片大')
                break
            res = cv2.matchTemplate(gray_frame, resized, cv2.TM_CCOEFF_NORMED)
            loc = np.where(res >= 0.6)
            for pt in zip(*loc[::-1]):
                #print(pt)
                (startx, starty) = (int(pt[0]+W1), int(pt[1]+H))
                (endx, endy) = (int(pt[0]+W1 + h_t*r), int(pt[1]+H + w_t *r))
                cv2.rectangle(frame, (startx, starty), (endx, endy), (0, 255, 0), 3)
                #cv2.rectangle(frame,pt,(pt[0]+h_t*r,pt[1]+w_t*r), (0, 255, 0), 3)
        cv2.imshow('result',frame)
    counter +=1
    if cv2.waitKey(40) & 0xFF == ord('q'):  
        break
    end=time.clock()
    print('=============')
    print('time', end-start)
cap.release()  # 释放资源
cv2.destroyWindow()  #关闭窗口

相关标签: opencv python