环境python2+opencv2
效果:打开摄像头,鼠标选择目标,自动跟踪
优缺点:可以跟踪,但会突然跟丢。算法问题。
# -*- coding: utf-8 -*-
import cv2
import numpy as np
tem=[0,0,0,0]
tem_im=[]
ix,iy=-1,-1
ox,oy=-1,-1
#0 nothing 1 template choose 2 show the destination
mode=0
def 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:
break
cv2.destroyAllWindows()