import os import math import cv2 import numpy as np from shapely.geometry import Polygon from rknnlite.api import RKNNLite CLASSES = ['clamp'] nmsThresh = 0.4 objectThresh = 0.5 # ------------------- 工具函数 ------------------- def letterbox_resize(image, size, bg_color=114): if isinstance(image, str): image = cv2.imread(image) target_width, target_height = size image_height, image_width, _ = image.shape scale = min(target_width / image_width, target_height / image_height) new_width, new_height = int(image_width * scale), int(image_height * scale) image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_AREA) canvas = np.ones((target_height, target_width, 3), dtype=np.uint8) * bg_color offset_x, offset_y = (target_width - new_width) // 2, (target_height - new_height) // 2 canvas[offset_y:offset_y + new_height, offset_x:offset_x + new_width] = image return canvas, scale, offset_x, offset_y class DetectBox: def __init__(self, classId, score, xmin, ymin, xmax, ymax, angle): self.classId = classId self.score = score self.xmin = xmin self.ymin = ymin self.xmax = xmax self.ymax = ymax self.angle = angle def rotate_rectangle(x1, y1, x2, y2, a): cx, cy = (x1 + x2) / 2, (y1 + y2) / 2 x1_new = int((x1 - cx) * math.cos(a) - (y1 - cy) * math.sin(a) + cx) y1_new = int((x1 - cx) * math.sin(a) + (y1 - cy) * math.cos(a) + cy) x2_new = int((x2 - cx) * math.cos(a) - (y2 - cy) * math.sin(a) + cx) y2_new = int((x2 - cx) * math.sin(a) + (y2 - cy) * math.cos(a) + cy) x3_new = int((x1 - cx) * math.cos(a) - (y2 - cy) * math.sin(a) + cx) y3_new = int((x1 - cx) * math.sin(a) + (y2 - cy) * math.cos(a) + cy) x4_new = int((x2 - cx) * math.cos(a) - (y1 - cy) * math.sin(a) + cx) y4_new = int((x2 - cx) * math.sin(a) + (y1 - cy) * math.cos(a) + cy) return [(x1_new, y1_new), (x3_new, y3_new), (x2_new, y2_new), (x4_new, y4_new)] def intersection(g, p): g = Polygon(np.array(g).reshape(-1,2)) p = Polygon(np.array(p).reshape(-1,2)) if not g.is_valid or not p.is_valid: return 0 inter = g.intersection(p).area union = g.area + p.area - inter return 0 if union == 0 else inter / union def NMS(detectResult): predBoxs = [] sort_detectboxs = sorted(detectResult, key=lambda x: x.score, reverse=True) for i in range(len(sort_detectboxs)): if sort_detectboxs[i].classId == -1: continue p1 = rotate_rectangle(sort_detectboxs[i].xmin, sort_detectboxs[i].ymin, sort_detectboxs[i].xmax, sort_detectboxs[i].ymax, sort_detectboxs[i].angle) predBoxs.append(sort_detectboxs[i]) for j in range(i + 1, len(sort_detectboxs)): if sort_detectboxs[j].classId == sort_detectboxs[i].classId: p2 = rotate_rectangle(sort_detectboxs[j].xmin, sort_detectboxs[j].ymin, sort_detectboxs[j].xmax, sort_detectboxs[j].ymax, sort_detectboxs[j].angle) if intersection(p1, p2) > nmsThresh: sort_detectboxs[j].classId = -1 return predBoxs def sigmoid(x): return np.where(x >= 0, 1 / (1 + np.exp(-x)), np.exp(x) / (1 + np.exp(x))) def softmax(x, axis=-1): exp_x = np.exp(x - np.max(x, axis=axis, keepdims=True)) return exp_x / np.sum(exp_x, axis=axis, keepdims=True) def process(out, model_w, model_h, stride, angle_feature, index, scale_w=1, scale_h=1): class_num = len(CLASSES) angle_feature = angle_feature.reshape(-1) xywh = out[:, :64, :] conf = sigmoid(out[:, 64:, :]) conf = conf.reshape(-1) boxes = [] for ik in range(model_h * model_w * class_num): if conf[ik] > objectThresh: w = ik % model_w h = (ik % (model_w * model_h)) // model_w c = ik // (model_w * model_h) xywh_ = xywh[0, :, (h * model_w) + w].reshape(1, 4, 16, 1) data = np.arange(16).reshape(1, 1, 16, 1) xywh_ = softmax(xywh_, 2) xywh_ = np.sum(xywh_ * data, axis=2).reshape(-1) xywh_add = xywh_[:2] + xywh_[2:] xywh_sub = (xywh_[2:] - xywh_[:2]) / 2 angle = (angle_feature[index + (h * model_w) + w] - 0.25) * math.pi cos_a, sin_a = math.cos(angle), math.sin(angle) xy = xywh_sub[0] * cos_a - xywh_sub[1] * sin_a, xywh_sub[0] * sin_a + xywh_sub[1] * cos_a xywh1 = np.array([xy[0] + w + 0.5, xy[1] + h + 0.5, xywh_add[0], xywh_add[1]]) xywh1 *= stride xmin = (xywh1[0] - xywh1[2] / 2) * scale_w ymin = (xywh1[1] - xywh1[3] / 2) * scale_h xmax = (xywh1[0] + xywh1[2] / 2) * scale_w ymax = (xywh1[1] + xywh1[3] / 2) * scale_h boxes.append(DetectBox(c, conf[ik], xmin, ymin, xmax, ymax, angle)) return boxes # ------------------- 主函数 ------------------- def detect_clamp_angles(model_path, image_path): img = cv2.imread(image_path) if img is None: print(f"❌ 错误:无法读取图像!路径: {image_path}") return None img_resized, scale, offset_x, offset_y = letterbox_resize(img, (640, 640)) infer_img = img_resized[..., ::-1] # BGR -> RGB infer_img = np.expand_dims(infer_img, 0) rknn_lite = RKNNLite(verbose=True) print('--> Load RKNN model') ret = rknn_lite.load_rknn(model_path) if ret != 0: print("Load RKNN model failed") return None print('done') print('--> Init runtime environment') ret = rknn_lite.init_runtime(core_mask=RKNNLite.NPU_CORE_0) if ret != 0: print("Init runtime environment failed") return None print('done') print('--> Running model') results = rknn_lite.inference([infer_img]) outputs = [] for x in results[:-1]: index, stride = 0, 0 if x.shape[2] == 20: stride, index = 32, 20*4*20*4 + 20*2*20*2 elif x.shape[2] == 40: stride, index = 16, 20*4*20*4 elif x.shape[2] == 80: stride, index = 8, 0 feature = x.reshape(1, 65, -1) outputs += process(feature, x.shape[3], x.shape[2], stride, results[-1], index) predbox = NMS(outputs) directions = [] print("✅ 检测框主方向角度:") for i, box in enumerate(predbox): direction = box.angle % np.pi directions.append(direction) angle_deg = np.degrees(direction) print(f" Box {i+1}: {CLASSES[box.classId]} {angle_deg:.2f}°") # 计算任意两框夹角 if len(directions) >= 2: print("\n🔍 任意两框之间最小夹角:") for i in range(len(directions)): for j in range(i + 1, len(directions)): diff = abs(directions[i] - directions[j]) diff = min(diff, np.pi - diff) print(f" Box {i+1} 与 Box {j+1}: {np.degrees(diff):.2f}°") else: print("⚠️ 少于两个目标,无法计算夹角。") rknn_lite.release() return directions # 返回角度列表(弧度) # ------------------- 调用示例 ------------------- if __name__ == "__main__": model_path = "obb.rknn" image_path = "2.jpg" detect_clamp_angles(model_path, image_path)