英文:
Directly pass / return image from http response to web interface (streamlit)
问题
这是从API调用中获取图像(作为PNG格式)并将其保存为PNG文件,然后再打开以在Streamlit中显示的代码部分。这段代码的部分内容如下:
from PIL import Image
import requests
import shutil
# 在函数中:
response.raw.decode_content = True
with open("image.png", "wb") as out_file:
shutil.copyfileobj(response.raw, out_file)
# 在Streamlit中:
image = Image.open("image.png")
st.image(image, caption="这是一个标题。")
是否有一种直接将二进制数据返回给st.image()
函数的方法?我猜测,将图像保留在内存中而不是写入本地文件会更高效。我想象中的代码如下:
def get_image():
# 发送POST请求等...
response.raw.decode_content = True
return response.raw
image = get_image()
st.image(image)
我对在Python中处理二进制图像数据完全不熟悉,因此我会感激任何指向有用资源的指导
英文:
I am getting an image (as png) back from an API call. This is then saved as a png file and opened back up to display it in streamlit. This works fine, parts of the code are:
from PIL import Image
import requests
import shutil
# in function:
response.raw.decode_content = True
with open("image.png", "wb") as out_file:
shutil.copyfileobj(response.raw, out_file)
# in streamlit:
image = Image.open("image.png")
st.image(image, caption="This is a caption.")
Is there a way to directly return the binary data to the st.image() function? My guess would be, that it's way more performant to just keep the image in memory instead of writing it to a local file. I am imagining something like:
def get_image():
#post request etc...
response.raw.decode_content = True
return response.raw
image = get_image()
st.image(image)
I am completely new to handling binary image data in python, so I would appreciate any pointers to helpful resources
答案1
得分: 2
因为 st.image
接受一个 BytesIO
对象 作为参数,您可以使用下面的逻辑:
import streamlit as st
from io import BytesIO
import requests
@st.cache_data
def get_image():
url = "https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon@2.png"
r = requests.get(url)
return BytesIO(r.content)
st.image(get_image(), caption="StackOverflow")
输出:
英文:
Since st.image
accepts a BytesIO
object as a parameter, you can use the logic below :
> image
: (numpy.ndarray, [numpy.ndarray], BytesIO, str, or [str])
import streamlit as st
from io import BytesIO
import requests
@st.cache_data
def get_image():
url = "https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon@2.png"
r = requests.get(url)
return BytesIO(r.content)
st.image(get_image(), caption="StackOverflow")
Output :
答案2
得分: 1
Here is the translated code snippet:
from PIL import Image
from io import BytesIO
i = Image.open(BytesIO(r.content))
英文:
If you read the requests doc you will find:
from PIL import Image
from io import BytesIO
i = Image.open(BytesIO(r.content))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论