p1点和p2点是一条线段的两端,沿着p1指向p2的方向,将线段长度延伸长度x,求延伸后的点ep。如下图:
Python代码:
import mathdef extend_line_segment(p1, p2, extension_length):"""延伸线段长度并返回延伸后的点坐标参数:p1: list,起始点的坐标 [x1, y1]p2: list,结束点的坐标 [x2, y2]extension_length: float,延伸长度返回值:list,延伸后的点的坐标 [x, y]"""# 计算p1指向p2的向量vector = [p2[0] - p1[0], p2[1] - p1[1]]# 计算向量的模magnitude = math.sqrt(vector[0] ** 2 + vector[1] ** 2)# 单位化向量unit_vector = [vector[0] / magnitude, vector[1] / magnitude]# 判断线段是否水平或垂直if p1[0] == p2[0]: # 垂直线段extended_point = [p2[0], p2[1] + extension_length]elif p1[1] == p2[1]: # 水平线段extended_point = [p2[0] + extension_length, p2[1]]else: # 其他情况# 计算延伸后的点extended_point = [p2[0] + unit_vector[0] * extension_length, p2[1] + unit_vector[1] * extension_length]return extended_pointif __name__ == '__main__':p1 = [10, 200]p2 = [110, 100]extend_p = extend_line_segment(p1, p2, 300)print("延伸后的点坐标: ", extend_p)# 绘制图import matplotlib.pyplot as pltplt.plot([p1[0], p2[0]], [p1[1], p2[1]], 'r-')plt.plot([p2[0], extend_p[0]], [p2[1], extend_p[1]], 'b-')# 加注释plt.annotate('p1', xy=(p1[0], p1[1]), xytext=(p1[0], p1[1]))plt.annotate('p2', xy=(p2[0], p2[1]), xytext=(p2[0], p2[1]))plt.annotate('ep', xy=(extend_p[0], extend_p[1]), xytext=(extend_p[0] + 5, extend_p[1] + 5))# 等距plt.axis('equal')plt.show()
C++:
cv::Point2f extend_line_segment(const cv::Point2f& p1, const cv::Point2f& p2, double extension_length) {// 计算p1指向p2的向量cv::Point2f vector = {p2.x - p1.x, p2.y - p1.y};// 计算向量的模double magnitude = sqrt(vector.x * vector.x + vector.y * vector.y);// 单位化向量cv::Point2f unit_vector = {static_cast<float>(vector.x / magnitude), static_cast<float>(vector.y / magnitude)};// 判断线段是否水平或垂直if (p1.x == p2.x) { // 垂直线段cv::Point2f extended_point = {p2.x, static_cast<float>(p2.y + extension_length)};return extended_point;} else if (p1.y == p2.y) { // 水平线段cv::Point2f extended_point = {static_cast<float>(p2.x + extension_length), p2.y};return extended_point;} else { // 其他情况// 计算延伸后的点cv::Point2f extended_point = {static_cast<float>(p2.x + unit_vector.x * extension_length), static_cast<float>(p2.y + unit_vector.y * extension_length)};return extended_point;}
}