将轮廓线转换为直线

Transform contour line as straight line

我有这张图片: 我使用

提取了行
    contours, hierarchy = cv2.findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)

那我有4个轮廓。我的目不仅仅是一行。

您可以使用 fitLine 将直线拟合到等高线。

void cv::fitLine (
        InputArray      points,
        OutputArray     line,
        int     distType,
        double      param,
        double      reps,
        double      aeps 
    ) 

对于二维线,它会将线输出为 (vx, vy, x0, y0):

where (vx, vy) is a normalized vector collinear to the line and (x0, y0) is a point on the line

可能有点晚了,但你可以使用:

  1. 你的图像(不是contours)准备数据:
import cv2
import numpy as np

# Load image
image = cv2.imread('test2.png')
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
edged = cv2.Canny(gray, 30, 100)
  1. 一种聚类方法,可将您的 contours 分组为 KMeans:
from sklearn.cluster import KMeans

# Get the list of points
points = np.argwhere(edged)

# Create 4 clusters of points
kmeans = KMeans(n_clusters=4).fit(points)
  1. 现在,使用 LinearRegression(或 np.polyfit)从 y = mx + b 中找到斜率 m 和截距 b 系数:
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt

# Find coefficients
coeffs = []
for i in range(4):
    idx = np.where(i == kmeans.labels_)[0]
    x = points[idx, 0].reshape(-1, 1)
    y = points[idx, 1]

    reg = LinearRegression().fit(x, y)
    m, b = reg.coef_[0], reg.intercept_  
    coeffs.append((m, b))

    plt.scatter(x, y, s=0.1)
    plt.axline(xy1=(0, b), slope=m, color='k', zorder=-1, lw=0.5)

plt.xlim(0, image.shape[0])
plt.ylim(0, image.shape[1])
plt.show()

输出:

>>> coeffs
[(101.53675590518964, -6345.8426544453905),
 (-68.00736350967681, 62626.8080715293),
 (-0.00030668339485539364, 318.2125762056594),
 (0.001297826071265324, 1622.8759316729752)]

现在你可以找到方程之间的交集了。