TypeError: Can't convert object of type 'UploadedFile' to 'str' for 'filename'

Hello Streamlit community,
So I’m applying the JPEG standard for image compression, and I want to take an input image from user and convert it to YCrCb image.
The problem is cv2.imread() doesn’t take the input image variable as argument, giving the following error: TypeError: Can’t convert object of type ‘UploadedFile’ to ‘str’ for 'filename’

Here’s my code:

import streamlit as st
import cv2

image = st.file_uploader("Upload an image", type=["JPEG", "JPG", "PNG"])
if image:
   # YCbCr
   img = cv2.imread(image, cv2.COLOR_RGB2YCrCb)
   # Display YCbCr image
   st.image(img, caption="YCbCr image")

What can you suggest to solve this problem?

Thanks in advance.

Hi @nainiayoub -

Please see the docs for file_uploader, which has varying methods of reading the UploadedFile class, depending on the output you require. I would guess that you need to do the bytes method:

bytes_data = uploaded_file.getvalue()

Best,
Randy

I am having a similar issue,
did you manage to solve the problem?

Here is the solution in case it is needed:

import streamlit as st
import cv2
import numpy as np

st.title("YSBCR Image Viewer")

# Display upload file widget
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])

if uploaded_file is not None:
    # Load image using OpenCV
    img = cv2.imdecode(np.fromstring(uploaded_file.read(), np.uint8), 1)

    # Convert image to YSBCR color space
    img_ysbcr = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)

    # Display original and YSBCR images
    st.image(img, caption='Original Image', use_column_width=True)
    st.image(img_ysbcr, caption='YSBCR Image', use_column_width=True)

1 Like

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.