|
from ultralytics import YOLO |
|
import cv2 |
|
import numpy as np |
|
|
|
def detect_and_visualize(image_path, model_path): |
|
|
|
model = YOLO(model_path) |
|
|
|
|
|
image = cv2.imread(image_path) |
|
|
|
|
|
results = model(image) |
|
|
|
|
|
result = results[0] |
|
|
|
|
|
for box in result.boxes: |
|
|
|
x1, y1, x2, y2 = box.xyxy[0].cpu().numpy() |
|
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2) |
|
|
|
|
|
conf = float(box.conf[0]) |
|
|
|
|
|
cls_id = int(box.cls[0]) |
|
cls_name = result.names[cls_id] |
|
|
|
|
|
color = tuple(np.random.randint(0, 255, 3).tolist()) |
|
|
|
|
|
cv2.rectangle(image, (x1, y1), (x2, y2), color, 2) |
|
|
|
|
|
label = f'{cls_name} {conf:.2f}' |
|
|
|
|
|
(label_width, label_height), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1) |
|
|
|
|
|
cv2.rectangle(image, (x1, y1-label_height-5), (x1+label_width, y1), color, -1) |
|
|
|
|
|
cv2.putText(image, label, (x1, y1-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1) |
|
|
|
|
|
output_path = 'output_detected.jpg' |
|
cv2.imwrite(output_path, image) |
|
print(f"检测结果已保存至: {output_path}") |
|
|
|
|
|
if __name__ == "__main__": |
|
image_path = "./test_math.png" |
|
model_path = "docgenome_object_detection_yolov8.pt" |
|
detect_and_visualize(image_path, model_path) |