Update Introduction.py

#1
by Krishnaveni11 - opened
Files changed (1) hide show
  1. Introduction.py +136 -176
Introduction.py CHANGED
@@ -1,188 +1,148 @@
1
  import streamlit as st
2
- from PIL import Image
3
  import random
4
- import os
5
- import zipfile
6
  import io
7
 
8
- # Directory to save images
9
- SAVE_DIR = r"C:\Users\syam0\Downloads\Image App"
10
-
11
- # Ensure the directory exists
12
- if not os.path.exists(SAVE_DIR):
13
- os.makedirs(SAVE_DIR)
14
-
15
- # Augmentation functions with user inputs
16
- def scale_image(image, count, scale_factor=None):
17
- if scale_factor is None:
18
- scale_factor = random.uniform(0.8, 1.2)
19
- return [image.resize((int(image.width * scale_factor), int(image.height * scale_factor))) for _ in range(count)]
20
-
21
- def translate_image(image, count, axis, translation_range=(-40, 40)):
22
- translations = []
23
- for _ in range(count):
24
- if axis == "x-axis":
25
- translation_x = random.randint(*translation_range)
26
- translation_y = 0
27
- elif axis == "y-axis":
28
- translation_x = 0
29
- translation_y = random.randint(*translation_range)
30
- else:
31
- translation_x = random.randint(*translation_range)
32
- translation_y = random.randint(*translation_range)
33
- translated_image = image.transform(image.size, Image.AFFINE, (1, 0, translation_x, 0, 1, translation_y))
34
- translations.append(translated_image)
35
- return translations
36
-
37
- def crop_image(image, count, crop_margin=None):
38
- if crop_margin is None:
39
- crop_margin = random.randint(5, 20)
40
- return [image.crop((crop_margin, crop_margin, image.width - crop_margin, image.height - crop_margin)) for _ in range(count)]
41
-
42
- def rotate_image(image, count, angle=None):
43
- if angle is None:
44
- angle = random.randint(0, 360)
45
- return [image.rotate(angle) for _ in range(count)]
46
-
47
- def shear_image(image, count, shear_factor=None):
48
- if shear_factor is None:
49
- shear_factor = random.uniform(-0.5, 0.5)
50
- return [
51
- image.transform(image.size, Image.AFFINE, (1, shear_factor, 0, shear_factor, 1, 0))
52
- for _ in range(count)
53
- ]
54
-
55
- # Function to save images to the specified directory
56
- def save_images(images, prefix):
57
- saved_files = []
58
- for i, img in enumerate(images):
59
- filename = os.path.join(SAVE_DIR, f"{prefix}_image_{i+1}.png")
60
- img.save(filename, format="PNG")
61
- saved_files.append(filename)
62
- return saved_files
63
-
64
- # Function to zip the images
65
- def create_zip(saved_files):
66
- zip_buffer = io.BytesIO()
67
- with zipfile.ZipFile(zip_buffer, "w") as zipf:
68
- for file in saved_files:
69
- zipf.write(file, os.path.basename(file))
70
- zip_buffer.seek(0)
71
- return zip_buffer
72
-
73
- # Custom CSS for background and styling
74
- st.markdown(
75
- """
76
- <style>
77
- body {
78
- background: linear-gradient(#ffaa80, #ff5500, #b33c00); /* Gradient background from yellow to red */
79
- font-family: 'Arial', sans-serif;
80
- color: #333;
81
- }
82
- .stApp {
83
- background: linear-gradient(#66d9ff, #d966ff, #66ff66); /* Gradient background for the entire app */
84
- }
85
- .stFileUploader {
86
- display: flex;
87
- justify-content: center;
88
- align-items: center;
89
- padding: 30px;
90
- border: 2px dashed #4CAF50; /* Green dashed border for a fresh look */
91
- background-color: rgba(76, 175, 80, 0.1); /* Light green background on hover */
92
- border-radius: 8px;
93
- cursor: pointer;
94
- }
95
- .stFileUploader:hover {
96
- background-color: rgba(76, 175, 80, 0.2); /* Slightly darker green on hover */
97
- }
98
- </style>
99
- """,
100
- unsafe_allow_html=True
101
- )
102
-
103
- # Streamlit app
104
- st.title("Image Augmentation App with Gradient Background")
105
-
106
- # Image uploader with custom styling
107
- uploaded_image = st.file_uploader("Drag and Drop Your Image", type=["jpg", "jpeg", "png"], label_visibility="collapsed")
108
-
109
- if uploaded_image:
110
- image = Image.open(uploaded_image)
111
- st.image(image, caption="Uploaded Image", use_container_width=True) # Fixed the deprecation warning by using `use_container_width=True`
112
-
113
- # User inputs for augmentation
114
- st.write("### Generate Augmented Images")
115
- num_augments = st.number_input("How many augmented images would you like to generate?", min_value=1, max_value=20, value=5)
116
-
117
- # Additional inputs for specific techniques
118
- rotate_angle = st.number_input("Enter the angle for rotation (0-360):", min_value=0, max_value=360, value=random.randint(0, 360))
119
- scale_factor = st.number_input("Enter the scaling factor (0.8-1.2):", min_value=0.8, max_value=1.2, value=random.uniform(0.8, 1.2))
120
- crop_margin = st.number_input("Enter the crop margin (5-20):", min_value=5, max_value=20, value=random.randint(5, 20))
121
- shear_factor = st.number_input("Enter the shear factor (-0.5 to 0.5):", min_value=-0.5, max_value=0.5, value=random.uniform(-0.5, 0.5))
122
- translate_axis = st.selectbox("Select axis for translation:", ["x-axis", "y-axis", "both axes"])
123
-
124
- # Generate and save all augmentations
125
- if st.button("Generate All Techniques"):
126
- all_augmentations = scale_image(image, num_augments, scale_factor) + \
127
- translate_image(image, num_augments, translate_axis) + \
128
- crop_image(image, num_augments, crop_margin) + \
129
- rotate_image(image, num_augments, rotate_angle) + \
130
- shear_image(image, num_augments, shear_factor)
131
 
132
- # Save images to the specified folder
133
- st.write("Generating and Saving Images...")
134
- saved_files = save_images(all_augmentations, "combined")
 
 
135
 
136
- # Display generated images
137
- st.write("Generated Augmented Images:")
138
- for img in all_augmentations:
139
- st.image(img, use_container_width=True)
140
-
141
- # Create a zip file
142
- zip_buffer = create_zip(saved_files)
143
 
144
- # Provide a download button for the zip file
145
- st.download_button(
146
- label="Download Augmented Images (ZIP)",
147
- data=zip_buffer,
148
- file_name="augmented_images.zip",
149
- mime="application/zip"
150
- )
151
-
152
- # Generate and save technique-specific augmentations
153
- st.write("### Select Specific Technique")
154
- technique = st.selectbox("Choose an augmentation technique:",
155
- ["Scale", "Translate", "Crop", "Rotate", "Shear"])
156
- technique_count = st.number_input(f"How many images do you want for {technique}?", min_value=1, max_value=20, value=5)
157
-
158
- if st.button(f"Generate and Save {technique} Images"):
159
- if technique == "Scale":
160
- specific_augmentations = scale_image(image, technique_count, scale_factor)
161
- elif technique == "Translate":
162
- specific_augmentations = translate_image(image, technique_count, translate_axis)
163
- elif technique == "Crop":
164
- specific_augmentations = crop_image(image, technique_count, crop_margin)
165
- elif technique == "Rotate":
166
- specific_augmentations = rotate_image(image, technique_count, rotate_angle)
167
- elif technique == "Shear":
168
- specific_augmentations = shear_image(image, technique_count, shear_factor)
169
 
170
- # Save images to the specified folder
171
- st.write(f"Generating and Saving {technique} Images...")
172
- saved_files = save_images(specific_augmentations, technique.lower())
 
 
 
173
 
174
- # Display generated images
175
- st.write(f"Generated {technique} Augmented Images:")
176
- for img in specific_augmentations:
177
- st.image(img, use_container_width=True)
 
 
 
178
 
179
- # Create a zip file
180
- zip_buffer = create_zip(saved_files)
181
 
182
- # Provide a download button for the zip file
 
 
183
  st.download_button(
184
- label=f"Download {technique} Augmented Images (ZIP)",
185
- data=zip_buffer,
186
- file_name=f"{technique.lower()}_augmented_images.zip",
187
- mime="application/zip"
188
- )
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from PIL import Image, ImageEnhance, ImageOps
3
  import random
 
 
4
  import io
5
 
6
+ # --- Helper Functions for Image Transformations ---
7
+ def translate_image(image, x_offset, y_offset):
8
+ """Translate the image by x and y offsets."""
9
+ return image.transform(
10
+ image.size,
11
+ Image.AFFINE,
12
+ (1, 0, x_offset, 0, 1, y_offset),
13
+ resample=Image.BICUBIC
14
+ )
15
+
16
+ def rotate_image(image, angle):
17
+ """Rotate the image by a given angle."""
18
+ return image.rotate(angle, expand=True)
19
+
20
+ def scale_image(image, scale_factor):
21
+ """Scale the image by a given factor."""
22
+ new_size = (int(image.width * scale_factor), int(image.height * scale_factor))
23
+ return image.resize(new_size)
24
+
25
+ def crop_image(image, left, upper, right, lower):
26
+ """Crop the image."""
27
+ return image.crop((left, upper, right, lower))
28
+
29
+ def flip_image(image, flip_type):
30
+ """Flip the image horizontally or vertically."""
31
+ if flip_type == 'Horizontal':
32
+ return ImageOps.mirror(image)
33
+ elif flip_type == 'Vertical':
34
+ return ImageOps.flip(image)
35
+ return image
36
+
37
+ # --- Main App Function ---
38
+ def main():
39
+ st.set_page_config(
40
+ page_title="Interactive Image Augmentation Tool",
41
+ layout="wide"
42
+ )
43
+
44
+ # --- Styling ---
45
+ st.markdown(
46
+ """
47
+ <style>
48
+ .stTitle {
49
+ color: #3E2723;
50
+ text-align: center;
51
+ font-family: 'Arial', sans-serif;
52
+ }
53
+ .stButton>button {
54
+ background-color: #C19A6B;
55
+ color: white;
56
+ border-radius: 8px;
57
+ }
58
+ .stDownloadButton>button {
59
+ background-color: #8B5E3C;
60
+ color: white;
61
+ border-radius: 8px;
62
+ }
63
+ </style>
64
+ """,
65
+ unsafe_allow_html=True
66
+ )
67
+
68
+ # --- Title and Introduction ---
69
+ st.title("πŸ–ΌοΈ Interactive Image Augmentation Tool")
70
+ st.write("""
71
+ Welcome to the **Interactive Image Augmentation Tool**! This app allows you to transform and enhance your images
72
+ using various augmentation techniques like **Translation**, **Rotation**, **Scaling**, **Cropping**, and **Flipping**.
73
+ """)
74
+
75
+ st.write("""
76
+ ### πŸ“ Instructions for Use:
77
+ - Upload an image using the uploader below.
78
+ - Select a transformation technique from the dropdown menu.
79
+ - Adjust the parameters using sliders and dropdowns.
80
+ - Preview the transformed image.
81
+ - Download the transformed image if you're satisfied.
82
+ """)
83
+
84
+ st.write("""
85
+ ### 🌟 Who Can Use This App?
86
+ - **Data Scientists:** Generate augmented datasets for image classification models.
87
+ - **Graphic Designers:** Experiment with creative visual effects.
88
+ - **Researchers:** Prepare data for analysis and experiments.
89
+ - **Students:** Learn image processing techniques interactively.
90
+ """)
91
+
92
+ # --- File Uploader ---
93
+ uploaded_file = st.file_uploader("πŸ“€ Upload an Image", type=['jpg', 'jpeg', 'png'])
94
+ if uploaded_file:
95
+ image = Image.open(uploaded_file)
96
+ st.image(image, caption="Original Image", use_column_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
+ st.subheader("πŸ”„ Apply Transformations")
99
+ transformation = st.selectbox(
100
+ "Choose a Transformation",
101
+ ["Translate", "Rotate", "Scale", "Crop", "Flip"]
102
+ )
103
 
104
+ if transformation == "Translate":
105
+ x_offset = st.slider("X Offset", -100, 100, 0)
106
+ y_offset = st.slider("Y Offset", -100, 100, 0)
107
+ transformed_image = translate_image(image, x_offset, y_offset)
 
 
 
108
 
109
+ elif transformation == "Rotate":
110
+ angle = st.slider("Rotation Angle", 0, 360, 0)
111
+ transformed_image = rotate_image(image, angle)
112
+
113
+ elif transformation == "Scale":
114
+ scale = st.slider("Scale Factor", 0.5, 2.0, 1.0)
115
+ transformed_image = scale_image(image, scale)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
+ elif transformation == "Crop":
118
+ left = st.slider("Left", 0, image.width, 0)
119
+ upper = st.slider("Upper", 0, image.height, 0)
120
+ right = st.slider("Right", left, image.width, image.width)
121
+ lower = st.slider("Lower", upper, image.height, image.height)
122
+ transformed_image = crop_image(image, left, upper, right, lower)
123
 
124
+ elif transformation == "Flip":
125
+ flip_type = st.selectbox("Flip Type", ["None", "Horizontal", "Vertical"])
126
+ transformed_image = flip_image(image, flip_type)
127
+
128
+ else:
129
+ st.warning("Select a valid transformation!")
130
+ return
131
 
132
+ st.image(transformed_image, caption="Transformed Image", use_column_width=True)
 
133
 
134
+ # --- Download Image ---
135
+ img_buffer = io.BytesIO()
136
+ transformed_image.save(img_buffer, format="PNG")
137
  st.download_button(
138
+ label="πŸ“₯ Download Transformed Image",
139
+ data=img_buffer.getvalue(),
140
+ file_name="transformed_image.png",
141
+ mime="image/png"
142
+ )
143
+
144
+ st.markdown("---")
145
+ st.write("🎯 **Experiment with transformations and download your enhanced images today!**")
146
+
147
+ if __name__ == "__main__":
148
+ main()