You need to enable JavaScript to run this app. 如何提升Streamlit图片标注应用从S3下载图片的速度?
优惠活动
大模型
产品
解决方案
定价
更多

如何提升Streamlit图片标注应用从S3下载图片的速度?

优化S3图片加载速度的实用方案

针对你这段从S3加载图片的代码耗时过长的问题,以下是几个直接有效的优化手段:

1. 并行下载替代串行循环

原代码是逐个串行下载图片,改成并行处理能大幅缩短总耗时,利用Python的concurrent.futures实现:

from concurrent.futures import ThreadPoolExecutor
import io
from PIL import Image

def load_image_from_s3(bucket, key):
    file_stream = io.BytesIO()
    bucket.Object(key).download_fileobj(file_stream)
    file_stream.seek(0)  # 重置流指针
    return Image.open(file_stream)

# 先获取所有需要加载的图片key
image_keys = [obj.key for obj in my_bucket.objects.filter(Prefix="images/"+item_data['Img'])]

# 并行加载
with ThreadPoolExecutor(max_workers=5) as executor:
    images = list(executor.map(lambda key: load_image_from_s3(my_bucket, key), image_keys))

注意:max_workers不要设得过高,避免触发S3请求限制

2. 使用S3预签名URL直接渲染

不用下载图片到本地内存,直接生成预签名URL让Streamlit直接加载,跳过本地IO和图片解码的中间步骤:

def get_s3_presigned_url(bucket, key, expires_in=3600):
    return bucket.meta.client.generate_presigned_url(
        'get_object',
        Params={'Bucket': bucket.name, 'Key': key},
        ExpiresIn=expires_in
    )

# 获取所有图片的预签名URL
image_urls = [get_s3_presigned_url(my_bucket, obj.key) for obj in my_bucket.objects.filter(Prefix="images/"+item_data['Img'])]

# 在Streamlit中直接显示
for url in image_urls:
    st.image(url)

这种方式把图片加载的压力转移到浏览器,后端只负责生成URL,耗时会显著降低。

3. 开启S3传输加速+优化boto3配置

  • 开启S3存储桶的传输加速功能,通过CloudFront的全球边缘节点加速数据传输
  • 调整boto3的下载配置,增大分块大小、优化超时:
from boto3.s3.transfer import TransferConfig

# 配置更大的分块大小(比如10MB)
config = TransferConfig(multipart_threshold=1024*1024*10, max_concurrency=5)

# 下载时指定配置
bucket.Object(key).download_fileobj(file_stream, Config=config)

4. 本地/内存缓存已加载的图片

如果标注过程中会重复加载相同图片,用缓存避免重复下载:

import functools
from streamlit import cache_data

# 用Streamlit的缓存装饰器缓存图片加载结果
@functools.lru_cache(maxsize=32)  # 或者用st.cache_data
def load_image_cached(bucket_name, key):
    # 这里需要传入bucket名称而不是bucket对象,因为对象不能被缓存
    s3 = boto3.resource('s3')
    bucket = s3.Bucket(bucket_name)
    file_stream = io.BytesIO()
    bucket.Object(key).download_fileobj(file_stream)
    file_stream.seek(0)
    return Image.open(file_stream)

# 使用缓存函数加载
images = [load_image_cached(my_bucket.name, obj.key) for obj in my_bucket.objects.filter(Prefix="images/"+item_data['Img'])]

5. 预处理图片(提前压缩/转格式)

在上传图片到S3时,就将图片压缩到标注所需的尺寸(比如1080p以内),或者转换为WebP、AVIF等更高效的格式,减少传输的数据量,从根源上降低下载耗时。

内容的提问来源于stack exchange,提问作者userInThisWorld

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 01:40:27