Opencv-python 计算点到直线的垂足点
代码
import numpy as np
import cv2 as cv
# 获取直线起始,结束点
def get_line_se(img, line):
rows, cols = img.shape[:2]
[vx, vy, x, y] = line
left_y = int((-x * vy / vx) + y)
right_y = int(((cols - x) * vy / vx) + y)
start_point = (0, left_y)
end_point = (right_y, cols - 1)
return start_point, end_point
# 获取直线 与 点的垂足
def get_foot(start_point, end_point, point_a):
start_x, start_y = start_point
end_x, end_y = end_point
pa_x, pa_y = point_a
p_foot = [0, 0]
if start_point[0] == end_point[0]:
p_foot[0] = start_point[0]
p_foot[1] = point_a[1]
return p_foot
k = (end_y - start_y) * 1.0 / (end_x - start_x)
a = k
b = -1.0
c = start_y - k * start_x
p_foot[0] = int((b * b * pa_x - a * b * pa_y - a * c) / (a * a + b * b))
p_foot[1] = int((a * a * pa_y - a * b * pa_x - b * c) / (a * a + b * b))
return p_foot
def main():
img_org = np.zeros((400, 400, 3), np.uint8)
line = [0.834612, 0.55083823, 44.620255, 32.430378]
point = (200, 200)
# 获取直线起始,结束点
start_point, end_point = get_line_se(img_org, line)
# 获取直线 与 点的垂足
p_foot = get_foot(start_point, end_point, point)
# 显示结果
img_show = img_org.copy()
cv.line(img_show, start_point, end_point, (255, 0, 0), 3)
cv.circle(img_show, point, 5, (0, 0, 255), -1)
cv.circle(img_show, p_foot, 8, (0, 255, 255), -1)
cv.imshow('img_show', img_show)
# cv.imwrite('img_show.jpg', img_show)
cv.waitKey()
cv.destroyAllWindows()
if __name__ == '__main__':
main()