show.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import os
  2. import json
  3. import cv2
  4. import numpy as np
  5. input_folder = r"G:\python_ws_g\data\arcout" # 你的 JSON + 图片输入文件夹
  6. output_folder = r"G:\python_ws_g\data\arcshow" # 保存带标注图片的文件夹
  7. MAX_WIDTH = 1280
  8. MAX_HEIGHT = 720
  9. def resize_to_fit(image, max_width=MAX_WIDTH, max_height=MAX_HEIGHT):
  10. h, w = image.shape[:2]
  11. scale = min(max_width / w, max_height / h, 1.0) # 只缩小不放大
  12. new_size = (int(w * scale), int(h * scale))
  13. resized_image = cv2.resize(image, new_size, interpolation=cv2.INTER_AREA)
  14. return resized_image
  15. def visualize_and_save(input_folder, output_folder):
  16. os.makedirs(output_folder, exist_ok=True)
  17. files = [f for f in os.listdir(input_folder) if f.endswith('.json')]
  18. files.sort()
  19. for json_file in files:
  20. json_path = os.path.join(input_folder, json_file)
  21. with open(json_path, 'r', encoding='utf-8') as f:
  22. data = json.load(f)
  23. image_path = os.path.join(input_folder, data["imagePath"])
  24. if not os.path.exists(image_path):
  25. print(f"图像不存在:{image_path}")
  26. continue
  27. image = cv2.imread(image_path)
  28. for shape in data["shapes"]:
  29. label = shape["label"]
  30. points = shape["points"]
  31. pts = np.array(points, dtype=np.int32).reshape((-1, 1, 2))
  32. color = (0, 255, 0)
  33. cv2.polylines(image, [pts], isClosed=True, color=color, thickness=2)
  34. x0, y0 = pts[0][0]
  35. cv2.putText(image, label, (x0, y0 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 1)
  36. resized_image = resize_to_fit(image)
  37. base_name = os.path.splitext(json_file)[0]
  38. save_path = os.path.join(output_folder, base_name + ".jpg")
  39. cv2.imwrite(save_path, resized_image)
  40. print(f"保存图片: {save_path}")
  41. if __name__ == "__main__":
  42. visualize_and_save(input_folder, output_folder)