python 对二值化图像中的边缘像素点进行拟合曲线,并画图
时间: 2024-05-09 08:15:41 浏览: 16
要对二值化图像中的边缘像素点进行拟合曲线,可以使用 OpenCV 库中的 `findContours` 函数找到边缘像素的坐标,然后使用 `fitLine` 函数对这些坐标进行拟合得到一条直线,或者使用 `approxPolyDP` 函数对这些坐标进行多边形拟合得到曲线。
以下是一个例子,假设我们有一张二值化的图像,并且已经使用 `findContours` 函数找到了边缘像素的坐标:
```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 读入二值化图像
img = cv2.imread('binary_image.png', cv2.IMREAD_GRAYSCALE)
# 找到边缘像素的坐标
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contour_pts = contours[0][:, 0, :]
# 对坐标进行拟合
# 使用 fitLine 函数,得到一条直线
vx, vy, x0, y0 = cv2.fitLine(contour_pts, cv2.DIST_L2, 0, 0.01, 0.01)
line_pts = np.array([[x0 - vx * 1000, y0 - vy * 1000], [x0 + vx * 1000, y0 + vy * 1000]], np.int32)
# 使用 approxPolyDP 函数,得到曲线
epsilon = 0.1 * cv2.arcLength(contour_pts, True)
curve_pts = cv2.approxPolyDP(contour_pts, epsilon, True)
# 绘制结果
plt.imshow(img, cmap='gray')
plt.plot(contour_pts[:, 0], contour_pts[:, 1], '.r')
plt.plot(line_pts[:, 0], line_pts[:, 1], '-b')
plt.plot(curve_pts[:, 0, 0], curve_pts[:, 0, 1], '-g')
plt.show()
```
在这个例子中,我们先使用 `findContours` 函数找到边缘像素的坐标,然后使用 `fitLine` 函数得到一条直线,或者使用 `approxPolyDP` 函数得到曲线。最后使用 Matplotlib 库中的 `plot` 函数将结果绘制出来。