当前位置:   article > 正文

python opencv之提取轮廓并拟合圆

python opencv之提取轮廓并拟合圆

图片存储地址为:C:\Users\Pictures\test.png,该图像图片背景是黑色的,目标区域是亮的,目标区域是两段圆弧和两段曲线构成的封闭区域,其中两段圆弧属于同一个圆,但在目标区域的相对位置,也就是不是相邻的,现在用python+opencv提取轮廓并拟合圆弧的圆心和半径。

1、拟合所有圆弧

  1. import cv2
  2. import numpy as np
  3. # 读取图像
  4. image_path = r'C:\Users\Pictures\test.png'
  5. image = cv2.imread(image_path)
  6. # 转换为灰度图像
  7. gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  8. # 对图像进行二值化处理
  9. _, threshold_image = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY)
  10. # 查找图像轮廓
  11. contours, _ = cv2.findContours(threshold_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  12. # 迭代所有轮廓
  13. for contour in contours:
  14. # 拟合轮廓为圆弧(仅拟合最小外接圆)
  15. (x, y), radius = cv2.minEnclosingCircle(contour)
  16. # 绘制圆弧
  17. cv2.circle(image, (int(x), int(y)), int(radius), (0, 255, 0), 2)
  18. # 显示结果图像
  19. cv2.imshow('Detected Arcs', image)
  20. cv2.waitKey(0)
  21. cv2.destroyAllWindows()

2、拟合最大圆弧

  1. import cv2
  2. import numpy as np
  3. # 读取图像
  4. image_path = r'C:\Users\Pictures\test.png'
  5. image = cv2.imread(image_path)
  6. # 转换为灰度图像
  7. gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  8. # 对图像进行二值化处理
  9. _, threshold_image = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY)
  10. # 查找图像轮廓
  11. contours, _ = cv2.findContours(threshold_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  12. max_radius = 0
  13. max_circle_center = None
  14. # 迭代所有轮廓
  15. for contour in contours:
  16. # 拟合轮廓为圆弧(仅拟合最小外接圆)
  17. (x, y), radius = cv2.minEnclosingCircle(contour)
  18. if radius > max_radius:
  19. max_radius = radius
  20. max_circle_center = (int(x), int(y))
  21. # 绘制最大半径的圆
  22. cv2.circle(image, max_circle_center, int(max_radius), (0, 255, 0), 2)
  23. # 在图像上标注圆心和直径
  24. cv2.putText(image, f"Center: {max_circle_center}", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
  25. cv2.putText(image, f"Diameter: {2 * max_radius}", (50, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
  26. # 显示结果图像
  27. cv2.imshow('Detected Arcs', image)
  28. cv2.waitKey(0)
  29. cv2.destroyAllWindows()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/344975
推荐阅读
相关标签
  

闽ICP备14008679号