Files
zjsh_yolov11/angle_base_obb/anger_caculate.py

85 lines
2.6 KiB
Python
Raw Normal View History

2025-09-01 14:14:18 +08:00
from ultralytics import YOLO
import cv2
import numpy as np
import os
# 1. 加载模型
2025-09-05 14:29:33 +08:00
model = YOLO(r'/home/hx/yolo/ultralytics_yolo11-main/runs/train/exp_obb2/weights/best.pt')
2025-09-01 14:14:18 +08:00
# 2. 读取图像
2025-09-05 14:29:33 +08:00
img_path = r"/home/hx/yolo/output_masks/2.jpg"
2025-09-01 14:14:18 +08:00
img = cv2.imread(img_path)
if img is None:
print(f"❌ 错误:无法读取图像!请检查路径:{img_path}")
exit(1)
2025-09-05 14:29:33 +08:00
# 3. 预测OBB 模式)
2025-09-01 14:14:18 +08:00
results = model(
img,
save=False,
2025-09-05 14:29:33 +08:00
imgsz=640,
conf=0.15,
mode='obb'
2025-09-01 14:14:18 +08:00
)
# 4. 获取结果并绘制
result = results[0]
2025-09-05 14:29:33 +08:00
annotated_img = result.plot()
2025-09-01 14:14:18 +08:00
2025-09-05 14:29:33 +08:00
# 5. 保存结果
2025-09-01 14:14:18 +08:00
output_dir = "./inference_results"
os.makedirs(output_dir, exist_ok=True)
filename = os.path.basename(img_path)
save_path = os.path.join(output_dir, "detected_" + filename)
cv2.imwrite(save_path, annotated_img)
print(f"✅ 推理结果已保存至: {save_path}")
2025-09-05 14:29:33 +08:00
# 6. 提取旋转框并计算 **两个框之间的夹角**
2025-09-01 14:14:18 +08:00
boxes = result.obb
if boxes is None or len(boxes) == 0:
print("❌ No objects detected.")
else:
print(f"✅ Detected {len(boxes)} object(s):")
2025-09-05 14:29:33 +08:00
directions = [] # 存储每个框的主方向(弧度),归一化到 [0, π)
2025-09-01 14:14:18 +08:00
for i, box in enumerate(boxes):
cls = int(box.cls.cpu().numpy()[0])
conf = box.conf.cpu().numpy()[0]
2025-09-05 14:29:33 +08:00
xywhr = box.xywhr.cpu().numpy()[0] # [cx, cy, w, h, r]
cx, cy, w, h, r_rad = xywhr
2025-09-01 14:14:18 +08:00
2025-09-05 14:29:33 +08:00
# 确定主方向(长边方向)
if w >= h:
direction = r_rad # 长边方向就是 r
else:
direction = r_rad + np.pi / 2 # 长边方向是 r + 90°
2025-09-01 14:14:18 +08:00
2025-09-05 14:29:33 +08:00
# 归一化到 [0, π)
direction = direction % np.pi
2025-09-01 14:14:18 +08:00
2025-09-05 14:29:33 +08:00
directions.append(direction)
angle_deg = np.degrees(direction)
print(f" Box {i+1}: Class: {cls}, Confidence: {conf:.3f}, 主方向: {angle_deg:.2f}°")
# ✅ 计算任意两个框之间的夹角最小夹角0° ~ 90°
if len(directions) >= 2:
print("\n🔍 计算两个旋转框之间的夹角(主方向夹角):")
for i in range(len(directions)):
for j in range(i + 1, len(directions)):
dir1 = directions[i]
dir2 = directions[j]
# 计算方向差(取最小夹角,考虑周期性)
diff = abs(dir1 - dir2)
diff = min(diff, np.pi - diff) # 最小夹角0 ~ π/2
diff_deg = np.degrees(diff)
print(f" Box {i+1} 与 Box {j+1} 之间的夹角: {diff_deg:.2f}°")
2025-09-01 14:14:18 +08:00
else:
print("⚠️ 检测到少于两个目标,无法计算夹角。")
2025-09-05 14:29:33 +08:00
# 7. 显示图像
2025-09-01 14:14:18 +08:00
cv2.imshow("YOLO OBB Prediction", annotated_img)
cv2.waitKey(0)
cv2.destroyAllWindows()