numpy 我怎样才能找到相交线的中心点?

d8tt03nd  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(84)

我试图找到中心点的线加入如下图所示

如下所示

我尝试了下面的方法,但我无法找到一个逻辑来找到连接线的确切位置

import cv2
import numpy as np
from skimage.transform import hough_line, hough_line_peaks
import matplotlib.pyplot as plt
from matplotlib import cm
from numpy.linalg import LinAlgError
from imutils import paths 
get_all_imgs = list(paths.list_images(r"img.png"))

for img_f in get_all_imgs:
# Load the image
img = cv2.imread(img_f)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_blue = np.array([26, 0, 0])
upper_blue = np.array([52, 255, 255])
hsvmask = cv2.inRange(hsv, lower_blue, upper_blue)

# Perform Hough Transform to detect lines
h, theta, d = hough_line(hsvmask)

# Function to find intersection of two lines
def intersection(line1, line2):
    rho1, theta1 = line1
    rho2, theta2 = line2
    A = np.array([
        [np.cos(theta1), np.sin(theta1)],
        [np.cos(theta2), np.sin(theta2)]
    ])
    b = np.array([[rho1], [rho2]])
    try:
        x0, y0 = np.linalg.solve(A, b)
        x0, y0 = int(np.round(x0)), int(np.round(y0))
        return [x0, y0]
    except LinAlgError:
        return None

# Find intersections
intersections = []
lines = list(zip(*hough_line_peaks(h, theta, d)))
for i, line1 in enumerate(lines):
    for line2 in lines[i+1:]:
        if line1 != line2:
            intersect = intersection((line1[2], line1[1]), (line2[2], line2[1]))
            if intersect is not None:
                intersections.append(intersect)

# Find the intersection point with the shortest distance to the origin
distances = [np.sqrt(x**2 + y**2) for x, y in intersections]
min_distance_index = np.argmin(distances)
min_distance_point = intersections[min_distance_index]

# Plot the results
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
ax.imshow(hsvmask, cmap=cm.gray)
for _, angle, dist in zip(*hough_line_peaks(h, theta, d)):
    (x0, y0) = dist * np.array([np.cos(angle), np.sin(angle)])
    ax.axline((x0, y0), slope=np.tan(angle + np.pi/2), color='red')

# Plot the intersection point with the shortest distance
ax.plot(min_distance_point[0], min_distance_point[1], 'bo')

plt.tight_layout()
plt.show()

输出为

任何帮助或建议来解决这个问题将是有益的

kfgdxczn

kfgdxczn1#

如果在直角坐标系(a,B,c)中定义直线,其中ax+by+c=0,例如:

>>> lines = np.array([[1,0,-1], [1,0,-3], [-1,1,-1], [-1,1,3]])

可以将超定线性系统Ax=B定义为:

>>> A = lines[:, :2]
>>> B = -lines[:, 2]

然后使用lstsq()(近似)求解它,以获得所有直线的最近点:

>>> np.linalg.lstsq(A, B)[0]
array([2., 1.])

相关问题