DrawCenterInfo.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import cv2
  2. import json
  3. import numpy as np
  4. from typing import Union
  5. def draw_boxes_and_center_info(image:Union[str, np.ndarray], json_data:dict):
  6. """
  7. 将JSON数据中的内外框和居中信息绘制到图片上。
  8. Args:
  9. image (str): 原始图片文件的路径。
  10. json_data (dict): 包含内外框检测结果和居中计算结果的字典。
  11. """
  12. try:
  13. if isinstance(image, str):
  14. img = cv2.imread(image)
  15. else:
  16. img = image
  17. if img is None:
  18. raise FileNotFoundError(f"无法读取图片: {image}")
  19. h, w, _ = img.shape # 获取图像的宽度和高度
  20. # --------------------- 绘制内框 (inner_box) ---------------------
  21. if "inner_box" in json_data["box_result"] and json_data["box_result"]["inner_box"]["num"] > 0:
  22. for shape_info in json_data["box_result"]["inner_box"]["shapes"]:
  23. points = np.array(shape_info["points"], dtype=np.int32)
  24. # 绘制多边形
  25. cv2.polylines(img, [points], isClosed=True, color=(0, 230, 130), thickness=2) # 绿色
  26. # 标记内框的标签
  27. cv2.putText(img, "Inner Box", tuple(points[0]), cv2.FONT_HERSHEY_SIMPLEX, 3, (0, 255, 0), 5,
  28. cv2.LINE_AA)
  29. # --------------------- 绘制外框 (outer_box) ---------------------
  30. if "outer_box" in json_data["box_result"] and json_data["box_result"]["outer_box"]["num"] > 0:
  31. for shape_info in json_data["box_result"]["outer_box"]["shapes"]:
  32. points = np.array(shape_info["points"], dtype=np.int32)
  33. # 绘制多边形
  34. cv2.polylines(img, [points], isClosed=True, color=(120, 130, 250), thickness=2)
  35. # 标记外框的标签
  36. cv2.putText(img, "Outer Box", tuple(points[0] + [0, -50]), cv2.FONT_HERSHEY_SIMPLEX, 3, (0, 0, 255), 5,
  37. cv2.LINE_AA)
  38. # --------------------- 显示结果 ---------------------
  39. # 如果需要显示图片
  40. # cv2.imshow("Detection Result", img)
  41. # cv2.waitKey(0)
  42. # cv2.destroyAllWindows()
  43. return img
  44. except FileNotFoundError as e:
  45. print(e)
  46. except Exception as e:
  47. print(f"处理图片时发生错误: {e}")
  48. # if __name__ == '__main__':
  49. # image_file = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\pokemon_front_corner_no_reflect_defect-corner_result.jpg" # 请替换为你的实际图片文件名
  50. #
  51. # # 从JSON文件中加载数据
  52. # json_file_path = r"C:\Code\ML\Project\CheckCardBoxAndDefectServer\_temp_work\pokemon_front_card_center-center_result.json"
  53. # with open(json_file_path, 'r') as f:
  54. # data = json.load(f)
  55. #
  56. # # 调用函数绘制
  57. # img = draw_boxes_and_center_info(image_file, data)
  58. # cv2.imwrite("test01.jpg", img)