image_converter / app.py
Anum15's picture
Update app.py
4893dea verified
import streamlit as st
import cv2
import numpy as np
from PIL import Image
from io import BytesIO
st.set_page_config(page_title="Grayscale Image Converter", layout="centered")
st.title("🖼️ Grayscale Image Converter with Filters & Resize")
st.write("Upload an image, apply filters, resize it, and download the grayscale version!")
# Upload image
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
# Convert uploaded file to numpy array
file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
image = cv2.imdecode(file_bytes, 1) # Load image in color (BGR)
# Convert to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Convert OpenCV images to PIL format for Streamlit display
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
original_pil = Image.fromarray(image_rgb)
gray_pil = Image.fromarray(gray_image)
# Show original and grayscale images side-by-side
st.subheader("Original vs Grayscale Image")
col1, col2 = st.columns(2)
with col1:
st.image(original_pil, caption="Original Image", use_column_width=True)
with col2:
st.image(gray_pil, caption="Grayscale Image", use_column_width=True)
# Filter options
st.subheader("Apply Filters")
filter_option = st.selectbox(
"Choose a filter to apply",
["None", "Gaussian Blur", "Sharpen", "Edge Detection"]
)
if filter_option == "Gaussian Blur":
image = cv2.GaussianBlur(image, (15, 15), 0)
gray_image = cv2.GaussianBlur(gray_image, (15, 15), 0)
elif filter_option == "Sharpen":
kernel = np.array([[0, -1, 0], [-1, 5,-1], [0, -1, 0]])
image = cv2.filter2D(image, -1, kernel)
gray_image = cv2.filter2D(gray_image, -1, kernel)
elif filter_option == "Edge Detection":
image = cv2.Canny(image, 100, 200)
gray_image = cv2.Canny(gray_image, 100, 200)
# Resize options
st.subheader("Resize Image")
width = st.slider("Select width", 50, 500, 300)
height = int((width / original_pil.width) * original_pil.height)
resized_image = cv2.resize(image, (width, height))
resized_gray_image = cv2.resize(gray_image, (width, height))
# Display filtered and resized images
st.subheader("Filtered & Resized Image")
filtered_resized_rgb = cv2.cvtColor(resized_image, cv2.COLOR_BGR2RGB)
filtered_resized_pil = Image.fromarray(filtered_resized_rgb)
filtered_resized_gray_pil = Image.fromarray(resized_gray_image)
col1, col2 = st.columns(2)
with col1:
st.image(filtered_resized_pil, caption="Filtered Resized Image", use_column_width=True)
with col2:
st.image(filtered_resized_gray_pil, caption="Filtered Resized Grayscale", use_column_width=True)
# Convert filtered grayscale image to bytes for download
buf = BytesIO()
filtered_resized_gray_pil.save(buf, format="PNG")
byte_im = buf.getvalue()
# Add download button
st.download_button(
label="📥 Download Filtered & Resized Grayscale Image",
data=byte_im,
file_name="filtered_resized_grayscale_image.png",
mime="image/png"
)