python opencv之提取轮廓并拟合圆-拟合最大圆弧

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

上一篇:Centos安装mysql


下一篇:.[backups@airmail.cc].faust勒索病毒深度解析 | 数据恢复 | 数据解密