Vectorizing Images – Python Code Examples
This article introduces you to the basics of vectorizing images using Aspose.SVG Python library. The article walks through several Python examples demonstrating the functionality of ImageVectorization and the impact of configuration properties on the result of vectorization.
Raster Image vs. Vector Graphic
There are two main types of images: vector and raster. The choice between them depends on the specific use case. A bitmap, also known as a raster image, is a two-dimensional array that maps colors to individual pixels. Raster images are typically much larger file sizes than vector images and work well for photographs or images with color gradients. However, a significant disadvantage of raster images is the loss of quality when scaled, leading to pixelation and blurriness.
Vector graphics, on the other hand, consist of geometric shapes such as Bezier curves, splines, and lines. These shapes are determined by mathematical equations, allowing vector images to be infinitely scaled without losing quality. This makes vector graphics ideal for logos, icons, page layouts, maps, graphs, line art, and illustrations. They often result in smaller file sizes than raster images, especially for simpler projects.
Vectorizing Images
Image vectorization is the process of converting a raster image into vector graphics. This involves converting the pixel information of a raster image into a series of mathematical curves and shapes. The benefits of vector images include their scalability and typically smaller file sizes for certain types of images. However, vector images may be less effective for highly detailed images or photographs that require complex color variations and gradients.
Aspose.SVG for Python via .NET provides a robust solution for vectorizing images through the
ImageVectorization namespace. This allows users to convert various raster image formats such as JPG, PNG, BMP, TIFF, and GIF to the vector SVG file format. The vectorization process can be fine-tuned using configuration properties such as path_builder
, colors_limit
, error_threshold
, trace_smoother
, max_iterations
, stencil
, etc. which affect the quality and detail of the resulting vector graphics. This technology allows precise control of the vectorization process, ensuring high quality and scalability of vector images.
Python Example 1. Image Vectorization
To vectorize an image with Aspose.SVG Python library, you should follow a few steps:
- Create an instance of the
BezierPathBuilder class to define the path-building strategy. Here, you can set BezierPathBuilder’s properties, such as
trace_smoother
,error_threshold
, andmax_iterations
. - Create an instance of the
ImageVectorizer class. The ImageVectorizer is the main class used to convert images to vector graphics.
- Assign the
path_builder
configuration (defined earlier) to thevectorizer
object. This means the vectorizer will use the settings specified in the path_builder for path creation and optimization. - Set the
colors_limit
andline_width
properties of the of the ImageVectorizerConfiguration class.
- Assign the
- Use the vectorize() method to vectorize an image from the specified file.
- Save the vectorized image as an SVG file using the
save method on the
SVGDocument
class.
1import os
2from aspose.svg import *
3from aspose.svg.converters import *
4from aspose.svg.drawing import *
5from aspose.svg.rendering.image import *
6from aspose.svg.imagevectorization import *
7
8# Setup directories
9input_folder = "data/"
10output_folder = "output/"
11src_file = "fish.png"
12output_file = "fish-vectorized.svg"
13if not os.path.exists(output_folder):
14 os.makedirs(output_folder)
15
16# Configuration for vectorization
17path_builder = BezierPathBuilder()
18path_builder.trace_smoother = ImageTraceSmoother(3)
19path_builder.error_threshold = 10.0
20path_builder.max_iterations = 20
21
22vectorizer = ImageVectorizer()
23vectorizer.configuration.path_builder = path_builder
24vectorizer.configuration.colors_limit = 3
25vectorizer.configuration.line_width = 1.5
26
27# Vectorize an image
28with vectorizer.vectorize(os.path.join(input_folder, src_file)) as document:
29 output_file = os.path.join(output_folder, output_file)
30 document.save(output_file)
This code example allows you to vectorize a color raster image into a vector one. The vectorization options are selected in such a way as to achieve the desired result shown in figure (b). We wanted a simplified three-color image of the original. The following figure demonstrates the source image (a) and the vectorized image using the above Python code snippet (b).
Vectorization Options
You can apply custom settings to get the best result from the image vectorization. Below are some of the main settings you can control, along with their default values:
- tolerance – The value of the tolerance determines the maximum error tolerance allowed for a point to be eliminated from the trace. It must be between 0 and 4. The default value is 0.3.
- trace_smoother – This property is used to smooth the paths generated during the vectorization process. It can take a parameter (
severity
) that defines the degree of smoothing applied. - error_threshold – This property defines the maximum deviation of points to the fitted curve. By default, it is 30.
- max_iterations – defines a number of iterations for the least-squares approximation method. By default, it is 30.
- background_color – the default value is transparent white.
- colors_limit – sets the maximum number of colors used to quantize an image. The default value is 25.
- line_width – sets the line width. The value of this parameter is affected by the graphics scale. The default value is 1.
- image_size_limit – maximal dimension of an image determined by the multiplication of image width and height. The size of the image will be scaled based on this property. The default value is 1800000.
Python Example 2. Photo Vectorization
Is it possible to convert a photo in vector format to look identical to the photo?
SVG is not well suited for drawing photorealistic images. Vector pictures do not allow for natural color transitions yet. Vector graphics are the best for creating logos, illustrations, technical drawings. It is not the most suitable format for continuous-tone images with blends of color or to edit photographs. However, vectorizing photos can result in impressive artistic effects that can be interesting and useful.
In this section, we convert a photo to vector format and try to choose vectorization options so that the result looks identical to the photo:
1import os
2from aspose.svg import *
3from aspose.svg.converters import *
4from aspose.svg.drawing import *
5from aspose.svg.rendering.image import *
6from aspose.svg.imagevectorization import *
7
8# Setup directories
9input_folder = "data/"
10output_folder = "output/"
11src_file = "lioness.jpg"
12output_file = "lioness.svg"
13if not os.path.exists(output_folder):
14 os.makedirs(output_folder)
15
16# Configuration for vectorization
17path_builder = BezierPathBuilder()
18path_builder.trace_smoother = ImageTraceSmoother(1)
19path_builder.error_threshold = 30.0
20path_builder.max_iterations = 30
21
22vectorizer = ImageVectorizer()
23vectorizer.configuration.path_builder = path_builder
24vectorizer.configuration.colors_limit = 25
25vectorizer.configuration.line_width = 1.5
26
27# Vectorize a photo
28with vectorizer.vectorize(os.path.join(input_folder, src_file)) as document:
29 output_file = os.path.join(output_folder, output_file)
30 document.save(output_file)
The figure demonstrates the source photo (a), the vectorized image using the Python code snippet (b).
As mentioned above, SVG is not the most suitable format for continuous-tone images with blends of color, etc. The vectorization process uses color image quantization. All small same colored spots or pixels, we replace by geometric shapes or curves. The source photo (a) and resulting SVG file (b) you may find and view in details by following the links – lioness.jpg, lioness.svg.
License Limitations
A free evaluation version of Aspose.SVG for Python via .NET provides all the features for image vectorization except the following:
- Only 4 dominant color will be used to quantize an image.
- Only 50% of SVG Document’s nodes will be saved during serialization.
If you want to try Aspose.SVG for Python via .NET without evaluation limitations request a 30-day temporary license. For more information, please refer to How to get a Temporary License?
The figure shows the result of the photo to vector conversion without applying a license.
See Also
- In the Image Vectorization – Workflow article, you will find a description of the image vectorization process - color quantization, resizing, contour tracing, etc.
- The Image Stencil – How to Make Stencil in Python article explains how to create stencils from images using Aspose.SVG for Python via .NET API.
- You can try Image Vectorizer in real-time! This tool offers various options for preprocessing bitmaps before saving them to SVG format. You are able to interactively manage the vectorized SVG file by using controls linked with proper vectorization options.
Aspose.SVG offers a Free Online Image Vectorizer that is designed to convert bitmap images such as JPG, PNG, BMP, TIFF, and GIF into vector graphics. After conversion, all vector graphic elements are saved as SVG files. Our free vectorizer works on any platform. With this app, you can apply various options to achieve the perfect result. Save time and experience the advantages of vector graphics with our free Image Vectorizer!