Convert the TempFile to opencv in a Jupyter notebook

What I’m trying to do: Create an AI app with anvil.
To do this, I upload a picture and send it to a Jupyter notebook.
There the image should be converted to opencv, classified and returned to Anvil to be viewed on the web.

What I’ve tried and what doesn’t work:
I looked at the tutorial but it didn’t work.

How could I convert the anvil.media.TempFile to opencv in an Jupyter notebook process it and send it back to anvil?

Code Sample:

import anvil.media

@anvil.server.callable
def classify_image(file):
    with anvil.media.TempFile(file) as filename:
        img = load_img(filename)
??????? to opencv

return processed_image

This seems more about opencv than Anvil. Opencv is a library that will accept an image file. Anvil simply has a file storage wrapper it uses, and you can convert that image or write it to disk, depending n what you need.

Typically if I’m doing some ML on an image I use PIL. Torch for example uses pillow easily. Does opencv expect a file path or is an image in memory acceptable?

Here’s how I handled a video file with OpenCV. You may find you can adapt it suit your needs:

1 Like

Hi Owen,

Thanks, but I think it’s way too complicated.
I just want a way to transfer a image from anvil to the Jupyter notebook, save it there, open it with opencv, send it back to anvil and display it in the wep app.
Do you have a solution for that?

Kind regards
Erwin

Hi Robert,

It didn’t work with an image in memory. Do you have some way to save the TempFile image in the Jupyter notebook using PIL? I could open it then with opencv and do my transformation and ML stuff.
Do you have a solution for that?

Kind regards
Erwin

1 Like

You could write the file to the hard drive with some generic Python. Or you can use Anvil’s built-in method to do that:

Media Object to temporary file

1 Like