gpt4 book ai didi

python - 在绘图上添加透明图片

转载 作者:太空狗 更新时间:2023-10-30 01:25:09 26 4
gpt4 key购买 nike

我下面的 python 脚本在使用 Basemap 模块生成的 map 上添加了一张图片(在这个简单示例中生成了一个矩形)和 GPS 轨迹。
现在我想让两个轨道都变成透明的矩形。通过 alpha kwarg 的轨道没有问题,但我不知道如何为图片做这件事。

import matplotlib.pyplot as plt
from PIL import Image
from matplotlib.offsetbox import AnnotationBbox, OffsetImage
from mpl_toolkits.basemap import Basemap

lats = [ 45, 15 ]
lons = [ 0 , 100 ]

fig = plt.figure( dpi = 300 )
ax = plt.subplot(111)

myBaseMap = Basemap( projection='ortho', lat_0=lats[-1], lon_0=lons[-1] )
myBaseMap.bluemarble()

planeImg = Image.new('RGB', (600, 300), color = 'red')
planeXY = myBaseMap( lons[-1], lats[-1] )
x,y = myBaseMap( lons, lats )

plt.plot( x, y, color='r', alpha=0.5, linewidth=3 )

imagebox = OffsetImage( planeImg , zoom=.4 )

ab = AnnotationBbox( imagebox, myBaseMap( lons[-1], lats[-1] ), xybox=( 0., 0. ), xycoords='data', boxcoords='offset points', frameon=False )
ax.add_artist(ab)
plt.show()

这段代码生成了下面带有透明线的图片。 现在我想以同样的方式使红色矩形透明。

我尝试在注释框和 ax 上使用 set_alpha 方法但没有用。
有任何想法吗 ?

谢谢。

最佳答案

如果您在创建 OffsetImage 之前为图像设置了 alpha 值,则结果看起来与预期一致。 this answer 中解释了如何设置枕头图像的 alpha 值。 .请注意,alpha 值必须介于 0 和 255 之间,而不是 0 和 1。简而言之,您只需要在代码中添加一行(注意我更改了图像分辨率):

import matplotlib.pyplot as plt
from PIL import Image
from matplotlib.offsetbox import AnnotationBbox, OffsetImage
from mpl_toolkits.basemap import Basemap

lats = [ 45, 15 ]
lons = [ 0 , 100 ]

fig = plt.figure( dpi = 100 )
ax = plt.subplot(111)

myBaseMap = Basemap( projection='ortho', lat_0=lats[-1], lon_0=lons[-1] )
myBaseMap.bluemarble()

planeImg = Image.new('RGB', (600, 300), color = 'red')
planeImg.putalpha(128)

planeXY = myBaseMap( lons[-1], lats[-1] )
x,y = myBaseMap( lons, lats )

plt.plot( x, y, color='r', alpha=0.5, linewidth=3 )

imagebox = OffsetImage( planeImg , zoom=.4 )

ab = AnnotationBbox( imagebox, myBaseMap( lons[-1], lats[-1] ), xybox=( 0., 0. ), xycoords='data', boxcoords='offset points', frameon=False )
ax.add_artist(ab)
plt.show()

得到如下图片:

result of the above code

关于python - 在绘图上添加透明图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51809017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com