I have this image: I extracted lines using
contours, hierarchy = cv2.findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
I have 4 contours then. My goal is to convert this lines as infinite straight lines (so I can detect overlap points of those lines then. Is this somehow possible? I tried hough lines, but it gives unpredictable solutions, in some cases lines doesnt have enough length, or there is much more lines than just one.
You can use fitLine to fit a straight line to a contour.
void cv::fitLine (
InputArray points,
OutputArray line,
int distType,
double param,
double reps,
double aeps
)
For 2D lines, it'll output the line as (vx, vy, x0, y0):
where (vx, vy) is a normalized vector collinear to the line and (x0, y0) is a point on the line
Maybe a bit late but you can use:
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)
contours
like 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)
m
and the intercept b
coefficients from y = mx + b
with LinearRegression
(or np.polyfit
):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()
Output:
>>> coeffs
[(101.53675590518964, -6345.8426544453905),
(-68.00736350967681, 62626.8080715293),
(-0.00030668339485539364, 318.2125762056594),
(0.001297826071265324, 1622.8759316729752)]
Now you can find the intersection between equations.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.