在Python matplotlib中通过两点绘制直线

0 投票
1 回答
1432 浏览
提问于 2025-04-17 22:16

我有一张图片,想用pyfits把它加载到一个二维数组里。我想在这张图片上画一条穿过两个像素的线,并把加上这条线的图片保存下来(不是绘图)。然后,我还想画一条与之前的线垂直的线,颜色要不同。请问用matplotlib怎么做比较好?我试过用PIL,但没成功。请看看我的代码,给我一些建议。我也附上了图片。

def plotAxes(map, angle, x_centroid, y_centroid):
    hor = math.floor(x_centroid + 20*(math.cos(angle)))
    ver = math.floor(y_centroid - 20*(math.sin(angle)))
    hor1 = math.floor(x_centroid + 20*(math.cos(angle+90.0)))
    ver1 = math.floor(y_centroid - 20*(math.sin(angle+90.0)))
    map_height = len(map)
    map_width = len(map[0])
    point = [ver, hor]
    center = [y_centroid, x_centroid]
    Max = np.max(map)
    array = np.zeros((map_height, map_width), int)
    for i in range(0, map_height):
        for j in range(0, map_width):
            array[i][j] = (math.floor((float(map[i][j])/float(Max))*255))
    im = Image.fromarray(np.uint8(array))
    draw = ImageDraw.Draw(im) 
    draw.line((x_centroid,y_centroid, hor,ver  ), fill="red")
    draw.line((x_centroid,y_centroid, hor1,ver1  ), fill="red")
    im.show()

不过上面的代码似乎没有把线画得垂直,角度看起来是120度,而不是90度。

enter image description here

1 个回答

1

抱歉,我在把角度传给正弦和余弦函数时搞错了。我应该用度数,但我用了弧度,结果就正常工作了。谢谢!

angle = (angle * math.pi)/180
hor = math.floor(x_centroid + 20*(math.cos(angle)))
ver = math.floor(y_centroid - 20*(math.sin(angle)))
hor1 = math.floor(x_centroid + 20*(math.cos(angle+ (math.pi)/2)))
ver1 = math.floor(y_centroid - 20*(math.sin(angle+(math.pi)/2)))

撰写回答