opencv实现目标跟踪——python

代码如下:

import cv2
 
     
def draw_circle(event, x, y, flags, param):
 
    global x1, y1, x2, y2, chose, mystart, click, img0, drawing
    if chose is False:
        if event == cv2.EVENT_LBUTTONDBLCLK:
            x1, y1 = x, y
            click = 0
            #print (click)
            chose = True
            drawing = False
        else:
             
            if event == cv2.EVENT_LBUTTONDOWN and click == 2:
                if drawing is True:
                    w = x2 - x1
                    h = y2 - y1
                    if w>0 and w*h>50 :
                        chose = True
                        mystart = True   
                        click = 3
                        drawing = False
                         
                    #else:
                        #x1, x2, y1, y2 = -1, -1, -1, -1
 
            if event == cv2.EVENT_LBUTTONDOWN and click == 1:
                 
                #init = False   
                drawing = True
                x1, y1 = x, y
                x2, y2 = -1, -1
                click = 2
        if drawing is True:
                x2, y2 = x, y
    if event == cv2.EVENT_MBUTTONDOWN:
        mystart = False
        quxiao = True
        click =1
        drawing = False
        print(mystart)
 
 
def tracking():
    global x1, y1, x2, y2, chose, mystart,  click, img0, drawing
    chose = False
    drawing = False
    mystart = False
    click = 1
     
    tracker = cv2.TrackerKCF_create()
    cap = cv2.VideoCapture(2)
    
    cv2.namedWindow('image')
    cv2.setMouseCallback('image', draw_circle)
     
     
    while 1:
            ret, img0 = cap.read()
             
            if drawing is True:              
                cv2.rectangle(img0, (x1, y1), (x2, y2), (0, 255, 0), 2)
            if chose:
                tracker = cv2.TrackerKCF_create()
                init_rect = (x1,y1,x2-x1,y2-y1)
                tracker.init(img0, init_rect)
                mystart = True
                chose = False
            if mystart:
                state, coord = tracker.update(img0)
                coord = [int(i) for i in coord]
                cv2.rectangle(img0, (coord[0],coord[1]), (coord[0]+coord[2],coord[1]+coord[3]), (255,0,0),2)
 
            cv2.imshow('image', img0)
            cv2.waitKey(10)
            
 
if __name__ == '__main__':
 
    tracking()

猜你喜欢

转载自blog.csdn.net/weixin_49513223/article/details/127110598