Download app.py from shin0624/YOLOv11_based_Realtime_Video_ObjectDetection_And_CrashPrediction: direct link, hf CLI and curl.
- Browser
- Download file 4.25 kB
-
https://huggingface.co/spaces/shin0624/YOLOv11_based_Realtime_Video_ObjectDetection_And_CrashPrediction/resolve/main/app.py
- Command line
-
hf download hf://spaces/shin0624/YOLOv11_based_Realtime_Video_ObjectDetection_And_CrashPrediction/app.py
-
curl -L -o app.py https://huggingface.co/spaces/shin0624/YOLOv11_based_Realtime_Video_ObjectDetection_And_CrashPrediction/resolve/main/app.py
4.25 kB
| import cv2 | |
| import numpy as np | |
| import gradio as gr | |
| from ultralytics import YOLO | |
| from spaces import GPU | |
| model = YOLO("yolo11n.pt") | |
| trajectories = {} | |
| previous_positions = {} | |
| class_colors = { | |
| 'person': (255, 0, 0), | |
| 'forklift': (0, 255, 0), | |
| 'cart': (0, 0, 255) | |
| } | |
| def calculate_collision_risk(pos1_now, pos1_prev, pos2_now, pos2_prev, threshold=100): | |
| dx = pos1_now[0] - pos2_now[0] | |
| dy = pos1_now[1] - pos2_now[1] | |
| distance = np.sqrt(dx ** 2 + dy ** 2) | |
| if distance > threshold: | |
| return 0 | |
| v1 = np.array(pos1_now) - np.array(pos1_prev) | |
| v2 = np.array(pos2_now) - np.array(pos2_prev) | |
| rel_v = v1 - v2 | |
| rel_pos = np.array(pos2_now) - np.array(pos1_now) | |
| if np.linalg.norm(rel_v) == 0 or np.linalg.norm(rel_pos) == 0: | |
| return 0 | |
| cos_angle = np.dot(rel_v, rel_pos) / (np.linalg.norm(rel_v) * np.linalg.norm(rel_pos)) | |
| proximity_score = max(0, (1 - distance / threshold)) | |
| direction_score = max(0, cos_angle) | |
| risk = proximity_score * direction_score * 100 | |
| return int(risk) | |
| def draw_minimap(trajectories, size=(300, 300)): | |
| map_img = np.ones((size[1], size[0], 3), dtype=np.uint8) * 255 | |
| def scale_point(p): return int(p[0] * size[0] / 640), int(p[1] * size[1] / 480) | |
| for obj_id, traj in trajectories.items(): | |
| cls = traj['class'] | |
| points = traj['points'] | |
| for pt in points: | |
| cv2.circle(map_img, scale_point(pt), 3, class_colors.get(cls, (0, 0, 0)), -1) | |
| return map_img | |
| def video_frame_generator(video): | |
| global trajectories, previous_positions | |
| trajectories = {} | |
| previous_positions = {} | |
| cap = cv2.VideoCapture(video) | |
| while cap.isOpened(): | |
| success, frame = cap.read() | |
| if not success: | |
| break | |
| results = model.track(frame, persist=True, verbose=False) | |
| if results and results[0].boxes.id is not None: | |
| boxes = results[0].boxes | |
| ids = boxes.id.cpu().numpy().astype(int) | |
| classes = boxes.cls.cpu().numpy().astype(int) | |
| xyxy = boxes.xyxy.cpu().numpy() | |
| current_positions = {} | |
| for obj_id, cls_id, box in zip(ids, classes, xyxy): | |
| cls_name = model.names[int(cls_id)] | |
| x1, y1, x2, y2 = box | |
| cx = int((x1 + x2) / 2) | |
| cy = int((y1 + y2) / 2) | |
| current_positions[obj_id] = (cx, cy) | |
| if obj_id not in trajectories: | |
| trajectories[obj_id] = {'class': cls_name, 'points': []} | |
| trajectories[obj_id]['points'].append((cx, cy)) | |
| cv2.circle(frame, (cx, cy), 5, class_colors.get(cls_name, (255, 255, 255)), -1) | |
| for i in range(1, len(trajectories[obj_id]['points'])): | |
| cv2.line(frame, trajectories[obj_id]['points'][i-1], | |
| trajectories[obj_id]['points'][i], class_colors.get(cls_name, (255, 255, 255)), 2) | |
| for id1 in current_positions: | |
| for id2 in current_positions: | |
| if id1 >= id2: | |
| continue | |
| pos1_now = current_positions[id1] | |
| pos2_now = current_positions[id2] | |
| pos1_prev = previous_positions.get(id1, pos1_now) | |
| pos2_prev = previous_positions.get(id2, pos2_now) | |
| risk = calculate_collision_risk(pos1_now, pos1_prev, pos2_now, pos2_prev) | |
| if risk > 0: | |
| mid = ((pos1_now[0] + pos2_now[0]) // 2, (pos1_now[1] + pos2_now[1]) // 2) | |
| cv2.putText(frame, f"{risk}%", mid, | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2) | |
| previous_positions = current_positions | |
| minimap = draw_minimap(trajectories) | |
| frame[0:minimap.shape[0], 0:minimap.shape[1]] = minimap | |
| yield cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) | |
| cap.release() | |
| demo = gr.Interface( | |
| fn=video_frame_generator, | |
| inputs=gr.Video(label="업로드할 영상"), | |
| outputs=gr.Image(label="실시간 프레임", type="numpy"), | |
| live=True, | |
| title="실시간 객체 추적 및 충돌 예측 (프레임 단위)", | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |