Files
font2pic/README.md
2026-02-06 11:56:47 +08:00

137 lines
3.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 图片转SVG工具
将图片中的黑色部分提取并转换为高保真 SVG基于 `potrace` 描边以保证准确还原。
## 功能特点
- 自动提取黑色区域Otsu 自动阈值)
- 透明通道白底合成,避免边缘污染
- `potrace` 高精度矢量化,支持孔洞
- 默认保真优先(关闭曲线优化)
- 支持圆拟合简化(近似圆轮廓可替代为圆弧)
## 安装依赖
```bash
pip install -r requirements.txt
```
### 安装 potrace必需
```bash
brew install potrace
```
### 字体转SVG依赖
用于 `font2svg.py`(字形轮廓输出):
```bash
pip install fonttools uharfbuzz
```
## 使用方法
### 基本用法
```bash
python pic2svg.py input.png
```
这将在同一目录生成 `input.svg` 文件。
### 指定输出目录
```bash
python pic2svg.py input.png --outdir svg
```
### 常用参数示例
```bash
# 使用固定阈值
python pic2svg.py input.png --threshold 128
# 保真优先(默认参数)
python pic2svg.py input.png --turdsize 0 --opttolerance 0 --unit 1
# 文件更小(可能略失真)
python pic2svg.py input.png --optimize-curves --opttolerance 0.2
# 圆拟合简化(仅当轮廓接近圆时生效)
python pic2svg.py input.png --circle-fit 0.02
# 批量转换(输入目录)
python pic2svg.py --indir images --outdir svg
```
### 字体转SVG新脚本
```bash
python font2svg.py --font path/to/font.ttf --text "Hello"
python font2svg.py --font font/XCDUANZHUANGSONGTI.ttf --text "星程紫微" --outdir svg
python font2svg.py --font path/to/font.ttf --text "Hello" --letter-spacing 20
python font2svg.py --fontdir font --text "星程紫微" --outdir svg
```
说明:单字体输出文件名根据 `--text` 自动生成;使用 `--fontdir` 时会加上字体名作为前缀。
## 参数说明
| 参数 | 说明 | 默认值 |
|------|------|--------|
| `input` | 输入图片路径(必需) | - |
| `--indir` | 输入目录(批量转换) | - |
| `--outdir` | 输出目录(自动创建,使用输入文件名.svg | - |
| `--threshold` | 固定阈值0-255未设置则使用Otsu | - |
| `--turdsize` | 抑制噪点面积阈值potrace -t | 0 |
| `--opttolerance` | 曲线优化容差potrace -O | 0.0 |
| `--unit` | 坐标量化单位potrace -u | 1 |
| `--optimize-curves` | 启用曲线优化(更小但可能略失真) | 关闭 |
| `--circle-fit` | 圆拟合误差阈值(相对半径),>0启用圆替代 | 0.0 |
### font2svg 参数说明
| 参数 | 说明 | 默认值 |
|------|------|--------|
| `--font` | 字体文件路径ttf/otf | - |
| `--text` | 文字内容 | - |
| `--outdir` | 输出目录(自动创建) | - |
| `--letter-spacing` | 字距(字体单位) | 0 |
| `--fontdir` | 字体目录遍历ttf/otf | - |
## 批量转换
```bash
python pic2svg.py --indir images --outdir output
```
## 工作原理
1. 读取图像,透明通道白底合成
2. 灰度化 + Otsu 反色二值化
3. 若启用 `--circle-fit`,先尝试圆拟合替代
4. 写入 PBM 位图
5. `potrace` 描边生成 SVG圆拟合失败时回退
## 故障排除
**细节缺失或断裂**:降低 `turdsize`,关闭 `--optimize-curves`,必要时设置更合适的 `--threshold`
**文件过大**:开启 `--optimize-curves` 或适当增大 `--opttolerance`
**边缘毛刺**:尝试调整 `--threshold`,或先对原图做轻微去噪。
**圆拟合过于粗糙**:减小 `--circle-fit` 或关闭圆拟合。
## 技术栈
- Python 3.6+
- OpenCV / NumPy
- potrace
- fonttools / uharfbuzz
## License
MIT