show.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import json
  2. import os
  3. import cv2
  4. import shutil
  5. import math
  6. # 输入文件夹
  7. json_folder = r"\\192.168.50.222\share\zyh\data\via\via_json"
  8. image_folder = r"\\192.168.50.222\share\zqy\colorphoto_for_guanban"
  9. output_folder = r"\\192.168.50.222\share\zyh\data\rgb_tuoyuan_draw"
  10. os.makedirs(output_folder, exist_ok=True)
  11. for json_file in os.listdir(json_folder):
  12. if not json_file.lower().endswith(".json"):
  13. continue
  14. json_path = os.path.join(json_folder, json_file)
  15. with open(json_path, "r", encoding="utf-8") as f:
  16. data = json.load(f)
  17. img_metadata = data.get("_via_img_metadata", {})
  18. for img_info in img_metadata.values():
  19. filename = img_info.get("filename")
  20. regions = img_info.get("regions", [])
  21. # 提取椭圆
  22. ellipses = [r for r in regions if r.get("shape_attributes", {}).get("name") == "ellipse"]
  23. if not ellipses:
  24. continue
  25. # 找图片路径
  26. img_path = os.path.join(image_folder, filename)
  27. if not os.path.exists(img_path):
  28. print(f"图片未找到: {filename}")
  29. continue
  30. img = cv2.imread(img_path)
  31. if img is None:
  32. print(f"图片无法读取: {filename}")
  33. continue
  34. # 绘制椭圆
  35. for e in ellipses:
  36. cx = e["shape_attributes"]["cx"]
  37. cy = e["shape_attributes"]["cy"]
  38. rx = e["shape_attributes"]["rx"]
  39. ry = e["shape_attributes"]["ry"]
  40. theta = e["shape_attributes"].get("theta", 0) # 弧度
  41. # OpenCV ellipse 角度需要度数,顺时针
  42. angle_deg = -math.degrees(theta)
  43. center = (int(cx), int(cy))
  44. axes = (int(rx), int(ry))
  45. cv2.ellipse(img, center, axes, angle_deg, 0, 360, (0, 255, 0), 2)
  46. # 保存画好的图片
  47. img_output_path = os.path.join(output_folder, filename)
  48. cv2.imwrite(img_output_path, img)
  49. print(f"已生成带椭圆标注的图片: {img_output_path}")