Python-查找图像中直线的线性方程

时间:2018-12-27 06:10:36

标签: python image-processing equation linear-equation

我正在使用Python v2.7进行这项工作。 作为输入,我有一个相对白色的图像,上面有清晰的黑线。该线始终是线性的,没有二阶或更高阶的多项式。该行仍然可以在图像上

我正在尝试以y = ax + b

的形式定义这条线的方程式

目前,我的方法是找到属于该线的像素,然后进行线性回归以获得方程。但是我试图找出我需要使用python中的哪个函数来实现这一点,而这正是我需要帮助的地方

或者也许您有一种更简单的方法。

添加一个图像作为示例 line

1 个答案:

答案 0 :(得分:1)

好的,所以我终于找到了想做的简单方式

def estimate_coef(x, y): 
    # number of observations/points 
    n = np.size(x) 

    # mean of x and y vector 
    m_x, m_y = np.mean(x), np.mean(y) 

    # calculating cross-deviation and deviation about x 
    SS_xy = np.sum(y*x) - n*m_y*m_x 
    SS_xx = np.sum(x*x) - n*m_x*m_x 

    # calculating regression coefficients 
    a = SS_xy / SS_xx 
    b = m_y - a*m_x 

    return(a, b) 


# MAIN CODE
# 1. Read image
# 2. find where the pixel belonging to the line are located
# 3. perform linear regression to get coeff

image = []      # contain the image read

# for all images to analyze
for x in range(len(dut.images)):
  print "\n\nimage ",x, dut.images[x]

  # read image (convert to greyscale)
  image  = imread(dut.images[x], mode="L")

  height = image.shape[0] - 1

  threshold = (np.min(image) + np.max(image)) / 2
  line = np.where(image < threshold) #get coordinate of the pixel belonging to the line

  x = line[1] # store the x position
  y = height - line[0] # store the y position. Need to invert because of image origine being on top left corner instead of bottom left

  #position = np.array([x,y])

  a, b = estimate_coef(x, y)
  print("Estimated coefficients:\n \
       a = %.6f \n \
       b = %.6f" % (a, b))