Spaces:
Build error
Build error
| import cv2 | |
| import gradio as gr | |
| from ultralytics import YOLO | |
| def inference(path:str, threshold:float=0.6): | |
| print("trying inference with path", path) | |
| if path is None: | |
| return None,0 | |
| model = YOLO('yolov8m.pt') # Caution new API since Ultralytics 8.0.43 | |
| # [0] # only considering class 'person' and not the 79 other classes... | |
| outputs = model.predict(source=path, classes= [0], show=False, conf=threshold) # new API with Ultralytics 8.0.43. Accepts 'show', 'classes', 'stream', 'conf' (default is 0.25) | |
| image = cv2.imread(path) | |
| counter = 0 | |
| for output in outputs: # mono item batch | |
| conf = output.boxes.conf # the tensor of detection confidences | |
| xyxy = output.boxes.xyxy | |
| cls = output.boxes.cls # 0 is 'person' and 5 is 'bus' 16 is dog | |
| nb=cls.size(dim=0) | |
| for i in range(nb): | |
| box = xyxy[i] | |
| if conf[i]<threshold: | |
| break | |
| cv2.rectangle( | |
| image, | |
| (int(box[0]), int(box[1])), | |
| (int(box[2]), int(box[3])), | |
| color=(0, 0, 255), | |
| thickness=2, | |
| ) | |
| counter+=1 | |
| return cv2.cvtColor(image, cv2.COLOR_BGR2RGB), counter | |
| gr.Interface( | |
| fn = inference, | |
| inputs = [ gr.components.Image(type="filepath", label="Input"), gr.Slider(minimum=0.5, maximum=0.9, step=0.05, value=0.7, label="Confidence threshold") ], | |
| outputs = [ gr.components.Image(type="numpy", label="Output"), gr.Label(label="nb of persons detected for given confidence threshold") ], | |
| title="Person detection with YOLO v8", | |
| description="Person detection, you can tweak the corresponding confidence threshold. Good results even when face not visible. New API since Ultralytics 8.0.43.", | |
| examples=[ ['data/businessmen-612.jpg'], ['data/businessmen-back.jpg']], | |
| allow_flagging="never" | |
| ).launch(debug=True, enable_queue=True) |