How to convert a PIL Image to a fastai Image object?

I am using a file_uploader from streamlit to get images into PIL JpegImageFile format :

import streamlit as st

inferencer = load_learner(path)

img_bytes = st.file_uploader("Squash It!!", type=['png', 'jpg', 'jpeg'])
if img_bytes is not None:
    st.write("Image Uploaded Successfully:")
    img = PIL.Image.open(img_bytes)

    pred_class, pred_idx, outputs = inferencer.predict(img)
    for out in outputs:
        st.write(out)

    st.write("Decision: ", pred_class)

However, I can’t find a method in the docs that will convert a PIL Image to a fastai Image. It seems without having that fastai wrapper, I can’t do inference. I get the error:

'JpegImageFile' object has no attribute 'apply_tfms'
File "C:\Users\WNeill\PycharmProjects\fastai-homework\Lesson2-v3\inference.py", line 20, in <module>
    pred_class, pred_idx, outputs = inferencer.predict(img)

PILImage.create(img_bytes)

Hi @arora_aman, I do not see that method in the docs for fastai… Can you point me to the documentation?

Edit: I think what you are referring to is part of the new library. I am going through the v3 course and have no desire to try implementing fastai2. I tried it once, and will not again.

TLDR

img_fastai = Image(img_tensor)

Thorough

from fastai.vision import *
import torchvision.transforms as T

img_pil = PIL.Image.open(path2img)
img_tensor = T.ToTensor()(img_pil)
img_fastai = Image(img_tensor)

3 Likes

Thank you, that worked like a charm! I’m not familiar with the underlying PyTorch yet (I just started the course). This was my first little taste :slight_smile:

fastai2 has changed the mid level and low level APIs dramatically, if you’re not comfortable yet, go through the v3 course once and then refer these fastai2 course notebooks to understand what has been changed.

I urge you to learn more about fastai2 because it’s damm good :sweat_smile:

Glad to hear it helped. Cheers : )

@arora_aman
how i can convert Fastai Image object back to Tensor ?

img.data gives you the underlying tensor from a fastai image.

i convert back and forth from PIL to FastAI like this:

import torchvision.transforms as tfms

def pil2fast(img):  
  return Image(tfms.ToTensor()(img))

def fast2pil(img):
  return tfms.ToPILImage()(img.data).convert("RGB")