gpt4 book ai didi

python - 如何获得每个边界点与霍夫线之间的垂直距离?

转载 作者:太空宇宙 更新时间:2023-11-03 22:08:59 28 4
gpt4 key购买 nike

这是我输入的图片。

enter image description here

曲线上的黄色点是“drawcountours”方法给出的,蓝色直线是霍夫线得到的。这是以下代码:

import numpy as np
import cv2
from matplotlib import pyplot as plt
# from scipy.cluster.vq import vq, kmeans
import numpy as np
import glob



images = glob.glob(r'C:\Users\Desktop\dist.png')

for fname in images:

Image = cv2.imread(fname)

gray = cv2.cvtColor(Image, cv2.COLOR_BGR2GRAY)
ret,seg = cv2.threshold(gray,40,250,cv2.THRESH_BINARY)

# cv2.imshow('H',seg)
# cv2.waitKey(0)


total=0
_, contours, hierarchy = cv2.findContours(seg, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
if cv2.contourArea(c) >80 and cv2.contourArea(c) <2000:
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])

epsilon = 0.001 * cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, epsilon, True)
total+=1

cv2.drawContours(Image, approx, -1, (0, 255, 255), 5)

cv2.imshow('l',Image)
cv2.waitKey(0)

lines = cv2.HoughLines(seg, 7, np.pi / 270, 300)

for rho, theta in lines[0]:
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
x1 = int(x0 + 1000* (-b))
y1 = int(y0 + 1000* (a))
x2 = int(x0 -1000 * (-b))
y2 = int(y0 -1000 * (a))

cv2.line(Image, (x1, y1), (x2,y2), (255, 255, 0), 2)
cv2.imshow('l', Image)
cv2.waitKey(0)

######get line equation#####
points = [(x1, y1), (x2, y2)]
x_coords, y_coords = zip(*points)
A = vstack([x_coords, ones(len(x_coords))]).T
m, c = lstsq(A, y_coords)[0]
print("Line Solution is y = {m}x + {c}".format(m=m, c=c))

#####to convert the obtained line equation to Ax+By+C=0 form######
A = m
B = -1
C = 0
for i in range(1, approx.shape[0]):


per_dis = ((A * approx[i][0][0]) + (B * approx[i][0][1]) + C) / math.sqrt((A ** 2) + (B ** 2)) # the perpendicular distance
inter_x = int(((B * (approx[i][0][0] - (A * approx[i][0][1]))) - (A * C)) / ((A ** 2) + (B ** 2)))#the x coordinate of the intersection point
inter_y = int((A * ((-B * approx[i][0][0]) + (A * approx[i][0][1])) - (B * C)) / ((A ** 2) + (B ** 2)))#the y coordinate of the intersection point

cv2.line(Image, (approx[i][0][0],approx[i][0][1]), (inter_x,inter_y), (255, 0, 255), 2)# to draw the green line

cv2.imshow('l', Image)
cv2.waitKey(0)

如何获得从那些contour 点(黄色点)到hough 线的垂直距离?换句话说,我想要以下输出。

enter image description here

我想显示绿线,还想知道每条绿线的长度。

我尝试使用维基百科的公式计算垂直距离,但得到以下输出:

enter image description here

最佳答案

为了获得该结果,您首先需要了解一些概念。第一个概念是线向量表示。您需要先找到您的线的矢量表示。

首先,您需要在霍夫线上获取 2 个随机点 a1 和 a2,以创建矢量表示 A

A = a2 - a1

和向量B来自

B = b1 - a1

使用这些矢量,您可以使用以下公式计算幅度和角度 θ:

震级 = (AT ⋅ B)/|A|

θ = cos-1((AT ⋅ B)/|A||B|)

然后,使用三角函数,您应该能够找到距离 L,即点到霍夫线之间的距离。

enter image description here

关于python - 如何获得每个边界点与霍夫线之间的垂直距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47745934/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com