Batch Vectorize Images in Python

Quick Answer: To batch vectorize images in Python, iterate through an input folder, filter raster formats such as PNG, JPG, BMP, TIFF, and GIF, call ImageVectorizer.vectorize() for each file, and save each returned SVG document to an output folder. Wrap each file conversion in try/except so one bad image does not stop the whole batch.

Batch Image Vectorization Workflow

Batch vectorization is useful when you need SVG versions of many icons, logos, scanned drawings, diagrams, or prepared raster assets. The workflow is the same as single-image vectorization, but the code also manages folders, file names, supported extensions, and failures.

Use this page when the question is “How do I process a folder of images?” For format-specific examples and visual results, see Vectorize Images in Python. For tuning output quality, see Image Vectorization Options in Python.

Supported Input Formats

The batch function below accepts common raster formats supported by the image vectorization workflow.

Input extensionTypical sourceOutput
.pngLogos, icons, transparent graphics, flat artwork.svg
.jpg, .jpegPhotos, previews, complex raster images.svg
.bmpSimple bitmap artwork.svg
.tif, .tiffScans, publishing images, image-processing output.svg
.gifLimited-color raster graphics.svg

Create a Reusable Batch Vectorizer

The following example builds a reusable batch function. It creates one ImageVectorizer configuration, scans the input folder, vectorizes each supported file, saves each result as SVG, and logs failed files without stopping the batch.

 1import os
 2from aspose.svg.imagevectorization import ImageVectorizer, ImageTraceSmoother, BezierPathBuilder
 3
 4SUPPORTED_EXTENSIONS = (".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".gif")
 5
 6
 7def create_vectorizer(colors_limit=8, smoothing=2, error_threshold=12.0):
 8    path_builder = BezierPathBuilder()
 9    path_builder.trace_smoother = ImageTraceSmoother(smoothing)
10    path_builder.error_threshold = error_threshold
11    path_builder.max_iterations = 20
12
13    vectorizer = ImageVectorizer()
14    vectorizer.configuration.path_builder = path_builder
15    vectorizer.configuration.colors_limit = colors_limit
16    vectorizer.configuration.line_width = 1.0
17    return vectorizer
18
19
20def batch_vectorize_images(input_folder, output_folder, vectorizer=None):
21    os.makedirs(output_folder, exist_ok=True)
22    vectorizer = vectorizer or create_vectorizer()
23    converted = []
24    failed = []
25
26    for file_name in os.listdir(input_folder):
27        if not file_name.lower().endswith(SUPPORTED_EXTENSIONS):
28            continue
29
30        input_path = os.path.join(input_folder, file_name)
31        output_name = os.path.splitext(file_name)[0] + ".svg"
32        output_path = os.path.join(output_folder, output_name)
33
34        try:
35            with vectorizer.vectorize(input_path) as document:
36                document.save(output_path)
37            converted.append(output_path)
38        except Exception as exc:
39            failed.append((input_path, str(exc)))
40
41    return converted, failed
42
43input_folder = "data/images/"
44output_folder = "output/svg/"
45
46vectorizer = create_vectorizer(colors_limit=8, smoothing=2, error_threshold=12.0)
47converted, failed = batch_vectorize_images(input_folder, output_folder, vectorizer)
48
49print(f"Converted files: {len(converted)}")
50print(f"Failed files: {len(failed)}")
51for input_path, error in failed:
52    print(f"Failed: {input_path} - {error}")

The function creates one SVG file for each supported raster image. For example, logo.png becomes logo.svg, and photo.jpg becomes photo.svg in the output folder.

The code performs five operations:

  1. Defines supported raster extensions for PNG, JPG, BMP, TIFF, and GIF files.
  2. Creates one reusable ImageVectorizer configuration with path smoothing, color limit, line width, and curve-fitting settings.
  3. Iterates through the input folder and skips files with unsupported extensions.
  4. Vectorizes each supported image and saves the result with the same base name and an .svg extension.
  5. Stores failed files and error messages so the batch can finish even when one input image cannot be processed.

Reuse the Function with Different Settings

For mixed assets, use different vectorizer settings for different folders instead of forcing one configuration onto every image. Logos usually need fewer colors and cleaner contours, while detailed JPG files often need more colors and a larger tolerance for simplification.

1# Batch vectorize flat logos and icons
2logo_vectorizer = create_vectorizer(colors_limit=6, smoothing=2, error_threshold=8.0)
3batch_vectorize_images("data/logos/", "output/logos-svg/", logo_vectorizer)
4
5# Batch vectorize detailed raster images
6photo_vectorizer = create_vectorizer(colors_limit=24, smoothing=1, error_threshold=25.0)
7batch_vectorize_images("data/photos/", "output/photos-svg/", photo_vectorizer)

This pattern keeps the folder loop reusable while allowing each asset group to use settings that match its source images.

Handle Failed Files Safely

A production batch should continue after a bad input file, unsupported file, locked file, or corrupted image. The example stores failed file paths and exception messages in failed, then prints them after the batch finishes. In a real application, you can write the failures to a log file or retry them with simpler settings.

If a folder contains subfolders, replace os.listdir() with os.walk() and create matching output folders before saving each SVG.

Common Mistakes and Fixes

ProblemLikely causeFix
No images are processedThe input folder is wrong or file extensions are not includedPrint input_folder and check SUPPORTED_EXTENSIONS
Output SVG files overwrite each otherDifferent input files share the same base namePreserve subfolders or add a suffix to generated SVG file names
One bad image stops the batchExceptions are not handled per fileKeep try/except inside the loop and log failed file names
Generated SVG files are too largeSource images are too detailed or settings preserve too much detailReduce image size, lower colors_limit, or increase smoothing
Small details disappearSimplification is too aggressiveLower smoothing, reduce error_threshold, or use a higher color limit
Batch results look inconsistentOne configuration is used for very different image typesSplit source images into groups and use separate vectorizer settings

FAQ

How do I batch vectorize images in Python?

Loop through an input folder, filter supported raster extensions, call ImageVectorizer.vectorize() for each file, and save every returned document as .svg.

Can I batch vectorize PNG and JPG files together?

Yes. Use one extension filter that includes .png, .jpg, and .jpeg, or separate the files into folders if they need different vectorization settings.

Should I stop the batch when one file fails?

Usually no. Catch exceptions per file, log the failed file names, and continue processing the rest of the folder.

Can I use different settings for different folders?

Yes. Create one vectorizer configuration for logos, another for photos or scans, and pass the appropriate vectorizer to the reusable batch function.

Can I batch vectorize images in subfolders?

Yes. Use recursive traversal with os.walk() and create matching output folders before saving the generated SVG files.

Related Articles