如何获得每个边界点与hough线之间的垂直距离?

时间:2017-12-11 03:11:09

标签: python matlab opencv image-processing computer-vision

这是我的输入图片。 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)

如何获得从那些计数点(黄点)到霍夫线的垂直距离?换句话说,我想要以下输出。 enter image description here

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

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

1 个答案:

答案 0 :(得分:3)

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

首先,您需要在Hough Line上获得2个随机点a1和a2,以创建矢量表示, A

A = a2 - a1

来自

和vector B

B = b1 - a1

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

幅度=( A T ·B )/ | A |

θ= cos -1 (( T ·B )/ | A || B |)

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

enter image description here