write code for a working image to svg converter in python
- User
write code for a working image to svg converter in python
- Assistant
write code for a working image to svg converter in python
Certainly! Below is a Python script that converts an image to an SVG file by detecting the edges in the image and creating vector paths from those edges. This script uses the opencv-python package for image processing and edge detection, and the svgwrite package to generate the SVG file.
Dependencies:
You can install these packages using pip:
pip install opencv-python svgwrite
Python Code:
import sys
import cv2
import numpy as np
import svgwrite
def image_to_svg(input_image_path, output_svg_path):
# Load the image
image = cv2.imread(input_image_path)
if image is None:
print(f"Error: Unable to open image file {input_image_path}")
sys.exit(1)
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply Gaussian Blur to reduce noise and improve edge detection
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Use Canny edge detection
edges = cv2.Canny(blurred, threshold1=50, threshold2=150, apertureSize=3)
# Find contours from the edges
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Create an SVG drawing
height, width = edges.shape
dwg = svgwrite.Drawing(output_svg_path, size=(width, height))
# Add white background to SVG
dwg.add(dwg.rect(insert=(0, 0), size=(width, height), fill='white'))
# Draw contours to SVG
for contour in contours:
# Simplify the contour to reduce the number of points
epsilon = 0.001 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
# Convert contours to lists of tuples
points = [(point[0][0], point[0][1]) for point in approx]
# Create SVG path data
if len(points) > 1:
path_data = "M " + " L ".join(f"{x},{y}" for x, y in points) + " Z"
dwg.add(dwg.path(d=path_data, fill='black', stroke='none'))
# Save SVG file
dwg.save()
print(f"SVG file saved as {output_svg_path}")
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python image_to_svg.py input_image output_svg")
sys.exit(1)
input_image_path = sys.argv[1]
output_svg_path = sys.argv[2]
image_to_svg(input_image_path, output_svg_path)
How the Code Works:
Image Loading and Preprocessing:
Edge Detection:
Finding and Approximating Contours:
cv2.approxPolyDP to simplify the contours by reducing the number of points, which makes the SVG file less complex.SVG Creation:
svgwrite.Saving the SVG File:
Usage:
Save the script to a file named image_to_svg.py and run it from the command line:
python image_to_svg.py input_image.jpg output_image.svg
Replace input_image.jpg with the path to your input image, and output_image.svg with the desired output SVG file name.
Example:
python image_to_svg.py sample.jpg output.svg
Notes:
Input Image Quality: The quality of the SVG output heavily depends on the input image. High-contrast images with clear edges produce the best results.
Edge Detection Thresholds: You can adjust the threshold1 and threshold2 parameters in the cv2.Canny function to fine-tune edge detection:
edges = cv2.Canny(blurred, threshold1=lower_threshold, threshold2=upper_threshold, apertureSize=3)
Contour Approximation Parameter: The epsilon parameter in cv2.approxPolyDP controls the approximation accuracy. Smaller values result in more points and a more detailed path. You can adjust it as needed:
epsilon = approximation_coefficient * cv2.arcLength(contour, True)
Fill and Stroke Colors: You can change the fill and stroke parameters in dwg.add to customize the SVG appearance.
Dependencies Installation:
Make sure you have Python 3 installed. Install dependencies using pip:
pip install opencv-python svgwrite
Full Example with Verbose Output and Error Handling:
import sys
import cv2
import numpy as np
import svgwrite
def image_to_svg(input_image_path, output_svg_path):
# Load the image
image = cv2.imread(input_image_path)
if image is None:
print(f"Error: Unable to open image file {input_image_path}")
sys.exit(1)
print("Image loaded successfully.")
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
print("Converted image to grayscale.")
# Apply Gaussian Blur to reduce noise and improve edge detection
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
print("Applied Gaussian blur to the image.")
# Use Canny edge detection
lower_threshold = 50
upper_threshold = 150
edges = cv2.Canny(blurred, threshold1=lower_threshold, threshold2=upper_threshold, apertureSize=3)
print(f"Performed Canny edge detection with thresholds {lower_threshold} and {upper_threshold}.")
# Find contours from the edges
contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(f"Found {len(contours)} contours in the image.")
# Create an SVG drawing
height, width = edges.shape
dwg = svgwrite.Drawing(output_svg_path, size=(width, height))
print(f"Initialized SVG drawing with width {width} and height {height}.")
# Add white background to SVG
dwg.add(dwg.rect(insert=(0, 0), size=(width, height), fill='white'))
# Draw contours to SVG
for i, contour in enumerate(contours):
# Simplify the contour to reduce the number of points
epsilon = 0.001 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
# Convert contours to lists of tuples
points = [(point[0][0], point[0][1]) for point in approx]
if len(points) > 1:
# Create SVG path data
path_data = "M " + " L ".join(f"{x},{y}" for x, y in points) + " Z"
dwg.add(dwg.path(d=path_data, fill='black', stroke='none'))
print(f"Added contour {i+1} with {len(points)} points to SVG.")
else:
print(f"Skipped contour {i+1} because it has less than 2 points.")
# Save SVG file
dwg.save()
print(f"SVG file saved as {output_svg_path}")
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python image_to_svg.py input_image output_svg")
sys.exit(1)
input_image_path = sys.argv[1]
output_svg_path = sys.argv[2]
image_to_svg(input_image_path, output_svg_path)
Conclusion:
This script provides a basic image to SVG conversion by extracting edges and converting them into vector paths. Keep in mind that for complex images or photographic content, the SVG may become very large and complex. For more sophisticated image tracing (like converting photos to scalable vector graphics with smooth gradients and colors), consider using dedicated tools like Potrace, Inkscape, or Adobe Illustrator, which offer advanced vectorization algorithms.
Let me know if you need further assistance or modifications to the script!