我更好地用图像解释我的问题
我有一个轮廓和一条穿过该轮廓的线。
在轮廓和直线的交点点,我想在直线和轮廓的交点处绘制一条垂直线,直至特定距离。
我知道直线的交点以及斜率。
作为参考,我附上这张图片。
如果你的图片中的蓝线是从A点到B点,而你想在B点画红线,你可以这样做:
v.x = B.x - A.x; v.y = B.y - A.y;
mag = sqrt (v.x*v.x + v.y*v.y); v.x = v.x / mag; v.y = v.y / mag;
temp = v.x; v.x = -v.y; v.y = temp;
C.x = B.x + v.x * length; C.y = B.y + v.y * length;
(请注意,您可以通过简单地对长度求反来在相反方向创建点 D,从而使其在两个方向上延伸。)这是我的函数版本:
def getPerpCoord(aX, aY, bX, bY, length):
vX = bX-aX
vY = bY-aY
#print(str(vX)+" "+str(vY))
if(vX == 0 or vY == 0):
return 0, 0, 0, 0
mag = math.sqrt(vX*vX + vY*vY)
vX = vX / mag
vY = vY / mag
temp = vX
vX = 0-vY
vY = temp
cX = bX + vX * length
cY = bY + vY * length
dX = bX - vX * length
dY = bY - vY * length
return int(cX), int(cY), int(dX), int(dY)
我的版本如下,参考上面@CofeDrink68的回答。
import math
def get_perp_coords(left_x, left_y, right_x, right_y, length, divider):
x_length = right_x - left_x
y_length = right_y - left_y
mag = math.sqrt(x_length**2 + y_length**2)
x_length_norm = x_length / mag
y_length_norm = y_length / mag
# middle point
middle_x = round((left_x + right_x) / 2)
middle_y = round((left_y + right_y) / 2)
# switch
temp = x_length_norm
x_length_norm = -1 * y_length_norm
y_length_norm = temp
# get coords
ratio = 1 / divider
new_x_1 = middle_x + x_length_norm * length * ratio
new_y_1 = middle_y + y_length_norm * length * ratio
new_x_2 = middle_x - x_length_norm * length * (1 - ratio)
new_y_2 = middle_y - y_length_norm * length * (1 - ratio)
# if coords goes beyond the original coordinate system
if new_x_1 < 0 or new_y_1 < 0 or new_x_2 < 0 or new_y_2 < 0:
ratio = 1 - ratio
new_x_1 = middle_x + x_length_norm * length * ratio
new_y_1 = middle_y + y_length_norm * length * ratio
new_x_2 = middle_x - x_length_norm * length * (1 - ratio)
new_y_2 = middle_y - y_length_norm * length * (1 - ratio)
return int(new_x_1), int(new_y_1), int(new_x_2), int(new_y_2)
length
是设置线的长度divider
是设置垂直线上下部分的比例,防止垂直线越过正值坐标系