gdTharusha commited on
Commit
cce9696
1 Parent(s): 0415503

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -106
app.py CHANGED
@@ -1,71 +1,44 @@
1
- import gradio as gr
2
- from PIL import Image, ImageFilter, ImageOps
3
- import numpy as np
4
  import io
5
- import tempfile
 
6
  import vtracer
7
- from skimage import color, filters, feature, morphology, exposure, util
8
  import cv2
9
- from scipy import ndimage
10
- from sklearn.cluster import KMeans
11
  from rembg import remove
 
 
 
12
 
13
- def preprocess_image(image, blur_radius, sharpen_radius, noise_reduction, detail_level, edge_method, color_quantization, enhance_with_ai):
14
- """Advanced preprocessing of the image before vectorization."""
15
-
16
- if blur_radius > 0:
17
- image = image.filter(ImageFilter.GaussianBlur(blur_radius))
18
-
19
- if sharpen_radius > 0:
20
- image = image.filter(ImageFilter.UnsharpMask(radius=sharpen_radius, percent=150, threshold=3))
21
-
22
- if noise_reduction > 0:
23
- image_np = np.array(image)
24
- image_np = cv2.fastNlMeansDenoisingColored(image_np, None, h=noise_reduction, templateWindowSize=7, searchWindowSize=21)
25
- image = Image.fromarray(image_np)
26
 
27
- if detail_level > 0:
28
- sigma = max(0.5, 3.0 - (detail_level * 0.5))
29
- image_np = np.array(image.convert('L'))
30
-
31
- if edge_method == 'Canny':
32
- edges = feature.canny(image_np, sigma=sigma)
33
- elif edge_method == 'Sobel':
34
- edges = filters.sobel(image_np)
35
- elif edge_method == 'Scharr':
36
- edges = filters.scharr(image_np)
37
- else: # Prewitt
38
- edges = filters.prewitt(image_np)
39
-
40
- edges = morphology.dilation(edges, morphology.square(max(1, 6 - detail_level)))
41
- edges_img = Image.fromarray((edges * 255).astype(np.uint8))
42
- image = Image.blend(image.convert('RGB'), edges_img.convert('RGB'), alpha=0.5)
43
-
44
- if color_quantization > 0:
45
- image = quantize_colors(image, color_quantization)
46
 
47
- if enhance_with_ai:
 
48
  image_np = np.array(image)
49
- # AI-based enhancement with rembg for smoothing edges and improving vectorization
50
- image_np = remove(image_np)
51
- image = Image.fromarray(image_np)
 
 
52
 
53
- return image
 
 
 
54
 
55
- def convert_image(image, blur_radius, sharpen_radius, noise_reduction, detail_level, edge_method, color_quantization,
56
- color_mode, hierarchical, mode, filter_speckle, color_precision, layer_difference,
57
- corner_threshold, length_threshold, max_iterations, splice_threshold, path_precision,
58
- enhance_with_ai):
59
- """Convert an image to SVG using vtracer with customizable and advanced parameters."""
60
-
61
- # Preprocess the image with additional detail level settings
62
- image = preprocess_image(image, blur_radius, sharpen_radius, noise_reduction, detail_level, edge_method, color_quantization, enhance_with_ai)
63
-
64
  # Convert Gradio image to bytes for vtracer compatibility
65
  img_byte_array = io.BytesIO()
66
  image.save(img_byte_array, format='PNG')
67
  img_bytes = img_byte_array.getvalue()
68
-
69
  # Perform the conversion
70
  svg_str = vtracer.convert_raw_image_to_svg(
71
  img_bytes,
@@ -80,68 +53,48 @@ def convert_image(image, blur_radius, sharpen_radius, noise_reduction, detail_le
80
  length_threshold=float(length_threshold),
81
  max_iterations=int(max_iterations),
82
  splice_threshold=int(splice_threshold),
83
- path_precision=int(path_precision)
 
84
  )
85
-
86
  # Save the SVG string to a temporary file
87
  temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.svg')
88
  temp_file.write(svg_str.encode('utf-8'))
89
  temp_file.close()
90
-
91
- # Display the SVG in the Gradio interface and provide the download link
92
- svg_html = f'<svg viewBox="0 0 {image.width} {image.height}">{svg_str}</svg>'
93
- return gr.HTML(svg_html), temp_file.name
94
 
95
  # Gradio interface
96
  iface = gr.Blocks()
97
 
98
  with iface:
99
- gr.Markdown("# Super-Advanced Image to SVG Converter")
100
 
101
- with gr.Row():
102
- image_input = gr.Image(type="pil", label="Upload Image")
103
- blur_radius_input = gr.Slider(minimum=0, maximum=10, value=0, step=0.1, label="Blur Radius (for smoothing)")
104
- sharpen_radius_input = gr.Slider(minimum=0, maximum=5, value=0, step=0.1, label="Sharpen Radius")
105
- noise_reduction_input = gr.Slider(minimum=0, maximum=30, value=0, step=1, label="Noise Reduction")
106
- enhance_with_ai_input = gr.Checkbox(label="AI Edge Enhance", value=False)
107
-
108
- with gr.Row():
109
- detail_level_input = gr.Slider(minimum=0, maximum=10, value=5, step=1, label="Detail Level")
110
- edge_method_input = gr.Radio(choices=["Canny", "Sobel", "Scharr", "Prewitt"], value="Canny", label="Edge Detection Method")
111
- color_quantization_input = gr.Slider(minimum=2, maximum=64, value=0, step=2, label="Color Quantization (0 to disable)")
112
-
113
- with gr.Row():
114
- color_mode_input = gr.Radio(choices=["Color", "Binary"], value="Color", label="Color Mode")
115
- hierarchical_input = gr.Radio(choices=["Stacked", "Cutout"], value="Stacked", label="Hierarchical")
116
- mode_input = gr.Radio(choices=["Spline", "Polygon", "None"], value="Spline", label="Mode")
117
-
118
- with gr.Row():
119
- filter_speckle_input = gr.Slider(minimum=1, maximum=100, value=4, step=1, label="Filter Speckle")
120
- color_precision_input = gr.Slider(minimum=1, maximum=100, value=6, step=1, label="Color Precision")
121
- layer_difference_input = gr.Slider(minimum=1, maximum=100, value=16, step=1, label="Layer Difference")
122
-
123
- with gr.Row():
124
- corner_threshold_input = gr.Slider(minimum=1, maximum=100, value=60, step=1, label="Corner Threshold")
125
- length_threshold_input = gr.Slider(minimum=1, maximum=100, value=4.0, step=0.5, label="Length Threshold")
126
- max_iterations_input = gr.Slider(minimum=1, maximum=100, value=10, step=1, label="Max Iterations")
127
-
128
- with gr.Row():
129
- splice_threshold_input = gr.Slider(minimum=1, maximum=100, value=45, step=1, label="Splice Threshold")
130
- path_precision_input = gr.Slider(minimum=1, maximum=100, value=8, step=1, label="Path Precision")
131
-
132
- convert_button = gr.Button("Convert Image to SVG")
133
- svg_output = gr.HTML(label="SVG Output")
134
- download_output = gr.File(label="Download SVG")
135
-
136
- convert_button.click(
137
- fn=convert_image,
138
- inputs=[
139
- image_input, blur_radius_input, sharpen_radius_input, noise_reduction_input, detail_level_input, edge_method_input, color_quantization_input,
140
- color_mode_input, hierarchical_input, mode_input, filter_speckle_input, color_precision_input,
141
- layer_difference_input, corner_threshold_input, length_threshold_input, max_iterations_input,
142
- splice_threshold_input, path_precision_input, enhance_with_ai_input
143
- ],
144
- outputs=[svg_output, download_output]
145
- )
146
 
147
  iface.launch()
 
 
 
 
1
  import io
2
+ import gradio as gr
3
+ from PIL import Image
4
  import vtracer
5
+ import numpy as np
6
  import cv2
7
+ import tempfile
 
8
  from rembg import remove
9
+ from skimage import filters, img_as_ubyte, color, measure
10
+ from skimage.restoration import denoise_bilateral
11
+ from sklearn.cluster import KMeans
12
 
13
+ def convert_image(image, color_mode, hierarchical, mode, filter_speckle,
14
+ color_precision, layer_difference, corner_threshold,
15
+ length_threshold, max_iterations, splice_threshold, path_precision,
16
+ detail_level, ai_edge_enhance, smoothness, background_remove):
17
+ """Converts an image to SVG with customizable parameters and additional options."""
 
 
 
 
 
 
 
 
18
 
19
+ # Optionally remove the background
20
+ if background_remove:
21
+ image = Image.open(io.BytesIO(remove(np.array(image))))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # Apply AI enhancement and smoothness if selected
24
+ if ai_edge_enhance:
25
  image_np = np.array(image)
26
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
27
+ edges = filters.sobel(image_np)
28
+ enhanced = img_as_ubyte(edges)
29
+ enhanced = denoise_bilateral(enhanced, sigma_color=0.05, sigma_spatial=15, multichannel=False)
30
+ image = Image.fromarray(cv2.cvtColor(enhanced, cv2.COLOR_GRAY2RGB))
31
 
32
+ if smoothness > 0:
33
+ image_np = np.array(image)
34
+ image_np = cv2.GaussianBlur(image_np, (smoothness*2+1, smoothness*2+1), 0)
35
+ image = Image.fromarray(image_np)
36
 
 
 
 
 
 
 
 
 
 
37
  # Convert Gradio image to bytes for vtracer compatibility
38
  img_byte_array = io.BytesIO()
39
  image.save(img_byte_array, format='PNG')
40
  img_bytes = img_byte_array.getvalue()
41
+
42
  # Perform the conversion
43
  svg_str = vtracer.convert_raw_image_to_svg(
44
  img_bytes,
 
53
  length_threshold=float(length_threshold),
54
  max_iterations=int(max_iterations),
55
  splice_threshold=int(splice_threshold),
56
+ path_precision=int(path_precision),
57
+ detail_level=int(detail_level)
58
  )
59
+
60
  # Save the SVG string to a temporary file
61
  temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.svg')
62
  temp_file.write(svg_str.encode('utf-8'))
63
  temp_file.close()
64
+
65
+ return gr.HTML(f'<svg viewBox="0 0 {image.width} {image.height}">{svg_str}</svg>'), temp_file.name
 
 
66
 
67
  # Gradio interface
68
  iface = gr.Blocks()
69
 
70
  with iface:
 
71
 
72
+ gr.Interface(
73
+ fn=convert_image,
74
+ inputs=[
75
+ gr.Image(type="pil", label="Upload Image"),
76
+ gr.Radio(choices=["Color", "Binary"], value="Color", label="Color Mode"),
77
+ gr.Radio(choices=["Stacked", "Cutout"], value="Stacked", label="Hierarchical"),
78
+ gr.Radio(choices=["Spline", "Polygon", "None"], value="Spline", label="Mode"),
79
+ gr.Slider(minimum=1, maximum=100, value=4, step=1, label="Filter Speckle"),
80
+ gr.Slider(minimum=1, maximum=100, value=6, step=1, label="Color Precision"),
81
+ gr.Slider(minimum=1, maximum=100, value=16, step=1, label="Layer Difference"),
82
+ gr.Slider(minimum=1, maximum=100, value=60, step=1, label="Corner Threshold"),
83
+ gr.Slider(minimum=1, maximum=100, value=4.0, step=0.5, label="Length Threshold"),
84
+ gr.Slider(minimum=1, maximum=100, value=10, step=1, label="Max Iterations"),
85
+ gr.Slider(minimum=1, maximum=100, value=45, step=1, label="Splice Threshold"),
86
+ gr.Slider(minimum=1, maximum=100, value=8, step=1, label="Path Precision"),
87
+ gr.Slider(minimum=1, maximum=5, value=3, step=1, label="Detail Level"),
88
+ gr.Checkbox(value=False, label="AI Edge Enhance"),
89
+ gr.Slider(minimum=0, maximum=10, value=0, step=1, label="Smoothness"),
90
+ gr.Checkbox(value=False, label="Remove Background")
91
+ ],
92
+ outputs=[
93
+ gr.HTML(label="SVG Output"),
94
+ gr.File(label="Download SVG")
95
+ ],
96
+ title="Advanced Image to SVG Converter",
97
+ description="Upload an image and customize the conversion parameters as needed.",
98
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
  iface.launch()