Spaces:
Build error
Build error
File size: 9,988 Bytes
a8aca45 b423920 a8aca45 b423920 a8aca45 b423920 a8aca45 b423920 a8aca45 b423920 a8aca45 b423920 a8aca45 b423920 a8aca45 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | 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() |