曲线上的黄点由" 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)
如何获得从那些计数点(黄点)到霍夫线的垂直距离?换句话说,我想要以下输出。
我想显示绿线,也想知道每条绿线的长度。
我尝试使用维基百科中的公式计算垂直距离,但得到以下输出:enter image description here