| import bettercam | |
| import pathlib | |
| import torch | |
| import time | |
| import cv2 | |
| import mss | |
| import os | |
| temp = pathlib.PosixPath | |
| pathlib.PosixPath = pathlib.WindowsPath | |
| current_path = os.path.dirname(os.path.abspath(__file__)) | |
| model_path = None | |
| for file in os.listdir(current_path): | |
| if file.endswith(".pt"): | |
| model_path = os.path.join(current_path, file) | |
| break | |
| if model_path is None: | |
| print("No model found. Place it in the same folder as this script.") | |
| exit() | |
| model = torch.hub.load('ultralytics/yolov5', 'custom', path=model_path, force_reload=True) | |
| sct = mss.mss() | |
| monitor = sct.monitors[1] | |
| screen_x = monitor["left"] | |
| screen_y = monitor["top"] | |
| screen_width = monitor["width"] | |
| screen_height = monitor["height"] | |
| camera = bettercam.create(output_color="RGB", output_idx=0) | |
| cv2.namedWindow('YOLOv5 Detection', cv2.WINDOW_NORMAL) | |
| cv2.resizeWindow('YOLOv5 Detection', 960, 540) | |
| cv2.setWindowProperty('YOLOv5 Detection', cv2.WND_PROP_TOPMOST, 1) | |
| while True: | |
| start_time = time.time() | |
| frame = camera.grab(region=(screen_x, screen_y, screen_x + screen_width, screen_y + screen_height)) | |
| if frame is None: continue | |
| rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) | |
| results = model(rgb_frame) | |
| boxes = results.pandas().xyxy[0] | |
| for _, box in boxes.iterrows(): | |
| label = box['name'] | |
| score = box['confidence'] | |
| x, y, w, h = int(box['xmin']), int(box['ymin']), int(box['xmax'] - box['xmin']), int(box['ymax'] - box['ymin']) | |
| if label in ['map']: | |
| cv2.rectangle(rgb_frame, (x, y), (x + w, y + h), (0, 255, 255), 3) | |
| cv2.putText(rgb_frame, f"{score:.2f}", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 255, 255), 2, cv2.LINE_AA) | |
| if label in ['arrow']: | |
| cv2.rectangle(rgb_frame, (x, y), (x + w, y + h), (255, 0, 0), 3) | |
| cv2.putText(rgb_frame, f"{score:.2f}", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 0, 0), 2, cv2.LINE_AA) | |
| fps = round(1 / (time.time() - start_time), 1) | |
| cv2.putText(rgb_frame, f"FPS: {fps}", (20, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2, cv2.LINE_AA) | |
| cv2.imshow('YOLOv5 Detection', rgb_frame) | |
| cv2.resizeWindow('YOLOv5 Detection', 854, 480) | |
| if cv2.waitKey(1) & 0xFF == ord('q'): | |
| break | |
| cv2.destroyAllWindows() | 
