Image_Argumentation / src /streamlit_app.py
saikumar27's picture
Update src/streamlit_app.py
a8aca45 verified
Raw History Blame Contribute Delete
9.99 kB
import streamlit as st
import numpy as np
import pandas as pd
import os
import zipfile
import cv2
from typing import List, Optional
# Page Configuration
st.set_page_config(page_title="Image Augmentation", layout="wide")
# Custom CSS
st.markdown("""
<style>
.stApp {
background-color: #d0e8ff;
}
.main .block-container {
padding-top: 2rem;
padding-right: 2rem;
padding-left: 2rem;
padding-bottom: 2rem;
max-width: 100%;
}
.stButton>button {
background-color: #003366;
color: white;
font-weight: bold;
}
.stDownloadButton>button {
background-color: #28a745;
color: white;
font-weight: bold;
}
</style>
""", unsafe_allow_html=True)
# Main Heading
st.markdown('<h2 style="text-align: center;"><span style="color:#003366;">Generate Augmented Images</span></h2>', unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
class ImageAugmenter:
def __init__(self):
self.output_folder = "output_images"
def clear_folder(self):
"""Clear the output folder"""
if os.path.exists(self.output_folder):
for file in os.listdir(self.output_folder):
file_path = os.path.join(self.output_folder, file)
if os.path.isfile(file_path):
os.remove(file_path)
else:
os.makedirs(self.output_folder)
def save_image(self, image: np.ndarray, prefix: str = "img") -> str:
"""Save image to output folder"""
if not os.path.exists(self.output_folder):
os.makedirs(self.output_folder)
image_name = f"{prefix}_{len(os.listdir(self.output_folder)) + 1}.jpg"
image_path = os.path.join(self.output_folder, image_name)
cv2.imwrite(image_path, image)
return image_path
def zip_files(self) -> str:
"""Create zip file of all generated images"""
zip_filename = f"{self.output_folder}.zip"
with zipfile.ZipFile(zip_filename, 'w') as zipf:
for file in os.listdir(self.output_folder):
file_path = os.path.join(self.output_folder, file)
zipf.write(file_path, file)
return zip_filename
def translation(self, img: np.ndarray, n: int = 1) -> List[np.ndarray]:
"""Apply translation transformation"""
results = []
for _ in range(n):
tx = np.random.randint(2, 50)
ty = np.random.randint(1, 50)
tm = np.array([[1, 0, tx], [0, 1, ty]], dtype=np.float32)
trans_img = cv2.warpAffine(img, tm, dsize=(img.shape[1], img.shape[0]),
borderMode=cv2.BORDER_REFLECT)
results.append(trans_img)
return results
def rotation(self, img: np.ndarray, n: int = 1) -> List[np.ndarray]:
"""Apply rotation transformation"""
results = []
for _ in range(n):
angle = np.random.choice([30, 45, 90, 180, -90, -30, -45])
scale = np.round(np.random.uniform(1, 1.6), 2)
r_x = img.shape[0] // 2
r_y = img.shape[1] // 2
rm = cv2.getRotationMatrix2D((r_y, r_x), angle, scale)
r_img = cv2.warpAffine(img, rm, (img.shape[1], img.shape[0]))
results.append(r_img)
return results
def scaling(self, img: np.ndarray, n: int = 1) -> List[np.ndarray]:
"""Apply scaling transformation"""
results = []
for _ in range(n):
sx = np.random.uniform(1, 2)
sy = np.random.uniform(1, 2)
tx = np.random.randint(1, 16)
ty = np.random.randint(1, 12)
sm = np.array([[sx, 0, tx], [0, sy, ty]], dtype=np.float32)
s_img = cv2.warpAffine(img, sm, (img.shape[1], img.shape[0]))
results.append(s_img)
return results
def shearing(self, img: np.ndarray, n: int = 1) -> List[np.ndarray]:
"""Apply shearing transformation"""
results = []
for _ in range(n):
sx = np.round(np.random.uniform(1, 1.5), 2)
shx = np.round(np.random.uniform(0, 0.5))
tx = np.random.randint(1, 10)
shy = np.round(np.random.uniform(0, 0.5))
sy = np.round(np.random.uniform(1, 1.2), 2)
ty = np.random.randint(1, 15)
shm = np.array([[sx, shx, tx], [shy, sy, ty]], dtype=np.float32)
img_shear = cv2.warpAffine(img, shm, (img.shape[1], img.shape[0]),
borderMode=cv2.BORDER_REFLECT)
results.append(img_shear)
return results
def cropping(self, img: np.ndarray, n: int = 1) -> List[np.ndarray]:
"""Apply cropping transformation"""
results = []
for _ in range(n):
# Ensure we don't crop too much
min_dim = min(img.shape[0], img.shape[1])
crop_size = np.random.randint(min_dim // 2, min_dim)
x = np.random.randint(0, img.shape[1] - crop_size)
y = np.random.randint(0, img.shape[0] - crop_size)
img_crop = img[y:y+crop_size, x:x+crop_size]
# Resize to maintain original dimensions
img_crop = cv2.resize(img_crop, (img.shape[1], img.shape[0]))
results.append(img_crop)
return results
def main():
# Initialize augmenter
augmenter = ImageAugmenter()
# Upload image
uploaded_file = st.file_uploader("Upload an image...", type=["jpg", "jpeg", "png"])
if uploaded_file is None:
st.info("Please upload an image to get started")
return
# Display original image
img_array = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
st.subheader("Original Image")
st.image(img_rgb, use_column_width=True)
# Augmentation settings
st.markdown("---")
st.subheader("Augmentation Settings")
col1, col2 = st.columns(2)
with col1:
image_count = st.number_input("Number of Images to generate",
min_value=1, max_value=100, value=10)
with col2:
st.write("Select transformations:")
trans = st.checkbox("Translation", value=True)
rot = st.checkbox("Rotation", value=True)
scal = st.checkbox("Scaling")
shear = st.checkbox("Shearing")
crop = st.checkbox("Crop")
# Preview or Generate
st.markdown("---")
col1, col2 = st.columns(2)
with col1:
preview_btn = st.button("Preview Transformations")
with col2:
generate_btn = st.button("Generate All Images", type="primary")
if not (trans or rot or scal or shear or crop):
st.warning("Please select at least one transformation")
return
# Get selected transformations
transformations = []
if trans: transformations.append(("Translation", augmenter.translation))
if rot: transformations.append(("Rotation", augmenter.rotation))
if scal: transformations.append(("Scaling", augmenter.scaling))
if shear: transformations.append(("Shearing", augmenter.shearing))
if crop: transformations.append(("Crop", augmenter.cropping))
# Calculate how many images to generate per transformation
num_trans = len(transformations)
base = image_count // num_trans
remainder = image_count % num_trans
counts = [base + 1 if i < remainder else base for i in range(num_trans)]
if preview_btn:
st.subheader("Preview of Transformations")
augmenter.clear_folder()
cols = st.columns(min(3, len(transformations)))
for idx, ((name, func), col) in enumerate(zip(transformations, cols)):
with col:
st.write(f"**{name}**")
sample = func(img, 1)[0]
sample_rgb = cv2.cvtColor(sample, cv2.COLOR_BGR2RGB)
st.image(sample_rgb, use_column_width=True)
st.info("This shows one sample per selected transformation. Click 'Generate All Images' to create the full set.")
if generate_btn:
with st.spinner(f"Generating {image_count} augmented images..."):
augmenter.clear_folder()
progress_bar = st.progress(0)
generated_count = 0
for (name, func), count in zip(transformations, counts):
results = func(img, count)
for result in results:
augmenter.save_image(result)
generated_count += 1
progress_bar.progress(generated_count / image_count)
# Create zip file
zip_filename = augmenter.zip_files()
# Download button
with open(zip_filename, "rb") as f:
st.download_button(
label="Download All Images as ZIP",
data=f,
file_name=zip_filename,
mime="application/zip"
)
st.success(f"Successfully generated {generated_count} augmented images!")
# Show sample of generated images
st.subheader("Sample of Generated Images")
sample_files = os.listdir(augmenter.output_folder)[:6] # Show up to 6 samples
cols = st.columns(min(3, len(sample_files)))
for idx, (file, col) in enumerate(zip(sample_files, cols)):
with col:
img_path = os.path.join(augmenter.output_folder, file)
img_sample = cv2.imread(img_path)
img_sample_rgb = cv2.cvtColor(img_sample, cv2.COLOR_BGR2RGB)
st.image(img_sample_rgb, use_column_width=True)
if __name__ == "__main__":
main()