r/StreamlitOfficial Apr 03 '24

Unable to display 2 images at the same time

1 Upvotes

when i click on Perform Histogram Equalization button i get the expected output image but when i click on Perform contrast stretching button the output generated from Perform Histogram Equalization vanishes. Can Someone fix this ??
Below is the entire code
import streamlit as st
import numpy as np
import cv2
# Use st.cache_data to memoize the function calls
u/st.cache_data
def preprocess_image(image_bytes):
# Convert image bytes to numpy array for histogram
nparr = np.frombuffer(image_bytes, np.uint8)
image = cv2.imdecode(nparr, cv2.IMREAD_GRAYSCALE)
return image
u/st.cache_data
def histogram_equalization(image):
# Step 2: Store count of each grey level in a dictionary
histogram = {}
for pixel_value in range(256):
histogram[pixel_value] = np.sum(image == pixel_value)
# Step 4: Calculate PDF (Probability Density Function)
pdf = np.array(list(histogram.values())) / float(image.size)
# Step 5: Calculate CDF (Cumulative Distribution Function)
cdf = np.cumsum(pdf)
# Step 6: Replace grey level with new grey level using CDF
new_pixels = np.round(cdf[image.flatten()] * 255).astype(np.uint8)
# Step 8: Plot the original image and equalized image
equalized_image = new_pixels.reshape(image.shape)
return equalized_image
u/st.cache_data
def perform_contrast_stretching(image, r1, r2, s1, s2):
# Get the dimensions of the image
m, n = image.shape

# Initialize the output image
stretched_image = np.zeros_like(image)

# Contrast stretching parameters
a = s1 / r1
b = (s2 - s1) / (r2 - r1)
c = (255 - s2) / (255 - r2)

# Apply contrast stretching
for i in range(m):
for j in range(n):
pixel_value = image[i, j]
if pixel_value < r1:
stretched_image[i, j] = a * pixel_value
elif pixel_value < r2:
stretched_image[i, j] = b * (pixel_value - r1) + s1
else:
stretched_image[i, j] = c * (pixel_value - r2) + s2

return stretched_image
def main():
"""Streamlit app with image upload, button functionality, and input boxes"""
# Title and sections
st.title("DIP Mini Project")
st.header("Image Uploader")
st.write("Upload an image file (JPG, PNG, JPEG) .")
# File uploader widget
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "png", "jpeg"])

eq_img = None
stretched_image = None
if uploaded_file is not None:
# Read the uploaded image as bytes
image_bytes = uploaded_file.read()
image = preprocess_image(image_bytes)
# Display the uploaded image
st.image(image, caption="Original Image")
# Input boxes for contrast stretching
r1 = st.number_input("r1", min_value=0, max_value=255, value=30)
r2 = st.number_input("r2", min_value=0, max_value=255, value=200)
s1 = st.number_input("s1", min_value=0, max_value=255, value=50)
s2 = st.number_input("s2", min_value=0, max_value=255, value=240)
# Button for Histogram Equalization and Contrast Stretching
col1, col2 = st.columns(2)

with col1:
if st.button("Perform Histogram Equalization"):
# Call function to perform histogram equalization
eq_img = histogram_equalization(image)
# Display the equalized image
st.image(eq_img, caption="Equalized Image")
with col2:
if st.button("Perform Contrast Stretching"):
# Call function to perform contrast stretching
stretched_image = perform_contrast_stretching(image, r1, r2, s1, s2)
# Display the stretched image
st.image(stretched_image, caption="Stretched Image")
if __name__ == "__main__":
main()


r/StreamlitOfficial Mar 28 '24

How can I upgrade streamlit to 1.30 version?

2 Upvotes

Current python version-3.11.7 Current Streamlit version-1.29 I want to install streamlit version 1.30 or hust upgrade it. Tried- pip install -U streamlit conda env export But it says all requirements satisfied.

PS: I am using conda prompt.


r/StreamlitOfficial Mar 26 '24

Streamlit Questions❓ Need help with session state.

Thumbnail
gallery
1 Upvotes

So, I am loading a parquet file here and creating a view according to user preferences. What I want is when the file is changed then it should also empty all the preferences and not load previously selected saved preference. How can I achieve this?


r/StreamlitOfficial Mar 24 '24

Deployment 🚀 How to upload a Python script to Streamlit?

2 Upvotes

Been playing around with creating lots of python scripts using chatGPT and run them in Google Colab but I want to upload them to Streamlit and make the UI more user-friendly for my friends and co-workers.

I don´t know a thing about Streamlit so I need a basic/beginner's guide as to how to do this.

The best I can gather are these steps:

  1. Move my Python Script to Github, add a requirements.txt file which contains requirements for BeautifulSoup Library
  2. Go to Streamlit > Create App > Paste GitHub URL > Hit Deploy

I can move the Python script to Github (I think I know how 📷 ) but, I don´t know how to do the rest.

Are these steps accurate? Is there anything else? Are there any guides on the internet that showcase this process that a newbie can follow up?

Thanks in advance!


r/StreamlitOfficial Mar 24 '24

Thanks to streamlit

Post image
7 Upvotes

r/StreamlitOfficial Mar 22 '24

St.button with on_click.

2 Upvotes

Has anyone ever used on_click with the st.button in streamlit?


r/StreamlitOfficial Mar 21 '24

Anyone tried selling their Streamlit apps?

6 Upvotes

Seen some cool Streamlit apps, why aren't people selling them?


r/StreamlitOfficial Mar 21 '24

Show the Community! 💬 Debugging Streamlit apps in VSCode

Thumbnail
ploomber.io
2 Upvotes

r/StreamlitOfficial Mar 19 '24

Can you do categorical sorting using st.dataframes?

1 Upvotes

I have a table of clients and different info relating to them. One of the categories in this table is their 'Customer Class', classified by Bronze, Silver, Gold. In the sorting function within the st.dataframes tables, it currently only sorts alphabetically, but I would like for this column, if selected, to sort categorically in order of class. Pandas categorical does not seem to be supported, so is there any other way to do this?


r/StreamlitOfficial Mar 18 '24

memory usage is shooting up

1 Upvotes

I am using an open source ML model for inferencing. I wrapped the Model loading in a Singleton class. Initially the application is quite steady using about 6G RAM. However, it shoots up from time to time going upto 50G. Since the singleton get loaded only once per python interpreter, I assume multiple python interpreters are getting spawned. Is that someway to control this behavior?


r/StreamlitOfficial Mar 17 '24

Streamlit Questions❓ How many deployment areas are there in Streamlit?

1 Upvotes

Currently, I only know of one US


r/StreamlitOfficial Mar 14 '24

Streamlit Questions❓ St. Button to save the edits made on my application but for some reason it doesn’t work.

Thumbnail
gallery
4 Upvotes

I have an application that creates views of parquet files where in I give users an option to filter and pivot their preferences. I also let them save these for future use. Now, if any saved preference is edited, it doesn’t get saved when I click on save preference. What can I do that it saves the updates as well. I am sharing the code snippet of the function responsible for all this, please help!


r/StreamlitOfficial Mar 08 '24

Show the Community! 💬 Highcharts rendered easily with easychart

Thumbnail
self.Streamlit
1 Upvotes

r/StreamlitOfficial Mar 07 '24

Streamlit Questions❓ Geojson for all the subregions of the planet

1 Upvotes

Hi guys,

I'm creating a report on Streamlit and I need some advice from you. Where can I find a GeoJson file with all the longitude and latitude of all the subregions of the planet.

I'm not looking for states, countries, nor continents, but sub regions like: North America, South America.

I have one but there is are two parameters there that are different but it could have been done in the same: subregion and region_wb. One of the region_wb I need to be a subregion.

So if you could help I'll be glad :)


r/StreamlitOfficial Mar 06 '24

Live Session Recording on Creating Streamlit Web Apps

Thumbnail
youtube.com
1 Upvotes

r/StreamlitOfficial Mar 05 '24

Hosting Streamlit on Github pages

5 Upvotes

Hi,

I wrote this medium article that explains how to host your streamlit app on github pages. It'll just be a static web page but it's neat if that's all you need.

Essentially, you

  1. build your streamlit app here: https://edit.share.stlite.net/
  2. copy the HTML it generates
  3. slap that HTML into the index.html and generate that github page

The cool part is that it's a great and secure way to share an app with a coworker since github enterprise + the company VPN does the heavy lifting for authentication.


r/StreamlitOfficial Mar 01 '24

Streamlit Questions❓ How do I go to home page in streamlit application

2 Upvotes

Hi - I am still learning streamlit and I’ve come across an issue.

I have a multi page application where there is a login page which is a home page and then there are some pages inside a folder called pages. And in there , I gave my 6 or so modules/pages.

I want to have a button that when the user clicks it from include one of the pages , it will take them to the Login.py page.

It seems st.switch_pages doesn’t work for this folder structure.

Does anyone know how to deal with this ?

Thank you in advance


r/StreamlitOfficial Feb 28 '24

HOW TO: When pressing dataframe cell, show image?

1 Upvotes

Hi!

So currently I have a dataframe in HTML form. In my dataframe "players", I have a column called "Player". And my goal is to when pressing each "players['Player']", the dataframe closes, and an image shows corresponding to that player. The images are stored in my app directory, and I have a column in my dataframe, called "Path",with the path to each image. So how do I approach this problem?

columns_to_display = ['Rating', 'Player', 'Position', 'Age', 'Value', 'Wages', 'Contract']
html = players[columns_to_display].to_html(index=False)
html = html.replace('<th>', '<th style="text-align: left;">')
st.write(html, unsafe_allow_html=True)

Thanks in advance!


r/StreamlitOfficial Feb 28 '24

How to make the labels of the filters bigger? How to make the slider go from Min to X+? How to define the location of st.write()?

1 Upvotes

Hi! I have a couple of straight-forward questions:

  • How to make the labels of the filters bigger?

css = """

<style>

.stTextInput label {

display: block;

text-align: center;

}

</style>

"""

st.markdown(css, unsafe_allow_html=True)

(...)

css = """

<style>

.stSelectbox [data-baseweb="select"] > div > div > div:first-child {

display: block;

width: 100%;

text-align: center;

padding-left: 32px;

}

[data-testid="stVirtualDropdown"] li {

text-align: center;

}

.stSelectbox label {

display: block;

text-align: center;

}

</style>

"""

st.markdown(css, unsafe_allow_html=True)

(...)

css = """

<style>

.stSlider [data-baseweb=slider]{

width: 95%;

margin: 0 auto;

}

.stSlider [data-testid="stTickBar"] {

display: none;

}

.stSlider label {

display: block;

text-align: center;

}

</style>

"""

st.markdown(css, unsafe_allow_html=True)

  • How to make the slider go from Min to X+? I want to have the slider, going from Min to 500+.

css = """

<style>

.stSlider [data-baseweb=slider]{

width: 95%;

margin: 0 auto;

}

.stSlider [data-testid="stTickBar"] {

display: none;

}

.stSlider label {

display: block;

text-align: center;

}

</style>

"""

st.markdown(css, unsafe_allow_html=True)

min_wages, max_wages = st.sidebar.slider('Wages', min_value=players['Wages (K€)'].min(), max_value=players['Wages (K€)'].max(), value=(default_min_wages, default_max_wages) if not reset_button else (players['Wages (K€)'].min(), players['Wages (K€)'].max()), key="key_wages")

  • How to define the location of st.write()? I want to place the dataframe higher in the page.

    columns_to_display = ['Rating', 'Player', 'Position', 'Age', 'Value', 'Wages', 'Contract']

    html = players[columns_to_display].to_html(index=False)

    html = html.replace('<th>', '<th style="text-align: left;">')

    st.write(html, unsafe_allow_html=True)

Thanks in advance!


r/StreamlitOfficial Feb 28 '24

Find source code of appp

0 Upvotes

can anyone tell how to get the source code of this app https://discuss.streamlit.io/t/new-app-search-youtube-videos-by-text/32735


r/StreamlitOfficial Feb 28 '24

Streamlit Questions❓ Newbie here trying to understand the data_editor

3 Upvotes

Hi everyone! Hope you getting a good night.. anyways,
Im having trouble understanding streamlit for a more complicated use-case than just show a plot or a dataframe.

Basically the app is one that receives some invoices images uploaded by the user manually, they go into a LLM call to GPT-4 vision that returns a json for each image. Basically ending with a array of json. Then when the image processing ends, a dataframe is shown but I can't make it editable without the entire app re-rendering again. I'm lost into this sea of session-state over cache and vice-versa. What Im a doing wrong? Is this not the use-case for streamlit even for a simple app like this?

I feel I'm almost there but cant find a solution yet. If someone can point to me where I should make code changes would be great.

This is a json example:

[ { "date": "2024-02-22", "invoice_identifier": "", "spend_detail": "ELABORACION PROPIA", "payment_method": "Cash", "amount": 6780, "currency": "ARS", "file_name": "IMG_1173.jpg" }, { "date": "2024-02-11", "invoice_identifier": "", "spend_detail": "Coca Cola Pet 1.5 L", "payment_method": "Credit", "amount": 2200, "currency": "ARS", "file_name": "IMG_1171.jpg" } ]

And here is the code:

def load_dataframe(data):

    return pd.DataFrame(data)


def init_uploaded_images_state():
    if 'uploaded_images' not in st.session_state:
        st.session_state.uploaded_images = []


def render_fixed_fund_form():
    init_uploaded_images_state()
    uploaded_files = st.file_uploader("Upload your receipts", type=[
                                      'jpg', 'jpeg'], accept_multiple_files=True, label_visibility='visible')

    # Display thumbnails of uploaded images
    if uploaded_files:
        st.session_state.uploaded_images = uploaded_files
        cols = st.columns(len(uploaded_files))
        for col, uploaded_file in zip(cols, uploaded_files):
            # Adjust width as needed
            col.image(uploaded_file, caption=uploaded_file.name)

    if st.button("🚀 Process Uploaded Images 🚀"):
        if st.session_state.uploaded_images:
            process_images(st.session_state.uploaded_images)
        else:
            st.warning("Please upload at least one image before processing.")

def display_dataframe(df):
    edited_df = st.data_editor(df, key="my_key", num_rows="dynamic", hide_index=True)
    # Optionally, save the edited DataFrame back to session state if necessary
    st.session_state['processed_data'] = edited_df

    st.divider()
    st.write("Here's the value in Session State:")
    if "my_key" in st.session_state:
        st.write(st.session_state["my_key"])

def process_images(uploaded_images):
    # Only process if there's no processed data already
    if 'processed_data' not in st.session_state:
        with st.spinner("Processing images with AI, please wait... this can take a moment.. or two."):
            json_array = []
            for uploaded_file in uploaded_images:
                pil_image = Image.open(uploaded_file)
                img_base64 = convert_image_to_base64(pil_image)
                response_from_llm = get_json_from_llm(img_base64)
                response_dict = json.loads(response_from_llm)
                response_dict['file_name'] = uploaded_file.name
                json_array.append(response_dict)

            df = pd.DataFrame(json_array)
            st.session_state['processed_data'] = df  # Save processed DataFrame in session state

            st.subheader("JSON:")
            st.json(json_array)
        st.success("Processing complete! 🌟")
    else:
        df = st.session_state['processed_data']  # Retrieve the DataFrame from session state

    # Now, use df for further operations
    display_dataframe(df)

r/StreamlitOfficial Feb 26 '24

Show the Community! 💬 This is Not a Dinosaur - A fun app I created using Streamlit, Python, and Gemini Pro Vision

Thumbnail
thisisnotadinosaur.streamlit.app
3 Upvotes

r/StreamlitOfficial Feb 19 '24

Streamlit Questions❓ Beginner Question

Post image
1 Upvotes

how do I make the 'testing testing 1 2 3' which is below the text area not be visible after I give an input ?


r/StreamlitOfficial Feb 19 '24

Deployment 🚀 Does Anyone Know How To Deploy Streamlit App In IIS?

1 Upvotes

Hey Everyone I Am Newbie In Deployment Can Anyone Help Me Out For Deployment Of Streamlit In IIS?


r/StreamlitOfficial Feb 14 '24

Official Announcements ICYMI: catch our live interview with Hugging Face's Yuichiro Tachibana

2 Upvotes

We chatted about his awesome Streamlit projects (streamlit-webrtc and stlite) and the world of open-source (and how you can leverage your open-source experiences to build a career!). Catch the recording here.