【问题标题】:How to calculate pixel coordinates having start (x,y) , length in pixel and angle?如何计算具有 start (x,y) 、像素长度和角度的像素坐标?
【发布时间】:2020-09-06 08:42:46
【问题描述】:

我有一张 640 x 640 的图像,我想在上面画线。像 PIL 这样的包允许我写一行的常见任务

line(x1,y1,x2,y2)

其中 x1,y1 是起点,x2,y2 是终点线坐标。我有一个不同的任务,我有 x1,y1 和线长(以像素为单位)和方向角。如何仅使用这些数据计算 x2,y2?
谢谢 埃里克

根据 stackoverflow.com 管理员的建议,我正在修改此评论,而不是在下面单独发布答案,以便为我的问题提供代码加上一个疑问,即此代码适用于 0(零)角绘制直线朝向右侧站点,因为它应该是 90度角看起来像更多的 110 或根据图片的东西。我究竟做错了什么 ?再次提前感谢。

import math
from PIL import Image, ImageDraw

def calc_x2y2(length, angle, x1,y1):
    x2 = x1 + math.cos(angle)*length
    y2 = y1 + math.sin(angle)*length
    return (x2,y2)

w, h = 640, 640
x1,y1 = w/2, h/2
shape = [(x1,y1), calc_x2y2(300,90,x1,y1)]
# creating new Image object
img = Image.new("RGB", (w, h),(225,225,225))
# create line on the image
img1 = ImageDraw.Draw(img)
img1.line(shape, fill="#401eba", width=5)
img.show()

Straight line that should be 90 degree except it's not

【问题讨论】:

标签: python math


【解决方案1】:

你可以用给定的信息制作一个直角三角形。从那里我们可以看到

sin(A) = p/h cos(A) = b/h --- (1)

其中h 是线的长度,A 是角度,hb(base)pperpendicular

我们也知道

X2 = X1+b and Y2 = Y1+p --- (2)

将 (2) 中的 p 和 b 替换为 (1) 你会得到

X2 = X1+cos(A)*h
Y2 = Y1+sin(A)*h

【讨论】:

    【解决方案2】:

    sin(θ) 是垂直/斜边,而 cos(θ) 是底/斜边。因此,这变成了一个简单的数学问题,其中 y2 = y1 + L.sin(θ) 和 x2 = x1 + L.cos(θ)。 因此,新的坐标是:

    (y2 = y1 + L.sin(θ), x2 = x1 + L.cos(θ))

    在哪里 L = 线的长度 θ = 直线与 X 轴的夹角

    【讨论】:

    • 嗨,你为什么在你的答案中使用 L.sin(alpha) ? (刚刚看到答案并没有完全理解它;))
    • 是的,我理解数学以及你是如何做到的,但是 L.sin 很奇怪,你的意思是 L*sin() 吗? (我不明白 L 的用法)
    • 是的,我的意思是 L * sin(角度)。我刚混进数学里。现在,你满意吗?
    • 是的,对不起,只是想理解它
    • 没问题,伙计。乐于助人
    猜你喜欢
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多