过滤Dections有多种过滤方法。包括指定类,类集合,置信度,物体面积,边框面积,相对面积,边框维度和区域。

import numpy as np
import supervision as sv
import cv2 as cv
from ultralytics import YOLO

model_path=r'F:\python\yolov8\yolov8n.pt'
model=YOLO(model_path)
img=cv.imread('supervision-detection.png')
results=model(img)[0]
detections=sv.Detections.from_ultralytics(results)

def process_img(img,detections):
    box_annotator=sv.BoundingBoxAnnotator()
    label_annotator=sv.LabelAnnotator()
    labels=[
        f'{class_name} {confdence:.2f}'
        for class_name,confdence in zip(detections['class_name'],detections.confidence)
    ]
    annotated_frame=box_annotator.annotate(scene=img.copy(),detections=detections)
    annotated_frame=label_annotator.annotate(scene=annotated_frame,detections=detections,labels=labels)
    return annotated_frame

# 通过指定的class_id过滤
filter_detections=detections[detections.class_id==0]
single_class_frame=process_img(img,filter_detections)
cv.imshow('single class',single_class_frame)

# 通过class列表过滤
selected_class=[0,2,3]
filter_detections=detections[np.isin(detections.class_id,selected_class)]
class_list_frame=process_img(img,filter_detections)
cv.imshow('class list',class_list_frame)

# 通过置信度来过滤
filter_detections=detections[detections.confidence>0.5]
confidence_frame=process_img(img,filter_detections)
cv.imshow('confidence',confidence_frame)

# 通过边框面积来过滤
filter_detections=detections[detections.area>1000]
area_frame=process_img(img,filter_detections)
cv.imshow('area',area_frame)

# 通过相对面积来过滤
h,w,c=img.shape
image_area=h*w
filter_detections=detections[(detections.area/image_area)<0.8]
relative_area_frame=process_img(img,filter_detections)
cv.imshow('relative area',relative_area_frame)

# 通过边框的维度
w=detections.xyxy[:,2]-detections.xyxy[:,0]
h=detections.xyxy[:,3]-detections.xyxy[:,1]
filter_detections=detections[(w>200)&(h>200)]
box_dimensions_frame=process_img(img,detections)
cv.imshow('box dimensions',box_dimensions_frame)

# 通过多边形区域过滤
zone_array=np.array([[50,50],[50,100],[100,50],[100,100]])
zone=sv.PolygonZone(zone_array)
mask=zone.trigger(detections)
filter_detections=detections[mask]
ploygon_zone_frame=process_img(img,filter_detections)
cv.imshow('polygon zone',ploygon_zone_frame)

# 通过混合条件
selectd_class=[0]
filter_detections=detections[(np.isin(detections.class_id,selectd_class))&(detections.confidence>0.6)]
mix_frame=process_img(img,filter_detections)
cv.imshow('mix',mix_frame)


if cv.waitKey(0)&0XFF==ord('q'):
    cv.destoryAllWindows()
print('程序执行完成')

 

 posted on 2024-07-21 17:13  会飞的金鱼  阅读(50)  评论(0)    收藏  举报