导入CV2 将 numpy 导入为 np 从 ultralytics 导入 YOLO 从 deep_sort_realtime.deepsort_tracker 导入 DeepSort
def count_unique_people(video_path):
模型 = YOLO('yolov8n.pt')
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print("Error opening the video file")
return
tracker = DeepSort(max_age=30)
unique_ids = set()
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
results = model(frame, classes=0)
detections = []
for result in results:
boxes = result.boxes.xyxy.cpu().numpy()
scores = result.boxes.conf.cpu().numpy()
for box, score in zip(boxes, scores):
x1, y1, x2, y2 = box[:4]
detections.append([x1, y1, x2, y2, score])
# Updating the tracker with new detections
if len(detections) > 0:
tracked_objects = tracker.update_tracks(np.array(detections), frame=frame)
for track in tracked_objects:
if not track.is_confirmed() or track.time_since_update > 1:
continue
bbox = track.to_tlbr()
obj_id = track.track_id
unique_ids.add(obj_id)
# Displaying frames for visualization
for track in tracked_objects:
if not track.is_confirmed() or track.time_since_update > 1:
continue
bbox = track.to_tlbr()
obj_id = track.track_id
cv2.rectangle(frame, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), (0, 255, 0), 2)
cv2.putText(frame, f'ID: {int(obj_id)}', (int(bbox[0]), int(bbox[1]) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
cv2.imshow('Frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
print(f"Unique people have been discovered: {len(unique_ids)}")
video_path = 'video_2024-05-21_02-46-30.mp4' count_unique_people(视频路径)
回溯(最近一次调用最后一次): 文件“c:\Users 9246\Desktop\Recognize_test ec.py”,第 65 行,在 count_unique_people(视频路径) 文件“c:\Users 9246\Desktop\Recognize_test ec.py”,第 36 行,在 count_unique_people 中 tracked_objects = tracker.update_tracks(np.array(检测),frame=frame) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^ 文件“C:\Users 9246\AppData\Local\Programs\Python\Python312\Lib\site-packages\deep_sort_realtime\deepsort_tracker.py”,第 195 行,在 update_tracks 中 断言 len(raw_detections[0][0])==4 ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 类型错误:“numpy.float32”类型的对象没有 len()
您收到此错误可能是因为
len()
仅适用于类型 string
和 list