showarc.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import cv2
  2. import numpy as np
  3. import math
  4. def draw_arc_on_image(
  5. image_path,
  6. output_path,
  7. params,
  8. thickness=2,
  9. color=(0, 0, 255)
  10. ):
  11. """
  12. Draw ellipse arc on an image using given parameters.
  13. Args:
  14. image_path (str): path to the input image.
  15. output_path (str): path to save the output image.
  16. params (list or tensor): [cx, cy, a, b, theta1, theta2, theta3]
  17. cx, cy: center of ellipse
  18. a, b: long and short axis (radius, not diameter)
  19. theta1, theta2, theta3: angle range (radians)
  20. thickness (int): thickness of the arc.
  21. color (tuple): BGR color.
  22. Notes:
  23. OpenCV ellipse uses:
  24. - center (int, int)
  25. - axis lengths (int, int) are *half lengths*
  26. - rotation angle in degrees
  27. - startAngle, endAngle in degrees
  28. """
  29. # Load image
  30. img = cv2.imread(image_path)
  31. if img is None:
  32. raise FileNotFoundError(f"Image not found: {image_path}")
  33. cx, cy, a, b, t1, t2, t3 = params
  34. # Convert to int for OpenCV
  35. cx = int(cx)
  36. cy = int(cy)
  37. a = int(a) # long axis (radius)
  38. b = int(b) # short axis (radius)
  39. # Convert radian to degree
  40. t1_deg = math.degrees(t1)
  41. t2_deg = math.degrees(t2)
  42. t3_deg = math.degrees(t3)
  43. # If you want full ellipse:
  44. # cv2.ellipse(img, (cx, cy), (a, b), 0, 0, 360, color, thickness)
  45. # Draw arc only (theta1 -> theta2)
  46. cv2.ellipse(
  47. img,
  48. (cx, cy),
  49. (a, b),
  50. 0, # rotation angle of ellipse
  51. t1_deg, # start angle
  52. t2_deg, # end angle
  53. color,
  54. thickness
  55. )
  56. # Optionally draw second arc ¦È2 ¡ú ¦È3
  57. cv2.ellipse(
  58. img,
  59. (cx, cy),
  60. (a, b),
  61. 0,
  62. t2_deg,
  63. t3_deg,
  64. (0, 255, 0), # different color for visualization
  65. thickness
  66. )
  67. # Save output
  68. cv2.imwrite(output_path, img)
  69. print(f"[Saved] Arc drawn on image -> {output_path}")
  70. # Example usage:
  71. if __name__ == "__main__":
  72. params = [651.5971, 491.6041, 4.5752, 4.3241, 1.1640, 3.0971, 3.1106]
  73. draw_arc_on_image(
  74. image_path=r"/home/zhaoyinghan/下载/imageData.png",
  75. output_path="output_arc.png",
  76. params=params
  77. )