Streamlit上传图片报错:'UploadedFile'对象无'height'属性问题求助
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 pillowin your environment to use thePIL.Imagemodule. - Check for
None: Addingif 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

