ajson.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import json
  2. import os
  3. import cv2
  4. import shutil
  5. # 输入文件夹
  6. json_folder = r"\\192.168.50.222\share\zyh\data\via\via_json"
  7. image_folder = r"\\192.168.50.222\share\zqy\colorphoto_for_guanban"
  8. output_folder = r"\\192.168.50.222\share\zyh\data\rgb_tuoyuan_4point"
  9. os.makedirs(output_folder, exist_ok=True)
  10. for json_file in os.listdir(json_folder):
  11. if not json_file.lower().endswith(".json"):
  12. continue
  13. json_path = os.path.join(json_folder, json_file)
  14. with open(json_path, "r", encoding="utf-8") as f:
  15. data = json.load(f)
  16. img_metadata = data.get("_via_img_metadata", {})
  17. for img_info in img_metadata.values():
  18. filename = img_info.get("filename")
  19. regions = img_info.get("regions", [])
  20. # 跳过没有椭圆的图片
  21. ellipses = [r for r in regions if r.get("shape_attributes", {}).get("name") == "ellipse"]
  22. if not ellipses:
  23. continue
  24. # 找图片路径
  25. img_path = os.path.join(image_folder, filename)
  26. if not os.path.exists(img_path):
  27. print(f"图片未找到: {filename}")
  28. continue
  29. # 读取图片尺寸
  30. img = cv2.imread(img_path)
  31. if img is None:
  32. print(f"图片无法读取: {filename}")
  33. continue
  34. height, width = img.shape[:2]
  35. # 构造输出 JSON
  36. output_data = {
  37. "version": "5.0.1",
  38. "flags": {},
  39. "shapes": [],
  40. "imagePath": filename,
  41. "imageHeight": height,
  42. "imageWidth": width
  43. }
  44. for e in ellipses:
  45. cx = e["shape_attributes"]["cx"]
  46. cy = e["shape_attributes"]["cy"]
  47. rx = e["shape_attributes"]["rx"]
  48. ry = e["shape_attributes"]["ry"]
  49. # 四个端点
  50. left = [cx - rx, cy]
  51. right = [cx + rx, cy]
  52. top = [cx, cy - ry]
  53. bottom = [cx, cy + ry]
  54. xmin = min(left[0], right[0], top[0], bottom[0])
  55. xmax = max(left[0], right[0], top[0], bottom[0])
  56. ymin = min(left[1], right[1], top[1], bottom[1])
  57. ymax = max(left[1], right[1], top[1], bottom[1])
  58. shape_data = {
  59. "label": "circle",
  60. "points": [left, right, top, bottom],
  61. "shape_type": "polygon",
  62. "flags": {},
  63. "xmin": int(xmin),
  64. "ymin": int(ymin),
  65. "xmax": int(xmax),
  66. "ymax": int(ymax)
  67. }
  68. output_data["shapes"].append(shape_data)
  69. # 保存 JSON
  70. json_output_path = os.path.join(output_folder, filename.replace(".jpg", ".json"))
  71. with open(json_output_path, "w", encoding="utf-8") as out_f:
  72. json.dump(output_data, out_f, ensure_ascii=False, indent=4)
  73. # 复制图片到输出文件夹
  74. img_output_path = os.path.join(output_folder, filename)
  75. shutil.copy(img_path, img_output_path)
  76. print(f"已生成: {json_output_path} 和 {img_output_path}")