5show.py 2.1 KB

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