Krishnaveni11 commited on
Commit
7146af7
ยท
verified ยท
1 Parent(s): 9cd1a26

Update python.py

Browse files
Files changed (1) hide show
  1. python.py +162 -176
python.py CHANGED
@@ -1,188 +1,174 @@
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
+ body {
49
+ background: linear-gradient(to right, #F5F5DC, #E6D8C3, #D2B48C, #DEB887);
50
+ color: #5A5A5A;
51
+ }
52
+ .stTitle {
53
+ color: #3E2723;
54
+ text-align: center;
55
+ font-family: 'Arial', sans-serif;
56
+ }
57
+ .stButton>button {
58
+ background-color: #C19A6B;
59
+ color: white;
60
+ border-radius: 8px;
61
+ }
62
+ .stDownloadButton>button {
63
+ background-color: #8B5E3C;
64
+ color: white;
65
+ border-radius: 8px;
66
+ }
67
+ .instruction-box {
68
+ background: #FAF0E6;
69
+ border-left: 5px solid #C19A6B;
70
+ padding: 10px;
71
+ margin: 20px 0;
72
+ border-radius: 5px;
73
+ }
74
+ .use-case-box {
75
+ background: #FFF5EE;
76
+ border-left: 5px solid #8B5E3C;
77
+ padding: 10px;
78
+ margin: 20px 0;
79
+ border-radius: 5px;
80
+ }
81
+ </style>
82
+ """,
83
+ unsafe_allow_html=True
84
+ )
85
+
86
+ # --- Title and Introduction ---
87
+ st.title("๐Ÿ–ผ๏ธ Interactive Image Augmentation Tool")
88
+ st.write("""
89
+ Welcome to the **Interactive Image Augmentation Tool**! This app allows you to transform and enhance your images
90
+ using various augmentation techniques like **Translation**, **Rotation**, **Scaling**, **Cropping**, and **Flipping**.
91
+ """)
92
+
93
+ st.markdown("""
94
+ <div class='instruction-box'>
95
+ <h4>๐Ÿ“ Instructions for Use:</h4>
96
+ <ul>
97
+ <li>Upload an image using the uploader below.</li>
98
+ <li>Select a transformation technique from the dropdown menu.</li>
99
+ <li>Adjust the parameters using sliders and dropdowns.</li>
100
+ <li>Preview the transformed image.</li>
101
+ <li>Download the transformed image if you're satisfied.</li>
102
+ </ul>
103
+ </div>
104
+ """, unsafe_allow_html=True)
105
+
106
+ st.markdown("""
107
+ <div class='use-case-box'>
108
+ <h4>๐ŸŒŸ Who Can Use This App?</h4>
109
+ <ul>
110
+ <li><b>Data Scientists:</b> Generate augmented datasets for image classification models.</li>
111
+ <li><b>Graphic Designers:</b> Experiment with creative visual effects.</li>
112
+ <li><b>Researchers:</b> Prepare data for analysis and experiments.</li>
113
+ <li><b>Students:</b> Learn image processing techniques interactively.</li>
114
+ </ul>
115
+ </div>
116
+ """, unsafe_allow_html=True)
117
+
118
+ # --- File Uploader ---
119
+ uploaded_file = st.file_uploader("๐Ÿ“ค Upload an Image", type=['jpg', 'jpeg', 'png'])
120
+ if uploaded_file:
121
+ image = Image.open(uploaded_file)
122
+ st.image(image, caption="Original Image", use_column_width=True)
 
 
 
 
 
 
123
 
124
+ st.subheader("๐Ÿ”„ Apply Transformations")
125
+ transformation = st.selectbox(
126
+ "Choose a Transformation",
127
+ ["Translate", "Rotate", "Scale", "Crop", "Flip"]
128
+ )
129
 
130
+ if transformation == "Translate":
131
+ x_offset = st.slider("X Offset", -100, 100, 0)
132
+ y_offset = st.slider("Y Offset", -100, 100, 0)
133
+ transformed_image = translate_image(image, x_offset, y_offset)
 
 
 
134
 
135
+ elif transformation == "Rotate":
136
+ angle = st.slider("Rotation Angle", 0, 360, 0)
137
+ transformed_image = rotate_image(image, angle)
138
+
139
+ elif transformation == "Scale":
140
+ scale = st.slider("Scale Factor", 0.5, 2.0, 1.0)
141
+ transformed_image = scale_image(image, scale)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
+ elif transformation == "Crop":
144
+ left = st.slider("Left", 0, image.width, 0)
145
+ upper = st.slider("Upper", 0, image.height, 0)
146
+ right = st.slider("Right", left, image.width, image.width)
147
+ lower = st.slider("Lower", upper, image.height, image.height)
148
+ transformed_image = crop_image(image, left, upper, right, lower)
149
 
150
+ elif transformation == "Flip":
151
+ flip_type = st.selectbox("Flip Type", ["None", "Horizontal", "Vertical"])
152
+ transformed_image = flip_image(image, flip_type)
153
+
154
+ else:
155
+ st.warning("Select a valid transformation!")
156
+ return
157
 
158
+ st.image(transformed_image, caption="Transformed Image", use_column_width=True)
 
159
 
160
+ # --- Download Image ---
161
+ img_buffer = io.BytesIO()
162
+ transformed_image.save(img_buffer, format="PNG")
163
  st.download_button(
164
+ label="๐Ÿ“ฅ Download Transformed Image",
165
+ data=img_buffer.getvalue(),
166
+ file_name="transformed_image.png",
167
+ mime="image/png"
168
+ )
169
+
170
+ st.markdown("---")
171
+ st.write("๐ŸŽฏ **Experiment with transformations and download your enhanced images today!**")
172
+
173
+ if __name__ == "__main__":
174
+ main()