要实现基于简化后的轮廓并使用数学方法进行圆弧拟合,确保轮廓圆滑没有任何角度,可以尝试更先进的数学方法或库,如使用Bézier曲线或在Python中寻找适合的库进行圆弧拟合。然而,需要明确的是,标准的OpenCV库并没有直接提供圆弧拟合功能。这意味着我们需要利用数学和几何逻辑来逼近这一过程。
python
import numpy as np
import matplotlib.pyplot as plt
import cv2
def find_contours_and_simplify(img_path):
image = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)
mask = image[:, :, 3] if image.shape[2] == 4 else cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
mask = cv2.threshold(mask, 1, 255, cv2.THRESH_BINARY)[1]
contours, _ = cv2.findContours(mask, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_SIMPLE)
# 返回最大的轮廓
max_contour = max(contours, key=cv2.contourArea)
simplified_contour = cv2.approxPolyDP(max_contour, epsilon=cv2.arcLength(max_contour, True) * 0.02, closed=True)
return simplified_contour.squeeze()
def three_point_circle(p1, p2, p3):
"""
通过三个点计算圆的中心和半径
p1, p2, p3: (x, y)坐标
返回:圆的中心(cx, cy)和半径radius
"""
# 转换为numpy数组
p1, p2, p3 = np.array(p1), np.array(p2), np.array(p3)
# 计算两条中垂线的斜率和截距
midpoint1 = (p1 + p2) / 2
midpoint2 = (p2 + p3) / 2
if p2[0] - p1[0] != 0:
slope1 = -(p2[1] - p1[1]) / (p2[0] - p1[0])
intercept1 = midpoint1[1] - slope1 * midpoint1[0]
else:
slope1, intercept1 = None, None
if p3[0] - p2[0] != 0:
slope2 = -(p3[1] - p2[1]) / (p3[0] - p2[0])
intercept2 = midpoint2[1] - slope2 * midpoint2[0]
else:
slope2, intercept2 = None, None
# 计算圆心
if slope1 is None:
cx = midpoint1[0]
cy = slope2 * cx + intercept2
elif slope2 is None:
cx = midpoint2[0]
cy = slope1 * cx + intercept1
else:
cx = (intercept2 - intercept1) / (slope1 - slope2)
cy = slope1 * cx + intercept1
radius = np.linalg.norm(np.array([cx, cy]) - p1)
return (cx, cy), radius
def plot_arc(p1, p2, p3):
center, radius = three_point_circle(p1, p2, p3)
angle1 = np.arctan2(p1[1] - center[1], p1[0] - center[0])
angle2 = np.arctan2(p3[1] - center[1], p3[0] - center[0])
# 确定绘制圆弧的角度范围
angles = np.linspace(angle1, angle2, num=100) if angle1 < angle2 else np.linspace(angle2, angle1, num=100)
# 计算圆弧上的点并绘制
x = center[0] + radius * np.cos(angles)
y = center[1] + radius * np.sin(angles)
plt.plot(x, y, 'g-')
img_path = 'path/to/your/image.png'
contour = find_contours_and_simplify(img_path)
plt.figure(figsize=[6,6])
for i in range(len(contour)-2):
plot_arc(contour[i], contour[i+1], contour[i+2])
plt.axis('equal')
plt.show()