show.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import os
  2. import json
  3. import cv2
  4. import numpy as np
  5. input_folder = r"G:\python_ws_g\data\manycircle"
  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_NEAREST) # 改成最近邻防止圆点模糊
  14. return resized_image
  15. def fit_circle(points):
  16. """最小二乘法拟合圆: 返回 (cx, cy, r)"""
  17. x = points[:, 0]
  18. y = points[:, 1]
  19. A = np.c_[2*x, 2*y, np.ones(len(points))]
  20. b = x**2 + y**2
  21. sol, _, _, _ = np.linalg.lstsq(A, b, rcond=None)
  22. cx, cy, c = sol
  23. r = np.sqrt(c + cx**2 + cy**2)
  24. return cx, cy, r
  25. def visualize_and_save(input_folder, output_folder):
  26. os.makedirs(output_folder, exist_ok=True)
  27. files = [f for f in os.listdir(input_folder) if f.endswith('.json')]
  28. files.sort()
  29. for json_file in files:
  30. json_path = os.path.join(input_folder, json_file)
  31. with open(json_path, 'r', encoding='utf-8') as f:
  32. data = json.load(f)
  33. image_path = os.path.join(input_folder, data["imagePath"])
  34. if not os.path.exists(image_path):
  35. print(f"图像不存在:{image_path}")
  36. continue
  37. image = cv2.imread(image_path)
  38. for shape in data["shapes"]:
  39. label = shape["label"]
  40. points = np.array(shape["points"], dtype=np.float32)
  41. # 画关键点
  42. for (x, y) in points:
  43. cv2.circle(image, (int(x), int(y)), radius=3, color=(0, 255, 0), thickness=-1)
  44. # 拟合圆
  45. if points.shape[0] == 4:
  46. cx, cy, r = fit_circle(points)
  47. cv2.circle(image, (int(cx), int(cy)), int(r), (255, 0, 0), 2) # 蓝色圆
  48. cv2.circle(image, (int(cx), int(cy)), 3, (0, 0, 255), -1) # 圆心红点
  49. # 写标签
  50. x0, y0 = int(points[0][0]), int(points[0][1])
  51. cv2.putText(image, label, (x0, y0 - 5),
  52. cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 1)
  53. resized_image = resize_to_fit(image)
  54. base_name = os.path.splitext(json_file)[0]
  55. save_path = os.path.join(output_folder, base_name + ".jpg")
  56. cv2.imwrite(save_path, resized_image)
  57. print(f"保存图片: {save_path}")
  58. if __name__ == "__main__":
  59. visualize_and_save(input_folder, output_folder)