Svg-Tracer-New / app.py
gdTharusha's picture
Update app.py
bb3573e verified
raw
history blame
No virus
7.15 kB
import gradio as gr
from PIL import Image, ImageFilter
import numpy as np
import io
import tempfile
import vtracer
from skimage import color, filters
from skimage.feature import canny
from skimage.measure import shannon_entropy
def analyze_image(image):
"""Automatically adjust settings based on image analysis."""
# Convert image to grayscale for analysis
gray_image = np.array(image.convert('L'))
# Calculate basic metrics
entropy = shannon_entropy(gray_image)
edges = canny(gray_image, sigma=1.0).mean() # Mean edge intensity
# Adjust parameters based on metrics
if entropy > 5.0:
blur_radius = 0
edge_enhance = True
edge_threshold = 2.0
else:
blur_radius = 2
edge_enhance = False
edge_threshold = 1.0
color_mode = "Color" if entropy > 4.0 else "Binary"
hierarchical = "Stacked" if edges > 0.1 else "Cutout"
mode = "Spline" if edges > 0.15 else "Polygon"
filter_speckle = int(5 if edges > 0.12 else 15)
color_precision = int(8 if entropy > 4.5 else 10)
layer_difference = int(12 if edges > 0.2 else 20)
corner_threshold = int(60 if edges > 0.12 else 75)
length_threshold = float(5.0 if edges > 0.15 else 10.0)
max_iterations = int(15 if entropy > 4.5 else 10)
splice_threshold = int(50 if entropy > 4.0 else 70)
path_precision = int(10 if edges > 0.15 else 5)
return (blur_radius, edge_enhance, edge_threshold, color_mode, hierarchical, mode,
filter_speckle, color_precision, layer_difference, corner_threshold, length_threshold,
max_iterations, splice_threshold, path_precision)
def convert_image(image, auto_settings, blur_radius, edge_enhance, edge_threshold, color_mode, hierarchical, mode,
filter_speckle, color_precision, layer_difference, corner_threshold, length_threshold,
max_iterations, splice_threshold, path_precision):
"""Converts an image to SVG using vtracer with customizable parameters."""
# Auto-adjust settings based on image if auto_settings is enabled
if auto_settings:
(blur_radius, edge_enhance, edge_threshold, color_mode, hierarchical, mode,
filter_speckle, color_precision, layer_difference, corner_threshold, length_threshold,
max_iterations, splice_threshold, path_precision) = analyze_image(image)
# Preprocess the image
image = preprocess_image(image, blur_radius, edge_enhance, edge_threshold)
# Convert Gradio image to bytes for vtracer compatibility
img_byte_array = io.BytesIO()
image.save(img_byte_array, format='PNG')
img_bytes = img_byte_array.getvalue()
# Perform the conversion with advanced settings
svg_str = vtracer.convert_raw_image_to_svg(
img_bytes,
img_format='png',
colormode=color_mode.lower(),
hierarchical=hierarchical.lower(),
mode=mode.lower(),
filter_speckle=int(filter_speckle),
color_precision=int(color_precision),
layer_difference=int(layer_difference),
corner_threshold=int(corner_threshold),
length_threshold=float(length_threshold),
max_iterations=int(max_iterations),
splice_threshold=int(splice_threshold),
path_precision=int(path_precision)
)
# Save the SVG string to a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.svg')
temp_file.write(svg_str.encode('utf-8'))
temp_file.close()
# Display the SVG in the Gradio interface and provide the download link
svg_html = f'<svg viewBox="0 0 {image.width} {image.height}">{svg_str}</svg>'
return gr.HTML(svg_html), temp_file.name
def preprocess_image(image, blur_radius, edge_enhance, edge_threshold):
"""Applies advanced preprocessing steps to the image before tracing."""
if blur_radius > 0:
image = image.filter(ImageFilter.GaussianBlur(blur_radius))
if edge_enhance:
# Convert image to grayscale and apply edge detection
gray_image = np.array(image.convert('L'))
edges = canny(gray_image, sigma=edge_threshold)
edges_img = Image.fromarray((edges * 255).astype(np.uint8))
image = Image.blend(image.convert('RGB'), edges_img.convert('RGB'), alpha=0.5)
return image
# Gradio interface
iface = gr.Blocks()
with iface:
gr.Markdown("# CPU-Optimized AI-Enhanced Image to SVG Vectors with Auto Settings")
gr.Markdown("Upload an image and either use custom parameters or let the auto settings analyze and adjust everything for you.")
with gr.Row():
image_input = gr.Image(type="pil", label="Upload Image")
auto_settings_input = gr.Checkbox(value=False, label="Auto Settings")
with gr.Row(visible=False) as manual_settings:
blur_radius_input = gr.Slider(minimum=0, maximum=10, value=0, step=0.5, label="Blur Radius (for smoothing)")
edge_enhance_input = gr.Checkbox(value=False, label="AI Edge Enhance")
edge_threshold_input = gr.Slider(minimum=0.1, maximum=3.0, value=1.0, step=0.1, label="Edge Detection Threshold")
color_mode_input = gr.Radio(choices=["Color", "Binary"], value="Color", label="Color Mode")
hierarchical_input = gr.Radio(choices=["Stacked", "Cutout"], value="Stacked", label="Hierarchical")
mode_input = gr.Radio(choices=["Spline", "Polygon", "None"], value="Spline", label="Mode")
filter_speckle_input = gr.Slider(minimum=1, maximum=100, value=4, step=1, label="Filter Speckle")
color_precision_input = gr.Slider(minimum=1, maximum=100, value=6, step=1, label="Color Precision")
layer_difference_input = gr.Slider(minimum=1, maximum=100, value=16, step=1, label="Layer Difference")
corner_threshold_input = gr.Slider(minimum=1, maximum=100, value=60, step=1, label="Corner Threshold")
length_threshold_input = gr.Slider(minimum=1, maximum=100, value=4.0, step=0.5, label="Length Threshold")
max_iterations_input = gr.Slider(minimum=1, maximum=100, value=10, step=1, label="Max Iterations")
splice_threshold_input = gr.Slider(minimum=1, maximum=100, value=45, step=1, label="Splice Threshold")
path_precision_input = gr.Slider(minimum=1, maximum=100, value=8, step=1, label="Path Precision")
def toggle_settings(auto_settings):
return gr.update(visible=not auto_settings)
auto_settings_input.change(toggle_settings, inputs=[auto_settings_input], outputs=manual_settings)
convert_button = gr.Button("Convert Image to SVG")
svg_output = gr.HTML(label="SVG Output")
download_output = gr.File(label="Download SVG")
convert_button.click(
fn=convert_image,
inputs=[
image_input, auto_settings_input, blur_radius_input, edge_enhance_input, edge_threshold_input,
color_mode_input, hierarchical_input, mode_input, filter_speckle_input, color_precision_input,
layer_difference_input, corner_threshold_input, length_threshold_input, max_iterations_input,
splice_threshold_input, path_precision_input
],
outputs=[svg_output, download_output]
)
iface.launch()