求助:Streamlit中图片可展示,下载时报Invalid binary data格式错误
问题原因
你遇到的错误是因为denoise_img是skimage处理后得到的浮点型numpy数组,而Streamlit的st.download_button要求data参数必须是可直接下载的二进制数据(比如字节流),无法直接识别numpy数组或PIL Image对象。
解决方法
需要把处理后的图像数组转换成字节流格式,才能让下载按钮正常工作。具体步骤如下:
- 先将浮点型图像数组(范围0-1)转换为8位无符号整数数组(范围0-255),这是图像保存的标准格式
- 将数组转换为PIL Image对象,再通过
BytesIO将其转为字节流
修改后的完整代码:
import streamlit as st from PIL import Image import numpy as np from skimage import img_as_float, img_as_ubyte from skimage.restoration import denoise_nl_means, estimate_sigma from io import BytesIO file = st.file_uploader("请上传足底热成像图", type=["jpg", "png"]) if file is None: st.text("请上传图片文件") else: pic = Image.open(file) st.image(pic, use_column_width=1000) img = img_as_float(pic) sigma_est = np.mean(estimate_sigma(img, multichannel=True)) denoise_img = denoise_nl_means(img, h=1.15 * sigma_est, fast_mode=True,patch_size=5, patch_distance=3, multichannel=True) # 转换图像格式为可保存的字节流 # 1. 浮点转8位整数 denoise_img_ubyte = img_as_ubyte(denoise_img) # 2. 转PIL Image denoise_pil = Image.fromarray(denoise_img_ubyte) # 3. 转为字节流 buf = BytesIO() denoise_pil.save(buf, format="PNG") byte_im = buf.getvalue() st.image(denoise_img,caption= "去噪后图像", use_column_width=400) st.download_button(label="下载图像", data=byte_im, file_name="Denoised.png", mime="image/png")
关键修改点说明
- 使用
skimage的img_as_ubyte将浮点数组转为0-255的uint8数组,避免保存图像时出现颜色异常 - 通过
BytesIO将PIL Image对象转为字节流,这是Streamlit下载按钮能识别的格式 - 确保保存时指定
format="PNG",和下载的文件格式一致
内容的提问来源于stack exchange,提问作者varshadevi jothikumar
相关产品推荐
相关产品推荐

