|
@@ -0,0 +1,68 @@
|
|
|
|
|
+import cv2
|
|
|
|
|
+import json
|
|
|
|
|
+import numpy as np
|
|
|
|
|
+from typing import Union
|
|
|
|
|
+
|
|
|
|
|
+def draw_boxes_and_center_info(image:Union[str, np.ndarray], json_data:dict):
|
|
|
|
|
+ """
|
|
|
|
|
+ 将JSON数据中的内外框和居中信息绘制到图片上。
|
|
|
|
|
+
|
|
|
|
|
+ Args:
|
|
|
|
|
+ image (str): 原始图片文件的路径。
|
|
|
|
|
+ json_data (dict): 包含内外框检测结果和居中计算结果的字典。
|
|
|
|
|
+ """
|
|
|
|
|
+ try:
|
|
|
|
|
+ if isinstance(image, str):
|
|
|
|
|
+ img = cv2.imread(image)
|
|
|
|
|
+ else:
|
|
|
|
|
+ img = image
|
|
|
|
|
+ if img is None:
|
|
|
|
|
+ raise FileNotFoundError(f"无法读取图片: {image}")
|
|
|
|
|
+
|
|
|
|
|
+ h, w, _ = img.shape # 获取图像的宽度和高度
|
|
|
|
|
+
|
|
|
|
|
+ # --------------------- 绘制内框 (inner_box) ---------------------
|
|
|
|
|
+ if "inner_box" in json_data["box_result"] and json_data["box_result"]["inner_box"]["num"] > 0:
|
|
|
|
|
+ for shape_info in json_data["box_result"]["inner_box"]["shapes"]:
|
|
|
|
|
+ points = np.array(shape_info["points"], dtype=np.int32)
|
|
|
|
|
+ # 绘制多边形
|
|
|
|
|
+ cv2.polylines(img, [points], isClosed=True, color=(0, 230, 130), thickness=2) # 绿色
|
|
|
|
|
+ # 标记内框的标签
|
|
|
|
|
+ cv2.putText(img, "Inner Box", tuple(points[0]), cv2.FONT_HERSHEY_SIMPLEX, 3, (0, 255, 0), 5,
|
|
|
|
|
+ cv2.LINE_AA)
|
|
|
|
|
+
|
|
|
|
|
+ # --------------------- 绘制外框 (outer_box) ---------------------
|
|
|
|
|
+ if "outer_box" in json_data["box_result"] and json_data["box_result"]["outer_box"]["num"] > 0:
|
|
|
|
|
+ for shape_info in json_data["box_result"]["outer_box"]["shapes"]:
|
|
|
|
|
+ points = np.array(shape_info["points"], dtype=np.int32)
|
|
|
|
|
+ # 绘制多边形
|
|
|
|
|
+ cv2.polylines(img, [points], isClosed=True, color=(120, 130, 250), thickness=2)
|
|
|
|
|
+ # 标记外框的标签
|
|
|
|
|
+ cv2.putText(img, "Outer Box", tuple(points[0] + [0, -50]), cv2.FONT_HERSHEY_SIMPLEX, 3, (0, 0, 255), 5,
|
|
|
|
|
+ cv2.LINE_AA)
|
|
|
|
|
+ # --------------------- 显示结果 ---------------------
|
|
|
|
|
+
|
|
|
|
|
+ # 如果需要显示图片
|
|
|
|
|
+ # cv2.imshow("Detection Result", img)
|
|
|
|
|
+ # cv2.waitKey(0)
|
|
|
|
|
+ # cv2.destroyAllWindows()
|
|
|
|
|
+ return img
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+ except FileNotFoundError as e:
|
|
|
|
|
+ print(e)
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ print(f"处理图片时发生错误: {e}")
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+# if __name__ == '__main__':
|
|
|
|
|
+# image_file = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\pokemon_front_corner_no_reflect_defect-corner_result.jpg" # 请替换为你的实际图片文件名
|
|
|
|
|
+#
|
|
|
|
|
+# # 从JSON文件中加载数据
|
|
|
|
|
+# json_file_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\pokemon_front_card_center-center_result.json"
|
|
|
|
|
+# with open(json_file_path, 'r') as f:
|
|
|
|
|
+# data = json.load(f)
|
|
|
|
|
+#
|
|
|
|
|
+# # 调用函数绘制
|
|
|
|
|
+# img = draw_boxes_and_center_info(image_file, data)
|
|
|
|
|
+# cv2.imwrite("test01.jpg", img)
|