Closeing Images

I have a loop that is displaying a video frame by frame.
My issue is, I was expecting the images to display frame by frame…like flipping through a set of index cards; however, I’m getting the frames to display underneath each other one by one in a cascading fashion (if that makes sense).

Is there a way I can close an image in my streamlit app?

Here is my code

     cap = cv2.VideoCapture('/content/video.mp4')
     while cap.isOpened():
            ret, image = cap.read()
            st.image(Image.open(image), width=1200)

Hi @Andre_Williams, :wave:

Thank you for describing the expected and actual behavior, and providing a code snippet!

I would recommend using st.empty() to create a container for the image outside the while loop. In the while loop, call the .image() function on the container to draw the image, instead of st.image().

For every iteration i of the while loop, image_i-1 will be replaced by image_i:

import streamlit as st
import cv2
import time

cap = cv2.VideoCapture("/content/video.mp4")

# Create a single-element container
image_container = st.empty()

while cap.isOpened():
    ret, frame = cap.read()
    if ret:
        # Display the frame in the container and
        # Replace contents of the container with next frame on the next iteration
        image_container.image(frame, width=800)
        time.sleep(0.05) # Optional delay
    else:
        break

frame-by-frame

Does this help? :grinning_face_with_smiling_eyes:

Happy Streamlit-ing! :balloon:
Snehan