Converting FileLoader Media Object back into a video file

In Anvil, I have a FileLoader that takes in a video file (.mp4). However, this automatically converts the uploaded video file into a Media Object.

For example,

self.file_uploader.file

returns a Media Object instead of a video file.

Is there a way to convert the Media Object back into a video file? Perhaps converting to binary in the process?

My goal is to feed the uploaded video file in OpenCV as the following:

cv2.VideoCapture("video.mp4")

Thanks in advance!

If you want to convert a Media Object to binary, then get_bytes is what you’re after!

3 Likes

Thanks @eli-anvil ! I was able to get the Media Object to bytes part working using get_bytes() and I wonder how one’s able to convert from bytes into a video file / video streams?

I was able to convert bytes to image pretty straightforwardly with BytesIO via

image = io.BytesIO(bytes)

and reading with PIL

Image.open(image)

but I’m haven’t been able to do this for bytes to video.

I would try taking your media object, and writing it to a datatable media object column.

Then use the anvil.media.url attribute (from an object created from the media object now stored in the row of the data table, not the original one created by the file loader) to feed the video into opencv. Opencv should be able to take a url instead of a filename.

Then clean up the datatable row that you used to store the video, just make sure opencv is not still processing it!

I am guessing opencv probably won’t ever support python file handler objects like you could create using io.BytesIO() because opencv is based on various c++ libraries.

If you are using opencv on a local machine using the uplink than write the bytes string to a temp file:

with open("tempfilename_video.mp4", 'wb') as f:
    f.write( your_anvil_media_object.get_bytes() )

and call that using cv2.VideoCapture("tempfilename_video.mp4") or however you wish to deal with your temporary file.

I also suggest cleaning up your temp file when the process is done or someone could explode your local hard disk given enough access. :cd: :axe: