resetjson.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import json
  2. from pathlib import Path
  3. from PIL import Image
  4. # ======================
  5. # Paths Configuration
  6. # ======================
  7. JSON_DIR = Path("/data/share/zyh/master_dataset/circle/huayan_circle/251112_251111/day02_machine")
  8. IMAGE_DIR = Path("/data/share/zyh/master_dataset/circle/huayan_circle/251112_251111/day02_machine") # source images
  9. OUTPUT_DIR = JSON_DIR # overwrite original or use a new folder
  10. # ======================
  11. # Process each JSON
  12. # ======================
  13. for json_file in JSON_DIR.glob("*.json"):
  14. with open(json_file, "r") as f:
  15. data = json.load(f)
  16. # Determine corresponding image file
  17. stem_name = json_file.stem
  18. if stem_name.endswith("_annotations"):
  19. stem_name = stem_name.replace("_annotations", "")
  20. possible_extensions = [".png", ".jpg", ".jpeg"]
  21. img_file = None
  22. for ext in possible_extensions:
  23. candidate = IMAGE_DIR / f"{stem_name}{ext}"
  24. if candidate.exists():
  25. img_file = candidate
  26. break
  27. if img_file is None:
  28. print(f"[WARNING] No image found for JSON: {json_file.name}")
  29. continue
  30. # Load image size
  31. image = Image.open(img_file)
  32. img_width, img_height = image.size
  33. # Convert each entry to LabelMe shape (without arc)
  34. shapes = []
  35. for ann in data if isinstance(data, list) else data.get("annotations", []):
  36. shape = {
  37. "label": ann.get("label", ann.get("class_name", "circle")),
  38. "points": ann.get("points", []),
  39. "shape_type": "polygon",
  40. "flags": {},
  41. "xmin": ann.get("xmin", 0),
  42. "ymin": ann.get("ymin", 0),
  43. "xmax": ann.get("xmax", 0),
  44. "ymax": ann.get("ymax", 0)
  45. }
  46. shapes.append(shape)
  47. # Create LabelMe JSON
  48. labelme_json = {
  49. "version": "5.0.1",
  50. "flags": {},
  51. "shapes": shapes,
  52. "imagePath": img_file.name,
  53. "imageHeight": img_height,
  54. "imageWidth": img_width
  55. }
  56. # Save updated JSON (overwrite or to another folder)
  57. output_path = OUTPUT_DIR / json_file.name
  58. with open(output_path, "w") as f:
  59. json.dump(labelme_json, f, indent=4)
  60. print(f"Processed JSON saved: {output_path.name}")
  61. print("\n? All JSON files converted to LabelMe format (arc removed).")