简单模板匹配实现跟踪

来源:互联网 发布:麦博煲音箱软件 编辑:程序博客网 时间:2024/06/06 19:37

环境python2+opencv2

效果:打开摄像头,鼠标选择目标,自动跟踪

优缺点:可以跟踪,但会突然跟丢。算法问题。

# -*- coding: utf-8 -*-import cv2import numpy as nptem=[0,0,0,0]tem_im=[]ix,iy=-1,-1ox,oy=-1,-1#0 nothing 1 template choose 2 show the destinationmode=0def draw_rec(event,x,y,flags,param):    global tem_im,tem,ix,iy,ox,oy,mode        if event==cv2.EVENT_LBUTTONDOWN:        ix=x        iy=y        mode=1        '''    if event==cv2.EVENT_MOUSEMOVE and flags==cv2.EVENT_FLAG_LBUTTON:        cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),1)    '''    ox=x    oy=y    if event==cv2.EVENT_LBUTTONUP:        ox=x        oy=y        mode=2        tem=[ix,iy,ox,oy]        tem_im=img[tem[1]:tem[3],tem[0]:tem[2]].copy()    cap=cv2.VideoCapture(0)cv2.namedWindow('image')cv2.setMouseCallback('image',draw_rec)while(1):    success,img=cap.read()    if mode==1:         cv2.rectangle(img,(ix,iy),(ox,oy),(0,255,0),1)    if mode==2:        res = cv2.matchTemplate(img,tem_im,cv2.TM_SQDIFF)        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)        rect_p=(min_loc[0]+tem[2]-tem[0],min_loc[1]+tem[3]-tem[1])        cv2.rectangle(img,min_loc,rect_p,(0,255,0),1)            cv2.imshow('image',img)    if cv2.waitKey(20)&0xFF==27:        breakcv2.destroyAllWindows()


0 0
原创粉丝点击