Zero-To-Hero-Machine-learning / pages /6_image_augmentation.py
Ajay1100's picture
Update pages/6_image_augmentation.py
40759b2 verified
# Remove the second instance of:
import streamlit as st
from PIL import Image
import cv2
import numpy as np
import os
from zipfile import ZipFile
# Custom HTML & CSS for styling
def custom_css():
st.markdown(
"""
<style>
.title {
font-size: 36px;
font-weight: bold;
color: #2E3B55;
text-align: center;
margin-bottom: 20px;
}
.subtitle {
font-size: 24px;
font-weight: bold;
color: #444;
margin-top: 20px;
}
.content {
font-size: 18px;
color: #555;
margin-bottom: 10px;
}
</style>
""",
unsafe_allow_html=True,
)
# Apply custom styling
custom_css()
st.markdown('<p class="title">Image Augmentation</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Image augmentation is a technique used to artificially expand the size of a dataset by applying various transformations to images...</p>', unsafe_allow_html=True)
st.markdown('<p class="subtitle">Types of Image Augmentations</p>', unsafe_allow_html=True)
st.markdown('<p class="content"><b>Geometric Transformations</b></p>', unsafe_allow_html=True)
st.markdown('<p class="content">Rotation: Rotates the image by a certain degree.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Scaling: Resizes the image while maintaining aspect ratio.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Translation: Moves the image in horizontal or vertical directions.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Shearing: Skews the image along an axis.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Flipping: Mirrors the image horizontally or vertically.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Cropping: Removes parts of the image or randomly selects a smaller portion.</p>', unsafe_allow_html=True)
st.markdown('<p class="subtitle">Color-Based Transformations</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Brightness Adjustment: Increases or decreases the intensity of pixels.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Contrast Adjustment: Enhances or reduces differences between light and dark areas.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Saturation Adjustment: Modifies the intensity of colors.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Hue Shift: Changes the color balance of the image.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Grayscale Conversion: Removes color information, leaving only intensity.</p>', unsafe_allow_html=True)
st.markdown('<p class="subtitle">Noise and Distortion-Based Transformations</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Gaussian Noise: Adds random noise to simulate different lighting conditions.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Motion Blur: Simulates movement in the image.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Pixelation: Reduces image resolution to test model robustness.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Elastic Transform: Warps the image in a random, elastic manner.</p>', unsafe_allow_html=True)
st.markdown('<p class="subtitle">Why Use Image Augmentation?</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Prevents Overfitting: Helps the model generalize better by introducing variations.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Reduces Data Collection Costs: Generates new samples without additional real-world data.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Improves Model Performance: Enhances accuracy and robustness in real-world conditions.</p>', unsafe_allow_html=True)
st.markdown('<p class="content">Handles Imbalanced Datasets: Can create variations for underrepresented classes.</p>', unsafe_allow_html=True)
import streamlit as st
import cv2
import numpy as np
from PIL import Image
import random
# Function to apply multiple augmentations
def augment_image(image):
augmented_images = []
# Convert to OpenCV format
img_cv = np.array(image)
# 1. Rotate Image (Random 0-360 degrees)
angle = random.choice([90, 180, 270])
rotated = cv2.rotate(img_cv, cv2.ROTATE_90_CLOCKWISE if angle == 90 else
cv2.ROTATE_180 if angle == 180 else
cv2.ROTATE_90_COUNTERCLOCKWISE)
augmented_images.append(rotated)
# 2. Flip Horizontally
flipped = cv2.flip(img_cv, 1)
augmented_images.append(flipped)
# 3. Adjust Brightness (Increase)
bright = cv2.convertScaleAbs(img_cv, alpha=1.2, beta=30)
augmented_images.append(bright)
# 4. Add Gaussian Noise
noise = img_cv + np.random.normal(0, 25, img_cv.shape).astype(np.uint8)
noise = np.clip(noise, 0, 255)
augmented_images.append(noise)
# 5. Zoom In (Crop & Resize)
h, w, _ = img_cv.shape
crop_x, crop_y = int(0.2 * w), int(0.2 * h)
zoomed = img_cv[crop_y:h-crop_y, crop_x:w-crop_x]
zoomed = cv2.resize(zoomed, (w, h))
augmented_images.append(zoomed)
# 6. Convert to Grayscale
grayscale = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
grayscale = cv2.cvtColor(grayscale, cv2.COLOR_GRAY2BGR) # Convert back to 3 channels for uniformity
augmented_images.append(grayscale)
# 7. Contrast Adjustment
contrast = cv2.convertScaleAbs(img_cv, alpha=1.5, beta=0)
augmented_images.append(contrast)
# 8. Blurring (Gaussian)
blurred = cv2.GaussianBlur(img_cv, (11, 11), 0)
augmented_images.append(blurred)
return augmented_images
# Streamlit UI
st.title("Image Augmentation App 📸")
# Upload Image Section
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
if uploaded_file:
# Convert uploaded file to Image
image = Image.open(uploaded_file)
st.image(image, caption="Original Image", use_container_width=True)
# Augmentation Button
if st.button("Augment Image"):
augmented_imgs = augment_image(image)
# Display all augmented images
st.subheader("Augmented Images:")
cols = st.columns(4) # Creating columns for better layout
for i, aug_img in enumerate(augmented_imgs):
with cols[i % 4]:
st.image(aug_img, caption=f"Augmented {i+1}", use_container_width=True)