Streamlit: How to store value of variable in cache

Viewed 5121

I am using 2 differnt radio options for performing different tasks. I want to capture image form one and then do some operation later in the option 2. When I try to change the radio option to 2 after storing a frame in my_image (in the option 1), there comes an error in thre streamlit NameError: name 'my_image' is not defined. I was thinking that it can be done by storing the variable my_image in cache but I don't know how to do this. Is there any other way to do this.

import streamlit as st
import cv2

def Camera():
    frames1 = st.empty()
    button1 = st.button('DONE', key=0)
    while cap.isOpened():
        frames1.image(cap.read()[1], channels="BGR")
        if button1:
            my_image = cap.read()[1]
            cap.release()
            break
    return my_image

option = st.sidebar.radio('Choose the option', [1, 2])

if option == 1:
    cap = cv2.VideoCapture(0)

    my_image = Camera()
    st.image(my_image, channels="BGR")

if option == 2:
    st.image(my_image, channels='BGR')
2 Answers

Guess I needed this SessionState gist copied in a SessionState.py file.
I initialize a variable session_state = SessionState.get(name='', img=None).
In the option==1, assigned session_state.img = my_image and then used it to get to my_image in option==2.

import streamlit as st
import cv2
import SessionState

def Camera():
    frames1 = st.empty()
    button1 = st.button('DONE', key=0)
    while cap.isOpened():
        frames1.image(cap.read()[1], channels="BGR")
        if button1:
            my_image = cap.read()[1]
            cap.release()
            break
    return my_image


option = st.sidebar.radio('Choose the option', [0, 1])
session_state = SessionState.get(name='', img=None)
if option == 0:
    cap = cv2.VideoCapture(0)

    my_image = Camera()
    st.image(my_image, channels="BGR")
    session_state.img = my_image

if option == 1:
    my_image = session_state.img
    st.image(my_image, channels='BGR')

Streamlit runs top down each time there is an interaction event. In your code, my_image = Camera() is only run when option==0; when the radio button switches to the other option, my_image never gets defined.

Move the code that defines cap and my_image out of your first conditional statement.

Related