Streamlit images loop

Can someone help me to make this a loop or it can be a loop? I am new to python and streamlit library hehehe. I want to learn also here for my betterment. Thank youuu!

c1,c2,c3,c4,c5, c6, c7 = st.beta_columns(7)

        with c1:

          fig1 = plt.figure(figsize=(14,8))

          fig1.suptitle("Gray Eqhist")

          plt.imshow(gray_eqhist, 'gray')        

          st.pyplot(fig1)

        with c2:

          fig2 = plt.figure(figsize=(14,8))

          fig2.suptitle("Applied Clahe")

          plt.imshow(applied_clahe, 'gray')        

          st.pyplot(fig2)

        with c3:

          fig3 = plt.figure(figsize=(14,8))

          fig3.suptitle("Binary")

          plt.imshow(thresh1, 'gray')        

          st.pyplot(fig3)

        with c4:

          fig4 = plt.figure(figsize=(14,8))

          fig4.suptitle("Binary Threshold Inverted")

          plt.imshow(thresh2, 'gray')        

          st.pyplot(fig4)

        with c5:

          fig5 = plt.figure(figsize=(14,8))

          fig5.suptitle("Truncated Threshold")

          plt.imshow(thresh3, 'gray')        

          st.pyplot(fig5)

        with c6:

          fig6 = plt.figure(figsize=(14,8))

          fig6.suptitle("Set to 0")

          plt.imshow(thresh4, 'gray')        

          st.pyplot(fig6)

        with c7:

          fig7 = plt.figure(figsize=(14,8))

          fig7.suptitle("Set to 0 Inverted")

          plt.imshow(thresh5, 'gray')        

          st.pyplot(fig7)

It can be a loop, and most people would probably write it as one.

However, you’d need to set up a data structure with all the relevant information in, and if it is working, there is nothing fundamentally wrong with the code you have written.

If you wanted to learn about loops, I would begin with something simpler.

If you want to make this streamlit app and it is working for you, I would just be happy and move on.

If you’ve got a plan to make a much more complex version of this app with many more blocks, then attach the full demo code and the specifics and we’ll see what we can do!

1 Like

Yess, Thank you for the reply. My code is completely working, it’s just that I don’t know how to make this a loop hehehe. I can post the full code, if you don’t mind. Thank youuu!

Here is my code hehehe I remove some of the function I made, I’m embarrassed if I spoonfeed too much here hehehe. If I learn the logic, I will do it myself.

import streamlit as st

import numpy as np
import cv2
from PIL import Image
def welcome():
    st.title('Welcome')    
    st.subheader('Image Analyzation and Pre-Processing')
    
def analyze(uploaded_file):
    
    #Default Configuration
    st.set_option('deprecation.showfileUploaderEncoding', False)
    
    #This one everytime we have changes, it will instantly show realtime
    realtime_update = st.sidebar.checkbox(label="Update in Real Time", value=True)
    
    if uploaded_file:
img = Image.open(uploaded_file)

        

        #Invert
        
        pil2invert = np.array(img.convert("L"))
        fig1 = plt.figure(figsize=(14,8))
        plt.imshow(pil2invert)        
        st.pyplot(fig1)
        
def preprocess(uploaded_file):
    
    #Default Configuration
    st.set_option('deprecation.showfileUploaderEncoding', False)
    #This one everytime we have changes, it will instantly show realtime
    realtime_update = st.sidebar.checkbox(label="Update in Real Time", value=True)
    
    if uploaded_file:
        
        img = Image.open(uploaded_file)
        
        pil2cvt = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
        
        pil2cvt2gray = cv2.cvtColor(pil2cvt, cv2.COLOR_BGR2GRAY)
        st.write("Thresholding")
        
        gray_eqhist = cv2.equalizeHist(pil2cvt2gray)
        clahe=cv2.createCLAHE(clipLimit=40)
        applied_clahe = clahe.apply(gray_eqhist)
        
        th = st.sidebar.slider(
            label='Threshold Value',
            min_value=50,
            max_value=100)
        max_val = st.sidebar.slider(
            label='Max Value',
            min_value=200,
            max_value=255)
        ret, thresh1 = cv2.threshold(applied_clahe,th,max_val, cv2.THRESH_BINARY)
        ret, thresh2 = cv2.threshold(applied_clahe,th,max_val, cv2.THRESH_BINARY_INV)
        ret, thresh3 = cv2.threshold(applied_clahe,th,max_val, cv2.THRESH_TRUNC)
        ret, thresh4 = cv2.threshold(applied_clahe,th,max_val, cv2.THRESH_TOZERO)
        ret, thresh5 = cv2.threshold(applied_clahe,th,max_val, cv2.THRESH_TOZERO_INV)
        
        c1,c2,c3,c4,c5, c6, c7 = st.beta_columns(7)
        with c1:
          fig1 = plt.figure(figsize=(14,8))
          fig1.suptitle("Gray Eqhist")
          plt.imshow(gray_eqhist, 'gray')        
          st.pyplot(fig1)
          with c2:

          fig2 = plt.figure(figsize=(14,8))
          fig2.suptitle("Applied Clahe")
          plt.imshow(applied_clahe, 'gray')        
          st.pyplot(fig2)
        with c3:
          fig3 = plt.figure(figsize=(14,8))
          fig3.suptitle("Binary")
          plt.imshow(thresh1, 'gray')        
          st.pyplot(fig3)
        with c4:
          fig4 = plt.figure(figsize=(14,8))
          fig4.suptitle("Binary Threshold Inverted")
          plt.imshow(thresh2, 'gray')        
          st.pyplot(fig4)
        with c5:
          fig5 = plt.figure(figsize=(14,8))
          fig5.suptitle("Truncated Threshold")
          plt.imshow(thresh3, 'gray')        
          st.pyplot(fig5)
        with c6:
          fig6 = plt.figure(figsize=(14,8))
          fig6.suptitle("Set to 0")
          plt.imshow(thresh4, 'gray')        
          st.pyplot(fig6)
        with c7:
          fig7 = plt.figure(figsize=(14,8))
          fig7.suptitle("Set to 0 Inverted")
          plt.imshow(thresh5, 'gray')        
          st.pyplot(fig7)```

OK. So, you’d do something like this.

There are many different ways to set this out, and to index the correct data for each loop, but this is the sort of idea.
Note - this code won’t work - you would need to fill in the rest of the data for each specific loop where I have left … (I got bored filling these in!)

col_tuple = st.beta_columns(7)

figure_contents = (
    "Grey Eqhist",
    "Applied Clahe",
    "Binary",
    ...,
    )
    
imshow_params = (
    gray_eqhist,
    applied_clahe,
    thresh1,
    ...,
    )
    
loop_data = list(zip(
    col_tuple, 
    figure_contents, 
    imshow_params, 
    ...,)

for loop in loop_data:
    with loop[0]:
        fig_n = plt.figure(figsize=(14,8))
        fig.suptitle(loop[1])
        plt.imshow(loop[2], 'gray')
        st.pyplot(fig_n)

If you wanted to get fancy, you could define a data class so that you could store the loop data as a list of objects, or use dictionaries… but its fundamentally the same technique.

2 Likes

Thank youuu. I really appreciate youuuu. I’m blessed, I enter in this community.

Hi lasttt request hehehe I used your code and apply with the other code but one of the image doesnt need to have “gray”, because whe i want to invert an image it stay on grayscale.

def analyze(uploaded_file):
st.set_option('deprecation.showfileUploaderEncoding', False)
realtime_update = st.sidebar.checkbox(label="Update in Real Time", value=True)

if uploaded_file:
    img = Image.open(uploaded_file)
    pil2invert = np.array(img.convert("L")) #here the image didnt invert and just stay on grayscale.
    pil2gray = ImageOps.grayscale(img)
    img_palette = img.convert("P", palette=Image.ADAPTIVE, colors=8)

    col_tuple = st.beta_columns(4)
    
    figure_contents=(
      "Original",
      "Invert",
      "Gray",
      "Palette")

    imshow_params=(
        img, 
        pil2invert,
        pil2gray, 
        img_palette)

    loop_data=list(zip(
      col_tuple,
      figure_contents,
      imshow_params))

    for loop in loop_data:
      with loop[0]:
        fig_n=plt.figure(figsize=(14, 8))
        fig_n.suptitle(loop[1])
        plt.imshow(loop[2], 'gray')
        st.pyplot(fig_n)

So, that’s a lovely extension to what you’ve already done - create another tuple eg just below imshow_params and fill it with grey, grey, … whatever, add it to the zip loop_data collection, and then access it in the loop eg with loop[3]

You’ll quickly discover that this becomes unwieldy, and you can then look at other ways of storing the data that you want, like dictionaries, named tuples, data classes etc.

Which is a topic too broad to fit into this reply!

Thank youu again. But hehehe sorry I can’t visualize the code, my english comprehension is not as good😅. My fundamentals in programming is so bad. Can you like put a pseudocode or like the code you solved in my previous question? Heheheh Thank you so much. Sorry for I am so annoying and ask too many questions hehehe

So, just to edit your previous code.
Note that it becomes harder and harder to read when you store the data like this, other methods are available as described above.

def analyze(uploaded_file):
st.set_option('deprecation.showfileUploaderEncoding', False)
realtime_update = st.sidebar.checkbox(label="Update in Real Time", value=True)

if uploaded_file:
    img = Image.open(uploaded_file)
    pil2invert = np.array(img.convert("L")) #here the image didnt invert and just stay on grayscale.
    pil2gray = ImageOps.grayscale(img)
    img_palette = img.convert("P", palette=Image.ADAPTIVE, colors=8)

    col_tuple = st.beta_columns(4)
    
    figure_contents=(
      "Original",
      "Invert",
      "Gray",
      "Palette")

    imshow_params=(
        img, 
        pil2invert,
        pil2gray, 
        img_palette)

    imshow_cmap=(             # New tuple of options here
         'gray',
         'gray',
         'viridis',
         'viridis')

    loop_data=list(zip(
      col_tuple,
      figure_contents,
      imshow_params,
      imshow_cmap))   # add to this collection

    for loop in loop_data:
      with loop[0]:
        fig_n=plt.figure(figsize=(14, 8))
        fig_n.suptitle(loop[1])
        plt.imshow(loop[2], loop[3])   # insert into loop here
        st.pyplot(fig_n)

I’ve edited this directly, so I’m afraid the whitespace will be all wonky, but hopefully it shows you how you could extend this.

1 Like

Soooooo much Thanks. You are such a good person. I learn alot from you heheh despite I am very annoying hahahaha. Thank you so much again Sir! Youre such a life saver. :grin: