将位图转为彩色矢量 svg 图片

Overview

Gitee GitHub

Color Trace

更新日期:2021 年 8 月 6 日

这是一个将位图描摹为彩色矢量 svg 图片的程序,是一个命令行工具,使用 Python 脚本实现,运行环境 Python3.8+。

效果

以一个字帖图片为例,这是 png 格式的位图(370KB):

位图

这是颜色数为 1 的 svg 转换结果,即只有黑色(32KB):

矢量图-1颜色

颜色数为 3 的 svg 转换结果(190KB):

矢量图-3颜色

📝 原理

它的原理是:

  • 先将位图图片的颜色缩减,以 png 为中转格式
  • 将图片按颜色分层
  • 将每一层颜色使用 Potrace 生成矢量 svg 图片
  • 最后将所有颜色的 svg 图片合成为一张彩色的 svg 图片

🔨 依赖

为了实现上述的功能,你需要先保证安装有:

  • ImageMagick,用于转换图像格式

  • Potrace,用于将位图转换为单一颜色矢量图

  • pngquant,用于缩减颜色(Median-Cut 算法,这是默认使用的算法)

  • pngnq,用于缩减颜色(NeuQuant 算法)

    pngnq 是可选安装,NeuQuant 算法可以生成更多颜色,如果你不去手动选择这个算法,就不需要安装 pngnq

    因为在 Windows 上安装 pngnq 还需要手动去下载 libpng13.dll,太麻烦。懒人就直接不用它了。

上述安装的意思是:将那些程序的可执行文件所在的目录添加到系统的环境变量。(如果不懂这句话的意思可以百度学习下,这个太基础,就不讲了)

Python 依赖下列库:

  • lxml

使用 pip 安装即可

👍 使用方式

本工具是 Python 脚本的形式,脚本文件在 src 文件夹中,在命令行中使用:

$ python color-trace.py -h
usage: color-trace.py [-h] -i src [src ...] [-o dest] [-d destdir] [-C N]
                      [--width ] [--height ] [-c N] [-q algorithm]
                      [-fs | -ri] [-r paletteimg] [-s] [-p size] [-D size]
                      [-S threshold] [-O tolerance] [-bg] [-v] [--version]

使用 potrace 将位图转化为彩色 svg 矢量图

optional arguments:
  -h, --help, /?        显示帮助
  -i src [src ...], --input src [src ...]
                        输入文件,支持 * 和 ? 通配符
  -o dest, --output dest
                        输出保存路径,支持 * 通配符
  -d destdir, --directory destdir
                        输出保存的文件夹
  -C N, --cores N       多进程处理的进程数 (默认使用全部核心)
  --width          输出 svg 图像宽度,例如:6.5in、 15cm、100pt,默认单位是 inch
  --height         输出 svg 图像高度,例如:6.5in、 15cm、100pt,默认单位是 inch
  -c N, --colors N      [若未使用 -p 参数,则必须指定该参数] 表示在描摹前,先缩减到多少个颜色。最多 256
                        个。0表示跳过缩减颜色 (除非你的图片已经缩减过颜色,否则不推荐0)。
  -q algorithm, --quantization algorithm
                        颜色量化算法,即缩减颜色算法: mc, as, or nq. 'mc' (Median-Cut,中切,由
                        pngquant 实现,产生较少的颜色,这是默认); 'as' (Adaptive Spatial
                        Subdivision 自适应空间细分,由 ImageMagick 实现,产生的颜色更少); 'nq'
                        (NeuQuant 神经量化, 可以生成更多的颜色,由 pnqng 实现)。 如果 --colors 0
                        则不启用量化。
  -fs, --floydsteinberg
                        启用 Floyd-Steinberg 拟色 (适用于所有量化算法或 -p/--palette).警告:
                        任何米色算法都会显著的增加输出 svg 图片的大小和复杂度
  -ri, --riemersma      启用 Rimersa 拟色 (只适用于 as 量化算法或 -p/--palette)
  -r paletteimg, --remap paletteimg
                        使用一个自定义调色板图像,用于颜色缩减 [覆盖 -c 和 -q 选项]
  -s, --stack           堆栈描摹 (若要更精确的输出,推荐用这个)
  -p size, --prescale size
                        为得到更多的细节,在描摹前,先将图片进行缩放 (默认值: 1)。例如使用 2,描摹前先预放大两倍
  -D size, --despeckle size
                        抑制斑点的大小(单位是像素) (默认值:2)
  -S threshold, --smoothcorners threshold
                        转角平滑参数:0 表示不作平滑处理,1.334 是最大。(默认值:1.0
  -O tolerance, --optimizepaths tolerance
                        贝塞尔曲线优化参数: 最小是0,最大是5(默认值:0.2)
  -bg, --background     将第一个颜色这背景色,并尽可能优化最终的 svg
  -v, --verbose         打印出运行时的细节
  --version             显示程序版本

例如:

$ python color-trace.py -i 位图.png -c 3 -o 矢量.svg
$ python color-trace.py -i 文件夹/*.png -c 3 -d 输出文件夹

🔮 背景

这个程序的初始代码

我希望将手上的一些扫描版的 PDF 书籍转为矢量格式保存,借助矢量图形的优点,如果使用适当的参数,可以得到更观看体验更好、体积更小的电子书。于是发现了 Potrace,转换的效果非常好,许多程序、项目都在使用它和它的代码,唯一的遗憾是它只支持黑白。

Potrace(TM) 是一种用于描摹位图的工具,即将位图转换为平滑、可缩放的图像。输入是位图(PBM、PGM、PPM 或 BMP 格式),输出是几种矢量文件格式之一。

典型用途是从扫描的数据(例如公司或大学徽标、手写笔记等)创建 SVG 或 PDF 文件。生成的图像是平滑的,可以以任何分辨率呈现。

Potrace 目前可以生成以下输出格式:SVG、PDF、EPS、PostScript、DXF、GeoJSON、PGM、Gimppath 和 XFig。

然后我也试用了 Adobe illustrator、Inkscape 的描摹功能,但都需要图形界面一张一张操作,不能批量化操作,不如 Potrace

毕竟发现了 Potrace 这样一个古老、优秀、应用广泛的软件,然后我就在 Github 上搜索,看看有没有人用 Python 和 Potrace 结合,做出有意思的东西。

结果,还真就找到这样一个 star 几十的 repo:由 customink 在 2012 年用 Python3.2 实现的 color_trace

看了 readme 后,怀着激动的心下载了源码,试运行,结果报错。毕竟是 2012 年用 Python3.2 写的,太古老了,Python 的许多内置函数都变了不少。

想要用的话,就只能自己修了。英文源码我是看不下去,就把里面的大部分注释和变量都替换成了方便我理解的中文翻译,这样才逐渐理解了这个程序的原理,然后进行测试、修复、优化,最终可用了。Happy!

贡献代码

由于做这个程序的第一目的是给我自己用,所以就没有考虑国际化,里面的变量名大多都是中文,甚至把命令行帮助也做成了中文。考虑到方便阅读、维护,贡献代码时请使用中文作为变量、注释的首选语言。

在写注释时,中文打字慢,许多部分我都是使用 HaujetZhao/CapsWriter 进行语音输入辅助完成的,推荐使用。

有能力的爱好者可以 fork 此 repo,翻译为英文代码。

打赏

万水千山总是情,一块几块都是情。本软件完全开源,用爱发电,如果你愿意,可以以打赏的方式支持我一下:

sponsor

这个打赏二维码图片也是由 jpg 转成了黑色的 svg 文件,只有 55KB,Nice!

😀 交流

如果有软件方面的反馈可以提交 issues,或者加入 QQ 群:1146626791

🙏 鸣谢

Owner
Haujet Zhao
Haujet Zhao
A Blender add-on to create interesting meshes using symmetry

Procedural Symmetries This Blender add-on automates the process of iteratively applying a set of reflection planes to a base mesh. The result will con

1 Dec 29, 2021
Blue noise image stippling in Processing (requires GPU)

Blue noise image stippling in Processing (requires GPU)

Mike Wong 141 Oct 09, 2022
A large-scale dataset of both raw MRI measurements and clinical MRI images

fastMRI is a collaborative research project from Facebook AI Research (FAIR) and NYU Langone Health to investigate the use of AI to make MRI scans faster. NYU Langone Health has released fully anonym

Facebook Research 907 Jan 04, 2023
Tools for making image cutouts from sets of TESS full frame images

Cutout tools for astronomical images Astrocut provides tools for making cutouts from sets of astronomical images with shared footprints. It is under a

Space Telescope Science Institute 20 Dec 16, 2022
Me cleaner - Tool for partial deblobbing of Intel ME/TXE firmware images

me_cleaner me_cleaner is a Python script able to modify an Intel ME firmware image with the final purpose of reducing its ability to interact with the

Nicola Corna 4.1k Jan 08, 2023
🛹 Turn an SVG into an STL for stencil creation purposes

svg2stl This repository provides a script which takes as input an SVG such as this one: It outputs an STL file like this one: You can also see an inte

Max Halford 3 Dec 29, 2021
Image manipulation package used for EpicBot.

Image manipulation package used for EpicBot.

Nirlep_5252_ 7 May 26, 2022
Anime2Gif - an algorithm that detects scenes in a video and generates gifs from it

Anime2Gif Anime2Gif is an algorithm that detects scenes in a video and generates gifs from it. How to use To use it, first, you'll need to install it'

1 Dec 09, 2021
Bringing vtk.js into Dash and Python

Dash VTK Dash VTK lets you integrate the vtk.js visualization pipeline directly into your Dash app. It is powered by react-vtk-js. Docs Demo Explorer

Plotly 88 Nov 29, 2022
Pixel Brush Processing Unit

Pixel Brush Processing Unit The Pixel Brush Processing Unit (PBPU for short) is a simple 4-Bit CPU I designed in Logisim while I was still in school a

Pixel Brush 2 Nov 03, 2022
Program designed to mass edit and watermark all photos in a directory

Photographer-All-In-One This is a program designed for photographers to mass edit or watermark photos (.jpg || .png) You can run this program from any

Brad Martin 2 Nov 23, 2021
Polyfoto - Create image mosaics.

Polyfoto Create image mosaics. Showcase "Before and After Science" by Brian Eno "Scott 3" by Scott Walker Installation Clone this repository to your l

Shane Drabing 149 Dec 25, 2022
Plots the graph of a function with ASCII characters.

ASCII Graph Plotter Plots the graph of a function with ASCII characters. See the change log here. Developed by InformaticFreak (c) 2021 How to use py

InformaticFreak 2 Apr 29, 2022
Blender addon to generate better building models from satellite imagery.

Blender addon to generate better building models from satellite imagery.

Ivan Ereshchenko 24 Apr 14, 2022
Herramienta Para Snipear Nitros Y Participar En Sorteos Automaticamente

Crips Nitro Sniper Discord Nitro Sniper Y Auto Participar En Sorteos ⚠️ Es Bastante Rapido Y Efectivo Hecho En Python Como Usar ( Python ) : python -m

1 Oct 27, 2021
A Python3 library to generate dynamic SVGs

The Python library for generating dynamic SVGs using Python3

1 Dec 23, 2021
With this simple py script you will be able to get all the .png from a folder and generate a yml for Oraxen

Oraxen-item-to-yml With this simple py script you will be able to get all the .png from a folder and generate a yml for Oraxen How to use Install the

Akex 1 Dec 29, 2021
Visage Differentiation is a GUI application for outlining and labeling the visages in an image.

Visage Differentiation Visage Differentiation is a GUI application for outlining and labeling the visages in an image. The main functionality is provi

Grant Randa 0 Jan 13, 2022
image-processing exercises.

image_processing Assignment 21 Checkered Board Create a chess table using numpy and opencv. view: Color Correction Reverse black and white colors with

Benyamin Zojaji 25 Dec 15, 2022