How to Open Uploaded Streamlit Video file using OpenCV

I uploaded a video using streamlit but when I tried to read the video into Using OpenCV I get an error.
Streamlit Code

    uploaded_file = st.file_uploader("Choose a file")
    if uploaded_file is not None:
        # To read file as bytes:
        bytes_data = uploaded_file.read()
        st.write(bytes_data)
        print(bytes_data)

**OpenCV**
    import CV2
    # Opens the Video file
    cap= cv2.VideoCapture(uploaded_file)
    i=1
    while(cap.isOpened()):
        ret, frame = cap.read()
        if ret == False:
            break
        if i%100 == 0:
            cv2.imwrite('house'+str(i)+'.jpg',frame)

        i+=1
    cap.release()
    cv2.destroyAllWindows

The API reference states that UploadedFile class is a subclass of BytesIO, and therefore it is β€œfile-like”. This means you can pass them anywhere where a file is expected.

1 Like

Hi @chukypedro -

This answer seems to be working for people.

@randyzwitch Thanks I will try that out ASAP

@randyzwitch
Capture
Why do I get the above error whenever I close the uploaded video. It is coming from this line of code
tfile.write(f.read())

NoneType means there is no data being passed, which can happen in certain situations with file_uploader. Can you post your whole code here?

@randyzwitch Here is the scripts

import tempfile
import cv2
import streamlit as st

f = st.file_uploader("Choose a Video")      
tfile = tempfile.NamedTemporaryFile(delete=False) 
tfile.write(f.read())

# Opens the Video file
cap= cv2.VideoCapture(tfile.name)
stframe = st.empty()
i=1
while(cap.isOpened()):
    ret, frame = cap.read()
    if ret == False:
        break
    if i%1000 == 0:
        cv2.imwrite('new_image'+str(i)+'.jpg',frame)
    i+=1
cap.release()
cv2.destroyAllWindows()

@randyzwitch

tfile.write(f.read())

displays error when I close the uploaded video