[英]Convert Plotly image byte object to numpy array
plotly.io.to_image
function 用於將圖像作為字節返回 ZA8CFDE63311149EB2AC96F8 ( Doc )
我想將這個代表 PNG 圖像的字節 object 轉換為 numpy 數組,以便它可以在 Folium 中用作圖像疊加層。
這是一個例子:
import plotly.graph_objects as go
# Create plot
fig = go.Figure(data =
go.Contour(
z=[[10, 10.625, 12.5, 15.625, 20],
[5.625, 6.25, 8.125, 11.25, 15.625],
[2.5, 3.125, 5., 8.125, 12.5],
[0.625, 1.25, 3.125, 6.25, 10.625],
[0, 0.625, 2.5, 5.625, 10]]
))
# Export byte object
img_bytes = fig.to_image(format="png",width=600, height=350)
我嘗試過使用 PIL:
from PIL import Image
img = Image.frombytes("RGB", (350,600), img_bytes)
獲取ValueError: not enough image data
。
在使這個過程對我來說非常混亂之前,我從未使用過字節 object。
PS:任何其他方式使用 plotly 圖上 map 也很感激。
在Plotly 論壇上得到了有效的答案:
這是將 Plotly 無花果圖像轉換為數組的 function:
import io
from PIL import Image
def plotly_fig2array(fig):
#convert Plotly fig to an array
fig_bytes = fig.to_image(format="png")
buf = io.BytesIO(fig_bytes)
img = Image.open(buf)
return np.asarray(img)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.