import cv2 import numpy as np import json import matplotlib.pyplot as plt import math from typing import Union, List from app.core.logger import get_logger logger = get_logger(__name__) def get_points_from_file(json_file): """辅助函数,从JSON文件加载点""" with open(json_file, 'r') as f: data = json.load(f) return data['shapes'][0]['points'] def draw_rotated_bounding_boxes(image_path, inner_box_file, outer_box_file, output_path=None): """ 在图片上绘制内框和外框的旋转矩形。 Args: image_path (str): 原始图片的文件路径。 inner_box_file (str): 包含内框坐标的JSON文件路径。 outer_box_file (str): 包含外框坐标的JSON文件路径。 output_path (str, optional): 如果提供,结果图片将被保存到此路径。 默认为None,不保存。 """ # 1. 读取图片 image = cv2.imread(image_path) if image is None: print(f"错误: 无法读取图片 -> {image_path}") return print(f"成功加载图片: {image_path}") # 2. 读取坐标点 inner_points = get_points_from_file(inner_box_file) outer_points = get_points_from_file(outer_box_file) if inner_points is None or outer_points is None: print("因无法加载坐标点,程序终止。") return # 定义颜色 (BGR格式) OUTER_BOX_COLOR = (0, 255, 0) # 绿色 INNER_BOX_COLOR = (0, 0, 255) # 红色 THICKNESS = 10 # 可以根据你的图片分辨率调整线宽 # 3. 处理并绘制外框 # 将点列表转换为OpenCV需要的NumPy数组 outer_contour = np.array(outer_points, dtype=np.int32) # 计算最小面积旋转矩形 outer_rect = cv2.minAreaRect(outer_contour) # 获取矩形的4个角点 outer_box_corners = cv2.boxPoints(outer_rect) # 转换为整数,以便绘制 outer_box_corners_int = np.intp(outer_box_corners) # 在图片上绘制轮廓 cv2.drawContours(image, [outer_box_corners_int], 0, OUTER_BOX_COLOR, THICKNESS) print("已绘制外框 (绿色)。") # 4. 处理并绘制内框 inner_contour = np.array(inner_points, dtype=np.int32) inner_rect = cv2.minAreaRect(inner_contour) inner_box_corners = cv2.boxPoints(inner_rect) inner_box_corners_int = np.intp(inner_box_corners) cv2.drawContours(image, [inner_box_corners_int], 0, INNER_BOX_COLOR, THICKNESS) print("已绘制内框 (红色)。") # 5. 保存结果 (如果指定了路径) if output_path: cv2.imwrite(output_path, image) print(f"结果已保存到: {output_path}") # 6. 显示结果 # OpenCV使用BGR,Matplotlib使用RGB,需要转换颜色通道 image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # 使用Matplotlib显示,因为它在各种环境中(如Jupyter)表现更好 plt.figure(figsize=(10, 15)) # 调整显示窗口大小 plt.imshow(image_rgb) plt.title('旋转框可视化 (外框: 绿色, 内框: 红色)') plt.axis('off') # 不显示坐标轴 plt.show() def analyze_centering_rotated(inner_points: Union[str, List], outer_points: Union[str, List], ): """ 使用旋转矩形进行最精确的分析, 包括定向边距和精确的浮点数比值。 """ if isinstance(inner_points, str): inner_points = get_points_from_file(inner_points) if isinstance(outer_points, str): outer_points = get_points_from_file(outer_points) # 将点列表转换为OpenCV需要的NumPy数组格式 inner_contour = np.array(inner_points, dtype=np.int32) outer_contour = np.array(outer_points, dtype=np.int32) # 计算最小面积的旋转矩形 # 结果格式: ((中心点x, 中心点y), (宽度, 高度), 旋转角度) inner_rect = cv2.minAreaRect(inner_contour) outer_rect = cv2.minAreaRect(outer_contour) # 获取矩形的4个角点, 并转化为坐标 outer_box_corners = cv2.boxPoints(outer_rect) outer_box_corners_int = np.intp(outer_box_corners).tolist() inner_box_corners = cv2.boxPoints(inner_rect) inner_box_corners_int = np.intp(inner_box_corners).tolist() # --- 1. 标准化矩形尺寸,确保宽度总是长边 --- def standardize_rect(rect): (cx, cy), (w, h), angle = rect if w < h: # 如果宽度小于高度,交换它们,并调整角度 w, h = h, w angle += 90 return (cx, cy), (w, h), angle inner_center, inner_dims, inner_angle = standardize_rect(inner_rect) outer_center, outer_dims, outer_angle = standardize_rect(outer_rect) print("\n--- 基于旋转矩形的精确分析 ---") print( f"内框 (标准化后): 中心=({inner_center[0]:.1f}, {inner_center[1]:.1f}), 尺寸=({inner_dims[0]:.1f}, {inner_dims[1]:.1f}), 角度={inner_angle:.1f}°") print( f"外框 (标准化后): 中心=({outer_center[0]:.1f}, {outer_center[1]:.1f}), 尺寸=({outer_dims[0]:.1f}, {outer_dims[1]:.1f}), 角度={outer_angle:.1f}°") # --- 2. 评估居中度 (基于中心点) --- offset_x_abs = abs(inner_center[0] - outer_center[0]) offset_y_abs = abs(inner_center[1] - outer_center[1]) print(f"\n[居中度] 图像坐标系绝对中心偏移: 水平={offset_x_abs:.2f} px | 垂直={offset_y_abs:.2f} px") # --- 3. 评估平行度 --- angle_diff = abs(inner_angle - outer_angle) # 处理角度环绕问题 (例如 -89° 和 89° 其实只差 2°) angle_diff = min(angle_diff, 180 - angle_diff) print(f"[平行度] 角度差异: {angle_diff:.2f}° (值越小,内外框越平行)") # --- 4. 计算定向边距和比值 (核心部分) --- # 计算从外框中心指向内框中心的向量 center_delta_vec = (inner_center[0] - outer_center[0], inner_center[1] - outer_center[1]) # 将外框的旋转角度转换为弧度,用于三角函数计算 angle_rad = math.radians(outer_angle) # 计算外框自身的坐标轴单位向量(相对于图像坐标系) # local_x_axis: 沿着外框宽度的方向向量 # local_y_axis: 沿着外框高度的方向向量 local_x_axis = (math.cos(angle_rad), math.sin(angle_rad)) local_y_axis = (-math.sin(angle_rad), math.cos(angle_rad)) # 使用点积 (dot product) 将中心偏移向量投影到外框的局部坐标轴上 # 这能告诉我们,内框中心相对于外框中心,在“卡片自己的水平和垂直方向上”移动了多少 offset_along_width = center_delta_vec[0] * local_x_axis[0] + center_delta_vec[1] * local_x_axis[1] offset_along_height = center_delta_vec[0] * local_y_axis[0] + center_delta_vec[1] * local_y_axis[1] # 计算水平和垂直方向上的总边距 total_horizontal_margin = outer_dims[0] - inner_dims[0] total_vertical_margin = outer_dims[1] - inner_dims[1] # 根据投影的偏移量来分配总边距 # 理想情况下,偏移为0,左右/上下边距各分一半 # 如果有偏移,一侧增加,另一侧减少 margin_left = (total_horizontal_margin / 2) - offset_along_width margin_right = (total_horizontal_margin / 2) + offset_along_width margin_top = (total_vertical_margin / 2) - offset_along_height margin_bottom = (total_vertical_margin / 2) + offset_along_height # print("\n[定向边距分析 (沿卡片方向)]") # print(f"水平边距 (像素): 左={margin_left:.1f} | 右={margin_right:.1f}") # print(f"垂直边距 (像素): 上={margin_top:.1f} | 下={margin_bottom:.1f}") # # print("\n[精确边距比值分析]") # # 直接展示浮点数比值 # print(f"水平比值 (左:右) = {margin_left:.2f} : {margin_right:.2f}") # print(f"垂直比值 (上:下) = {margin_top:.2f} : {margin_bottom:.2f}") # 为了更直观,也可以计算一个百分比 if total_horizontal_margin > 0: left_percent = (margin_left / total_horizontal_margin) * 100 right_percent = (margin_right / total_horizontal_margin) * 100 print(f"水平边距分布: 左 {left_percent:.1f}% | 右 {right_percent:.1f}%") if total_vertical_margin > 0: top_percent = (margin_top / total_vertical_margin) * 100 bottom_percent = (margin_bottom / total_vertical_margin) * 100 print(f"垂直边距分布: 上 {top_percent:.1f}% | 下 {bottom_percent:.1f}%") return ((left_percent, right_percent), (top_percent, bottom_percent), angle_diff), inner_box_corners_int, outer_box_corners_int def formate_center_data(center_result, inner_data: dict, outer_data: dict, inner_rect_points: List, outer_rect_points: List): data = { "box_result": { "center_inference": { "angel_diff": center_result[2], "center_left": center_result[0][0], "center_right": center_result[0][1], "center_top": center_result[1][0], "center_bottom": center_result[1][1] } } } data['box_result']['inner_box'] = inner_data data['box_result']['outer_box'] = outer_data data['box_result']['inner_box']['shapes'][0]['rect_box'] = inner_rect_points data['box_result']['outer_box']['shapes'][0]['rect_box'] = outer_rect_points return data # if __name__ == "__main__": # img_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\temp\250805_pokemon_0001.jpg" # inner_file_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\temp\inner\250805_pokemon_0001.json" # outer_file_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\temp\outer\250805_pokemon_0001.json" # # inner_pts = get_points_from_file(inner_file_path) # print(inner_pts) # print(type(inner_pts)) # # result = analyze_centering_rotated(inner_file_path, outer_file_path) # print(result) # draw_rotated_bounding_boxes(img_path, inner_file_path, outer_file_path)