目标跟踪源码
# -*- coding:utf-8 -*-
import dlib
import cv2
points=[]
def show_info(frame,tracking_status):
pos1 = (10,20)
pos2 = (10,40)
pos3 = (10,60)
info1 = "click selct an area,start tracking"
info2 = "'1'-> start tracking,'2'->stop stacking,'q'->exit"
cv2.putText(frame,info1,pos1,cv2.FONT_HERSHEY_COMPLEX,0.5,(255,255,255))
cv2.putText(frame,info2,pos2,cv2.FONT_HERSHEY_COMPLEX,0.5,(255,255,255))
if tracking_status == True:
cv2.putText(frame,"status:tracking now ...",pos3,cv2.FONT_HERSHEY_COMPLEX,0.5,(0,255,0))
else:
cv2.putText(frame,"status:tracking stop",pos3,cv2.FONT_HERSHEY_COMPLEX,0.5,(255,0,0))
def mouse_event_handler(event,x,y,flags,parms):
global points
if event == cv2.EVENT_LBUTTONDOWN:
points=[(x,y)]
elif event == cv2.EVENT_LBUTTONUP:
points.append((x,y))
def cam_operate():
global points
capture = cv2.VideoCapture(0)
name_window = "object tracking"
cv2.namedWindow(name_window)
cv2.moveWindow(name_window,100,100)
cv2.setMouseCallback(name_window,mouse_event_handler)
tracker = dlib.correlation_tracker()
tracking_state = False
while True:
ret,frame = capture.read()
show_info(frame,tracking_state)
if len(points) == 2:
cv2.rectangle(frame,points[0],points[1],(0,255,0),3)
dlib_rect = dlib.rectangle(points[0][0],points[0][1],points[1][0],points[1][1])
if tracking_state is True:
tracker.update(frame)
pos = tracker.get_position()
cv2.rectangle(frame,(int(pos.left()),int(pos.top())),(int(pos.right()),int(pos.bottom())),(0,255,0),3)
key = cv2.waitKey(1) & 0xFF
if key == ord('1'):
if len(points) == 2:
tracker.start_track(frame,dlib_rect)
tracking_state = True
points=[]
elif key == ord('2'):
points=[]
tracking_state = False
elif key == ord('q'):
break
else:
pass
cv2.imshow(name_window,frame)
capture.release()
cv2.destroyAllWindows()
def main():
cam_operate()
if __name__ == "__main__":
main()
目标跟踪思路
1, 安装dlib,opencv
先按照opencv
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple/
再按照dlib
必须先安装两个库CMake,Boost
pip install CMake -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install Boost -i https://pypi.tuna.tsinghua.edu.cn/simple/
完成后再按照dlib
pip install dlib -i https://pypi.tuna.tsinghua.edu.cn/simple/
2,打开摄像头
opencv库里的方法
3, 创建窗口
opencv库里的方法
4, 绑定鼠标事件
5,启动跟踪器
6,跟踪状态切换
7, 循环视频流
dllib
作用:根据目标物体,跟踪目标