# encoding=utf-8 # 当前时间:2022/1/29 0:08 import datetime, os, glob import pandas as pd import numpy as np import cv2 dir = r'H:\pythonProject\python310\photoresources' file = glob.glob(os.path.join(dir,'foot.mp4')) # opencv已经实现了的追踪算法,目前有下面7种算法 # 报错原因:opencv版本包括4.5.1以上,都不支持这些函数;解决方法:通过cv2.legacy来调用这些函数,比如 ‘cv2.TrackerBoosting_create’ 改成 ‘cv2.legacy.TrackerBoosting_create’;其它也类似改动即可! OPENCV_OBJECT_TRACKERS = { "csrt": cv2.legacy.TrackerCSRT_create, "kcf": cv2.TrackerKCF_create, "boosting": cv2.legacy.TrackerBoosting_create, "mil": cv2.legacy.TrackerMIL_create, "tld": cv2.legacy.TrackerTLD_create, "medianflow": cv2.legacy.TrackerMedianFlow_create, "mosse": cv2.legacy.TrackerMOSSE_create } # 实例化OpenCV's multi——object tracker trackers = cv2.legacy.MultiTracker_create()# 创建一个多目标的实例对象,新版本必须加legacy[遗留],因为这是传统算法,必须加遗留的 cap = cv2.VideoCapture(file[0]) # 视频流 while True: # 取当前帧 ret,frame =cap.read() if frame is None: break # resize每一帧 h, w= frame.shape[:2] width = 600 # interpolation - 插值方法。共有5种:)INTER_AREA - 基于局部像素的重采样(resampling using pixel area relation)。对于图像抽取(image decimation)来说,这可能是一个更好的方法。但如果是放大图像时,它和最近邻法的效果类似。 frame =cv2.resize(frame,(width,int(h*width/float(w))),interpolation = cv2.INTER_AREA) # 追踪结果 success,boxes = trackers.update(frame) # success True ;# boxes () # 绘制区域 for box in boxes: print(box) x,y,w,h = [int(v) for v in box] cv2.rectangle(frame,pt1=(x,y),pt2=(x+w,y+h),thickness = 2,color = (0,255,0)) cv2.imshow('frame',frame) key = cv2.waitKey(100) # 选择Select a ROI and then press SPACE or ENTER button! if key in [ord('s'),ord('S')]: box =cv2.selectROI('frame',frame,fromCenter = False,showCrosshair = True) # showCrosshair: 是否显示网格 print(box) # (288, 192, 64, 59) # 创建1个新的追踪器 tracker = OPENCV_OBJECT_TRACKERS['kcf'] print(tracker) trackers.add(tracker,frame,box) # 把新创建的追踪器,frame,box都加到原来的追踪器trackers里 # 退出 elif key in [ord('q'),ord('Q'),27]: break cap.release() cv2.destroyAllWindows()