python-3.x - PngImageFile 类型的对象不可 JSON 序列化

标签 python-3.x folium

我正在尝试进行图像叠加。我正在使用卫星数据来研究阿根廷上空的现象,但我真的很想通过 folium 使用交互式 map 。到目前为止,在创建图像时,我得到了输出。但是,当我尝试将卫星图像叠加到 basemap 上时,我收到一条错误消息:

Object of type PngImageFile is not JSON serializable

我不知道如何解决它。

from PIL import Image

fig.savefig('GS.png', transparent=True)

img = Image.open("GS.png")


import folium
from folium import plugins


m = folium.Map(location=[-31.416016, -64.188929],  tiles = 'Stamen Terrain')

folium.raster_layers.ImageOverlay(img,
                     [[ya.min(), xa.min()], [ya.max(), xa.max()]],
                     opacity=0.5).add_to(mapa)

mapa

最佳答案

来自 folium.raster_layers.ImageOverlay 的文档,image 参数必须是“字符串、文件或类似数组的对象”:

image (string, file or array-like object) – The data you want to draw on the map. * If string, it will be written directly in the output file. * If file, it’s content will be converted as embedded in the output file. * If array-like, it will be converted to PNG base64 string and embedded in the output.

在您的代码中,您传递了一个 PIL Image

img = Image.open("GS.png")

并且 Image 不可 JSON 序列化。

尝试传递图像文件的路径:

import os
img = os.path.abspath("GS.png")

folium.raster_layers.ImageOverlay(
                     img,
                     [[ya.min(), xa.min()], [ya.max(), xa.max()]],
                     opacity=0.5).add_to(mapa)

或者,如果您确实需要 PIL Image,并且由于您已经有了 numpy(因为它是 folium 的依赖项),您也可以将 Image 转换为传递给 ImageOverlay 之前的 numpy 数组:

img = Image.open("GS.png")

folium.raster_layers.ImageOverlay(
                     numpy.array(img),
                     [[ya.min(), xa.min()], [ya.max(), xa.max()]],
                     opacity=0.5).add_to(mapa)

关于python-3.x - PngImageFile 类型的对象不可 JSON 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55802408/

相关文章:

python - "Pythonic"/将多个变量设置为同一函数调用或列表理解的更优雅的方法

python - 如何使用 python3 -i 加载脚本,但没有 name == main run?

python - 修复了点击 Bokeh 图元素时的 HoverTool TOOLTIPS

python-3.x - 将 jupyter notebook 转换为幻灯片时,绘图图不显示

python - 有没有办法在 Folium 中绘制许多标记?

python - GeoJSON 数据未显示在 Python folium map 中

python - 如何使用 .explore() 显示 geopandas 交互式 map

mysql - 每次项目运行时django都会给出重复的错误

python - 使用值列从 GPS 数据创建插值多边形

python - 带有 OpenStreetMap 数据的等值线图