You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Streamlit上传图片报错:'UploadedFile'对象无'height'属性问题求助

Fixing AttributeError for Uploaded Images in Your Where's Waldo Streamlit App

Hey there! Let's sort out that AttributeError: 'UploadedFile' object has no attribute 'height' issue you're facing. The problem boils down to a simple misunderstanding of what st.file_uploader returns:

Why the Error Happens

Streamlit's st.file_uploader gives you an UploadedFile object, which is essentially a file-like stream of your uploaded image—it's not a ready-to-use image object with properties like height or width. That's why trying to access img.height or convert it directly with asarray(img) won't work.

The Fix: Convert to a PIL Image First

You need to first convert the uploaded file stream into a proper image object using PIL (Pillow), which will give you access to the image's metadata and let you convert it to a numpy array correctly. Here's how to adjust your code:

import streamlit as st
from PIL import Image
import numpy as np
from numpy import asarray

st.title("Where's Waldo?")
uploaded_picture = st.file_uploader("Upload a picture of the following game: Where's Waldo?", type=['png', 'jpg'])

# Always check if a file was uploaded before processing
if uploaded_picture is not None:
    # Step 1: Convert the UploadedFile to a PIL Image
    img = Image.open(uploaded_picture)
    
    # Step 2: Convert the PIL Image to a numpy array (for your recognition logic)
    img_array = asarray(img)
    
    # Step 3: Get image dimensions (you can use either PIL's attributes or the array's shape)
    # Option 1: From PIL Image
    # img_height, img_width = img.height, img.width
    # Option 2: From numpy array (more useful if you're working with the array later)
    img_height, img_width = img_array.shape[:2]
    
    # Now generate your output_array with the correct dimensions
    output_array = np.zeros((int(img_height / 64), int(img_width / 64)))
    
    # Optional: Display the uploaded image to confirm
    st.image(img, caption="Uploaded Waldo Image", use_column_width=True)
    
    # Continue with your Waldo detection logic here...

Key Notes

  • Install Pillow if you haven't: Run pip install pillow in your environment to use the PIL.Image module.
  • Check for None: Adding if uploaded_picture is not None: prevents errors when the user hasn't uploaded an image yet.
  • Dimension Options: You can get height/width from either the PIL Image (img.height) or the numpy array (img_array.shape[0] for height, shape[1] for width)—use whichever fits your workflow better.

This should resolve the AttributeError and let you process the uploaded image just like you did with local file paths!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:54:07