TypeError: a bytes-like object is required, not 'Tensor'

I am working on a style transfer task, my model returns a tensor. recently I was saving that image using torchvision.utils

torchvision.utils.save_image(genarated_image, result_path)

now I have passed the same image to streamlit.

def image_input():
content_file = st.sidebar.file_uploader("Choose a Content Image", type=["png", "jpg", "jpeg"])
if content_file is not None:
    content = Image.open(content_file)
    content = np.array(content)  # pil to cv
    content = cv2.cvtColor(content, cv2.COLOR_RGB2BGR)
    st.warning("Upload an Image OR Untick the Upload Button)")

WIDTH = st.sidebar.select_slider('QUALITY (May reduce the speed)', list(range(150, 501, 50)), value=200)
content = imutils.resize(content, width=WIDTH)
generated = genarate_image(content)
st.sidebar.image(content, width=300, channels='BGR')
st.image(generated, channels='BGR', clamp=True)

But now streamlit giving me this error.

TypeError: a bytes-like object is required, not ‘Tensor’

is there a way to convert tensor into a “bytes-like object” ?


I suspect the tensor has too many dimensions (probably 4 instead of 3) to be treated as an image.
Also, it is probably the wrong data type, as the error message suggests.

Check the type and shape of the tensor.


If this is the case, you can reduce the dimensions and convert to a numpy array e.g. with numpy.squeeze() or with pytorch itself with generated.numpy().squeeze()

1 Like

It can be solved by transforming tensor to PIL image.