Python - 求出图像中直线的线性方程
Python - Finding the linear equation of a line in a image
我正在使用 Python v2.7 来完成这项工作。
作为输入,我有一个相对白色的图像,上面有一条清晰的黑线。该线始终是线性的,没有二阶或更高阶的多项式。这条线无论如何都可以在图像上
我试图以 y = ax +b
的形式定义这条线的方程
目前我的方法是找出哪个像素属于该线,然后进行线性回归以获得方程。但是我想找出我需要使用 python 中的哪个函数来实现这一点,这就是我需要帮助的地方
或者您有更简单的方法。
添加一张图片作为示例
好的,所以我最终找到了我想做的非常简单的方法
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))
我正在使用 Python v2.7 来完成这项工作。 作为输入,我有一个相对白色的图像,上面有一条清晰的黑线。该线始终是线性的,没有二阶或更高阶的多项式。这条线无论如何都可以在图像上
我试图以 y = ax +b
的形式定义这条线的方程目前我的方法是找出哪个像素属于该线,然后进行线性回归以获得方程。但是我想找出我需要使用 python 中的哪个函数来实现这一点,这就是我需要帮助的地方
或者您有更简单的方法。
添加一张图片作为示例
好的,所以我最终找到了我想做的非常简单的方法
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))