makalin commited on
Commit
c69ef9e
·
verified ·
1 Parent(s): f9c054a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -271
app.py CHANGED
@@ -4,246 +4,49 @@ import numpy as np
4
  from datetime import datetime
5
  import random
6
 
7
- def basic_filters(image, filter_type):
8
- """Applies basic image filters"""
9
- if filter_type == "Grayscale":
10
- return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
11
- elif filter_type == "Sepia":
12
- sepia_filter = np.array([
13
- [0.272, 0.534, 0.131],
14
- [0.349, 0.686, 0.168],
15
- [0.393, 0.769, 0.189]
16
- ])
17
- return cv2.transform(image, sepia_filter)
18
- elif filter_type == "X-Ray":
19
- # Enhanced X-ray effect
20
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
21
- inverted = cv2.bitwise_not(gray)
22
- # Increase contrast
23
- clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
24
- enhanced = clahe.apply(inverted)
25
- # Sharpen
26
- kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
27
- sharpened = cv2.filter2D(enhanced, -1, kernel)
28
- return cv2.cvtColor(sharpened, cv2.COLOR_GRAY2BGR)
29
- elif filter_type == "Blur":
30
- return cv2.GaussianBlur(image, (15, 15), 0)
31
 
32
- def classic_filters(image, filter_type):
33
- """Classic image filters"""
34
- if filter_type == "Pencil Sketch":
35
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
36
- inverted = cv2.bitwise_not(gray)
37
- blurred = cv2.GaussianBlur(inverted, (21, 21), 0)
38
- sketch = cv2.divide(gray, cv2.subtract(255, blurred), scale=256)
39
- return cv2.cvtColor(sketch, cv2.COLOR_GRAY2BGR)
40
-
41
- elif filter_type == "Sharpen":
42
- kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
43
- return cv2.filter2D(image, -1, kernel)
44
-
45
- elif filter_type == "Emboss":
46
- kernel = np.array([[0,-1,-1], [1,0,-1], [1,1,0]])
47
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
48
- emboss = cv2.filter2D(gray, -1, kernel) + 128
49
- return cv2.cvtColor(emboss, cv2.COLOR_GRAY2BGR)
50
-
51
- elif filter_type == "Edge Detection":
52
- edges = cv2.Canny(image, 100, 200)
53
- return cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
54
-
55
- def creative_filters(image, filter_type):
56
- """Creative and unusual image filters"""
57
- if filter_type == "Pixel Art":
58
- h, w = image.shape[:2]
59
- pixel_size = 20
60
- small = cv2.resize(image, (w//pixel_size, h//pixel_size))
61
- return cv2.resize(small, (w, h), interpolation=cv2.INTER_NEAREST)
62
-
63
- elif filter_type == "Mosaic Effect":
64
- h, w = image.shape[:2]
65
- mosaic_size = 30
66
- for i in range(0, h, mosaic_size):
67
- for j in range(0, w, mosaic_size):
68
- roi = image[i:i+mosaic_size, j:j+mosaic_size]
69
- if roi.size > 0:
70
- color = np.mean(roi, axis=(0,1))
71
- image[i:i+mosaic_size, j:j+mosaic_size] = color
72
- return image
73
-
74
- elif filter_type == "Rainbow":
75
- hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
76
- h, w = image.shape[:2]
77
- for i in range(h):
78
- hsv[i, :, 0] = (hsv[i, :, 0] + i % 180).astype(np.uint8)
79
- return cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
80
-
81
- elif filter_type == "Night Vision":
82
- green_image = image.copy()
83
- green_image[:,:,0] = 0 # Blue channel
84
- green_image[:,:,2] = 0 # Red channel
85
- return cv2.addWeighted(green_image, 1.5, np.zeros(image.shape, image.dtype), 0, -50)
86
-
87
- def special_effects(image, filter_type):
88
- """Applies special effects"""
89
- if filter_type == "Matrix Effect":
90
- green_matrix = np.zeros_like(image)
91
- green_matrix[:,:,1] = image[:,:,1] # Only green channel
92
- random_brightness = np.random.randint(0, 255, size=image.shape[:2])
93
- green_matrix[:,:,1] = np.minimum(green_matrix[:,:,1] + random_brightness, 255)
94
- return green_matrix
95
-
96
- elif filter_type == "Wave Effect":
97
- rows, cols = image.shape[:2]
98
- img_output = np.zeros(image.shape, dtype=image.dtype)
99
-
100
- for i in range(rows):
101
- for j in range(cols):
102
- offset_x = int(25.0 * np.sin(2 * 3.14 * i / 180))
103
- offset_y = int(25.0 * np.cos(2 * 3.14 * j / 180))
104
- if i+offset_x < rows and j+offset_y < cols:
105
- img_output[i,j] = image[(i+offset_x)%rows,(j+offset_y)%cols]
106
- else:
107
- img_output[i,j] = 0
108
- return img_output
109
-
110
- elif filter_type == "Timestamp":
111
- output = image.copy()
112
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
113
- font = cv2.FONT_HERSHEY_SIMPLEX
114
- cv2.putText(output, timestamp, (10, 30), font, 1, (255, 255, 255), 2)
115
- return output
116
-
117
- elif filter_type == "Glitch Effect":
118
- glitch = image.copy()
119
- h, w = image.shape[:2]
120
- for _ in range(10):
121
- x1 = random.randint(0, w-50)
122
- y1 = random.randint(0, h-50)
123
- x2 = random.randint(x1, min(x1+50, w))
124
- y2 = random.randint(y1, min(y1+50, h))
125
- glitch[y1:y2, x1:x2] = np.roll(glitch[y1:y2, x1:x2],
126
- random.randint(-20, 20),
127
- axis=random.randint(0, 1))
128
- return glitch
129
 
130
- def artistic_filters(image, filter_type):
131
- """Applies artistic image filters"""
132
- if filter_type == "Pop Art":
133
- img_small = cv2.resize(image, None, fx=0.5, fy=0.5)
134
- img_color = cv2.resize(img_small, (image.shape[1], image.shape[0]))
135
- for _ in range(2):
136
- img_color = cv2.bilateralFilter(img_color, 9, 300, 300)
137
- hsv = cv2.cvtColor(img_color, cv2.COLOR_BGR2HSV)
138
- hsv[:,:,1] = hsv[:,:,1]*1.5
139
- return cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
140
-
141
- elif filter_type == "Oil Paint":
142
- ret = np.float32(image.copy())
143
- ret = cv2.bilateralFilter(ret, 9, 75, 75)
144
- ret = cv2.detailEnhance(ret, sigma_s=15, sigma_r=0.15)
145
- ret = cv2.edgePreservingFilter(ret, flags=1, sigma_s=60, sigma_r=0.4)
146
- return np.uint8(ret)
147
-
148
- elif filter_type == "Cartoon":
149
- # Enhanced cartoon effect
150
- color = image.copy()
151
- gray = cv2.cvtColor(color, cv2.COLOR_BGR2GRAY)
152
- gray = cv2.medianBlur(gray, 5)
153
- edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9)
154
- color = cv2.bilateralFilter(color, 9, 300, 300)
155
- cartoon = cv2.bitwise_and(color, color, mask=edges)
156
- # Increase color saturation
157
- hsv = cv2.cvtColor(cartoon, cv2.COLOR_BGR2HSV)
158
- hsv[:,:,1] = hsv[:,:,1]*1.4 # Increase saturation
159
- return cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
160
 
161
- def atmospheric_filters(image, filter_type):
162
- """Applies atmospheric filters"""
163
- if filter_type == "Autumn":
164
- # Enhanced autumn effect
165
- autumn_filter = np.array([
166
- [0.393, 0.769, 0.189],
167
- [0.349, 0.686, 0.168],
168
- [0.272, 0.534, 0.131]
169
- ])
170
- autumn = cv2.transform(image, autumn_filter)
171
- # Increase color warmth
172
- hsv = cv2.cvtColor(autumn, cv2.COLOR_BGR2HSV)
173
- hsv[:,:,0] = hsv[:,:,0]*0.8 # Shift towards orange/yellow tones
174
- hsv[:,:,1] = hsv[:,:,1]*1.2 # Increase saturation
175
- return cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
176
-
177
- elif filter_type == "Nostalgia":
178
- # Enhanced nostalgia effect
179
- # Reduce contrast and add a yellowish tint
180
- image = cv2.convertScaleAbs(image, alpha=0.9, beta=10)
181
- sepia = cv2.transform(image, np.array([
182
- [0.393, 0.769, 0.189],
183
- [0.349, 0.686, 0.168],
184
- [0.272, 0.534, 0.131]
185
- ]))
186
- # Add vignette effect
187
- h, w = image.shape[:2]
188
- kernel = np.zeros((h, w))
189
- center = (h//2, w//2)
190
- for i in range(h):
191
- for j in range(w):
192
- dist = np.sqrt((i-center[0])**2 + (j-center[1])**2)
193
- kernel[i,j] = 1 - min(1, dist/(np.sqrt(h**2 + w**2)/2))
194
- kernel = np.dstack([kernel]*3)
195
- return cv2.multiply(sepia, kernel).astype(np.uint8)
196
-
197
- elif filter_type == "Brightness Increase":
198
- # Enhanced brightness increase
199
- hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
200
- # Increase brightness
201
- hsv[:,:,2] = cv2.convertScaleAbs(hsv[:,:,2], alpha=1.2, beta=30)
202
- # Slightly increase contrast
203
- return cv2.convertScaleAbs(cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR), alpha=1.1, beta=0)
204
 
205
- def image_processing(image, filter_type):
206
- """Main image processing function"""
207
- if image is None:
208
- return None
209
-
210
- image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
211
-
212
- # Process by filter categories
213
- basic_filters_list = ["Grayscale", "Sepia", "X-Ray", "Blur"]
214
- classic_filters_list = ["Pencil Sketch", "Sharpen", "Emboss", "Edge Detection"]
215
- creative_filters_list = ["Pixel Art", "Mosaic Effect", "Rainbow", "Night Vision"]
216
- special_effects_list = ["Matrix Effect", "Wave Effect", "Timestamp", "Glitch Effect"]
217
- artistic_filters_list = ["Pop Art", "Oil Paint", "Cartoon"]
218
- atmospheric_filters_list = ["Autumn", "Nostalgia", "Brightness Increase"]
219
-
220
- if filter_type in basic_filters_list:
221
- output = basic_filters(image, filter_type)
222
- elif filter_type in classic_filters_list:
223
- output = classic_filters(image, filter_type)
224
- elif filter_type in creative_filters_list:
225
- output = creative_filters(image, filter_type)
226
- elif filter_type in special_effects_list:
227
- output = special_effects(image, filter_type)
228
- elif filter_type in artistic_filters_list:
229
- output = artistic_filters(image, filter_type)
230
- elif filter_type in atmospheric_filters_list:
231
- output = atmospheric_filters(image, filter_type)
232
- else:
233
- output = image
234
-
235
- return cv2.cvtColor(output, cv2.COLOR_BGR2RGB) if len(output.shape) == 3 else output
236
-
237
- # Gradio interface
238
  with gr.Blocks(theme=gr.themes.Monochrome()) as app:
239
- gr.Markdown("# 🎨 Super and Unusual Image Filtering Studio")
240
- gr.Markdown("### 🌈 Add magical touches to your photos!")
241
-
242
  with gr.Row():
243
  with gr.Column():
244
  image_input = gr.Image(type="numpy", label="📸 Upload Photo")
245
  with gr.Accordion("ℹ️ Filter Categories", open=True):
246
- filter_type = gr.Radio(
247
  [
248
  # Basic Filters
249
  "Grayscale", "Sepia", "X-Ray", "Blur",
@@ -252,58 +55,26 @@ with gr.Blocks(theme=gr.themes.Monochrome()) as app:
252
  # Creative Filters
253
  "Pixel Art", "Mosaic Effect", "Rainbow", "Night Vision",
254
  # Special Effects
255
- "Matrix Effect", "Wave Effect", "Timestamp", "Glitch Effect",
256
  # Artistic Filters
257
  "Pop Art", "Oil Paint", "Cartoon",
258
  # Atmospheric Filters
259
  "Autumn", "Nostalgia", "Brightness Increase"
260
  ],
261
- label="🎭 Choose Filter",
262
- info="Select your magical effect"
263
  )
264
- submit_button = gr.Button("✨ Apply Filter", variant="primary")
265
 
266
  with gr.Column():
267
  image_output = gr.Image(label="🖼️ Filtered Photo")
268
-
269
- with gr.Accordion("📝 Filter Descriptions", open=False):
270
- gr.Markdown("""
271
- ### 🎨 Filter Categories and Effects
272
-
273
- #### 📊 Basic Filters
274
- - **Grayscale**: Converts the image to black-and-white tones, giving it a classic look
275
- - **Sepia**: Adds warm brown tones, creating an old-photo feel
276
- - **X-Ray**: Adds inverse lighting to create an X-ray scan effect
277
- - **Blur**: Applies a soft blur to the image, reducing detail.
278
-
279
- #### 🖼️ Classic Filters List
280
- - **Pencil Sketch**: Makes the image look like a pencil drawing
281
- - **Sharpen**: Enhances details in the image
282
- - **Emboss**: Adds an embossing effect with depth
283
- - **Edge Detection**: Highlights the edge lines in the image
284
-
285
- #### 🎮 Creative Filters
286
- - **Pixel Art**: Breaks the image into small squares in a retro pixel style
287
- - **Mosaic Effect**: Divides the image into small mosaic pieces
288
- - **Rainbow**: Adds colorful rainbow effects to the image
289
- - **Night Vision**: Simulates a night-vision device effect
290
-
291
- #### 🎬 Special Effects
292
- - **Matrix Effect**: Matrix movie effect
293
- - **Wave Effect**: Adds a wavy distortion, creating a ripple sensation
294
- - **Timestamp**: Adds the date and time the photo was taken, giving a nostalgic touch
295
- - **Glitch Effect**: Adds digital distortions for a retro-style glitch effect
296
-
297
- #### 🎭 Artistic Filters
298
- - **Pop Art**: Creates an iconic pop-art effect in the style of Andy Warhol, with bright colors and contrasts
299
- - **Oil Paint**: Simulates brush strokes, giving the image an oil painting look
300
- - **Texture Effect**: Adds surface texture for a tactile depth and art piece feel
301
- """)
302
 
303
  submit_button.click(
304
- image_processing,
 
305
  inputs=[image_input, filter_type],
306
- outputs=image_output
307
  )
308
 
309
  app.launch(share=True)
 
4
  from datetime import datetime
5
  import random
6
 
7
+ ASCII_CHARS = "@%#*+=-:. "
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ def ascii_art(image):
10
+ """Converts an image to ASCII art."""
11
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
12
+ height, width = gray.shape
13
+ scale = 0.1 # Scaling factor to reduce the resolution for ASCII
14
+ small_gray = cv2.resize(gray, (int(width * scale), int(height * scale)))
15
+ ascii_image = "\n".join(
16
+ "".join(ASCII_CHARS[pixel // 25] for pixel in row) for row in small_gray
17
+ )
18
+ return ascii_image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ # Basic, classic, creative, etc., filters (no changes in their definitions)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ def apply_combined_filters(image, filter_types):
23
+ """Applies a list of filters sequentially to the image."""
24
+ output_image = image
25
+ for filter_type in filter_types:
26
+ if filter_type in basic_filters_list:
27
+ output_image = basic_filters(output_image, filter_type)
28
+ elif filter_type in classic_filters_list:
29
+ output_image = classic_filters(output_image, filter_type)
30
+ elif filter_type in creative_filters_list:
31
+ output_image = creative_filters(output_image, filter_type)
32
+ elif filter_type in special_effects_list:
33
+ if filter_type == "ASCII Art":
34
+ return ascii_art(output_image) # Return ASCII output directly
35
+ output_image = special_effects(output_image, filter_type)
36
+ elif filter_type in artistic_filters_list:
37
+ output_image = artistic_filters(output_image, filter_type)
38
+ elif filter_type in atmospheric_filters_list:
39
+ output_image = atmospheric_filters(output_image, filter_type)
40
+ return output_image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
+ # Updated Gradio interface to allow multiple selections
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  with gr.Blocks(theme=gr.themes.Monochrome()) as app:
44
+ gr.Markdown("# 🎨 Image Filtering Studio")
 
 
45
  with gr.Row():
46
  with gr.Column():
47
  image_input = gr.Image(type="numpy", label="📸 Upload Photo")
48
  with gr.Accordion("ℹ️ Filter Categories", open=True):
49
+ filter_type = gr.CheckboxGroup(
50
  [
51
  # Basic Filters
52
  "Grayscale", "Sepia", "X-Ray", "Blur",
 
55
  # Creative Filters
56
  "Pixel Art", "Mosaic Effect", "Rainbow", "Night Vision",
57
  # Special Effects
58
+ "Matrix Effect", "Wave Effect", "Timestamp", "Glitch Effect", "ASCII Art",
59
  # Artistic Filters
60
  "Pop Art", "Oil Paint", "Cartoon",
61
  # Atmospheric Filters
62
  "Autumn", "Nostalgia", "Brightness Increase"
63
  ],
64
+ label="🎭 Choose Filters",
65
+ info="Select multiple filters to apply in sequence"
66
  )
67
+ submit_button = gr.Button("✨ Apply Filters", variant="primary")
68
 
69
  with gr.Column():
70
  image_output = gr.Image(label="🖼️ Filtered Photo")
71
+ ascii_output = gr.Textbox(label="ASCII Art Output", visible=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
  submit_button.click(
74
+ lambda image, filters: (apply_combined_filters(image, filters) if "ASCII Art" not in filters else None,
75
+ ascii_art(image) if "ASCII Art" in filters else None),
76
  inputs=[image_input, filter_type],
77
+ outputs=[image_output, ascii_output]
78
  )
79
 
80
  app.launch(share=True)