## File: README.md

> **相关项目**：
>
> - [TRIO](https://pytrio.cn/home)：一个新型的AI计算平台（Tinker Like），让模型训练者无需维护复杂GPU基础设施，在个人电脑就可以轻松做llm sft/rl训练，训推均按token计费而非GPU时，支持弹性扩展，同时开20个实验不再困难。




# 目录

- [最近更新](#-最近更新)
- [项目简介](#-项目简介)
- [社区](#-社区)
- [准备工作](#-准备工作)
- [Demo启动](#-运行-gradio-demo)
- [Python推理](#-python-推理)
- [API服务部署](#️-部署-api-服务)
- [Docker部署](#-docker-部署)
- [联系我们](#-联系我们)
- [FAQ](#faq)
- [感谢支持](#-感谢支持)
- [License](#-lincese)
- [引用](#-引用)



# 🤩 最近更新

- 在线体验： [](https://huggingface.co/spaces/TheEeeeLin/HivisionIDPhotos)、[![][modelscope-shield]][modelscope-link]、[![][modelers-shield]][modelers-link]、[![][compshare-shield]][compshare-link]

- 2024.11.20: Gradio Demo增加**打印排版**选项卡，支持六寸、五寸、A4、3R、4R五种排版尺寸
- 2024.11.16: API接口增加美颜参数
- 2024.09.25: 增加**五寸相纸**和**JPEG下载**选项｜默认照片下载支持300DPI
- 2024.09.24: API接口增加base64图像传入选项 | Gradio Demo增加**排版照裁剪线**功能
- 2024.09.22: Gradio Demo增加**野兽模式**，可设置内存加载策略 | API接口增加**dpi、face_alignment**参数
- 2024.09.18: Gradio Demo增加**分享模版照**功能、增加**美式证件照**背景选项
- 2024.09.17: Gradio Demo增加**自定义底色-HEX输入**功能 | **（社区贡献）C++版本** - [HivisionIDPhotos-cpp](https://github.com/zjkhahah/HivisionIDPhotos-cpp) 贡献 by [zjkhahah](https://github.com/zjkhahah)
- 2024.09.16: Gradio Demo增加**人脸旋转对齐**功能，自定义尺寸输入支持**毫米**单位



# 项目简介

> 🚀 谢谢你对我们的工作感兴趣。您可能还想查看我们在图像领域的其他成果，欢迎来信:zeyi.lin@swanhub.co.

HivisionIDPhoto 旨在开发一种实用、系统性的证件照智能制作算法。

它利用一套完善的AI模型工作流程，实现对多种用户拍照场景的识别、抠图与证件照生成。

**HivisionIDPhoto 可以做到：**

1. 轻量级抠图（纯离线，仅需 **CPU** 即可快速推理）
2. 根据不同尺寸规格生成不同的标准证件照、六寸排版照
3. 支持 纯离线 或 端云 推理
4. 美颜
5. 智能换正装（waiting）



---

如果 HivisionIDPhoto 对你有帮助，请 star 这个 repo 或推荐给你的朋友，解决证件照应急制作问题！



# 🏠 社区

我们分享了一些由社区构建的HivisionIDPhotos的有趣应用和扩展：

| [HivisionIDPhotos-ComfyUI][community-hivision-comfyui] | [HivisionIDPhotos-wechat-weapp][community-hivision-wechat] |
| :----------------------------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------: |
| [  ](https://github.com/AIFSH/HivisionIDPhotos-ComfyUI)  | [  ](https://github.com/no1xuan/HivisionIDPhotos-wechat-weapp)  |
|ComfyUI证件照处理工作流 | 证件照微信小程序（JAVA后端+原生前端） |

| [HivisionIDPhotos-Uniapp][community-hivision-uniapp] | [HivisionIDPhotos-web](https://github.com/jkm199/HivisionIDPhotos-web)|
| :------------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------: |
| [  ](https://github.com/soulerror/HivisionIDPhotos-Uniapp)  | [  ](https://github.com/jkm199/HivisionIDPhotos-web)  |
| 证件照微信小程序（uniapp）| 证件照应用网页版 |


- [HivisionIDPhotos-cpp](https://github.com/zjkhahah/HivisionIDPhotos-cpp): HivisionIDphotos C++版本，由 [zjkhahah](https://github.com/zjkhahah) 构建
- [ai-idphoto](https://github.com/wmlcjj/ai-idphoto): [HivisionIDPhotos-wechat-weapp](https://github.com/no1xuan/HivisionIDPhotos-wechat-weapp) 的uniapp多端兼容版，由 [wmlcjj](https://github.com/wmlcjj) 贡献
- [HivisionIDPhotos-uniapp-WeChat-gpto1](https://github.com/jkm199/HivisionIDPhotos-uniapp-WeChat-gpto1/): 由gpt-o1辅助完成开发的证件照微信小程序，由 [jkm199](https://github.com/jkm199) 贡献
- [HivisionIDPhotos-windows-GUI](https://github.com/zhaoyun0071/HivisionIDPhotos-windows-GUI)：Windows客户端应用，由 [zhaoyun0071](https://github.com/zhaoyun0071) 构建
- [HivisionIDPhotos-NAS](https://github.com/ONG-Leo/HivisionIDPhotos-NAS): 群晖NAS部署中文教程，由 [ONG-Leo](https://github.com/ONG-Leo) 贡献




# 🔧 准备工作

环境安装与依赖：
- Python >= 3.7（项目主要测试在 python 3.10）
- OS: Linux, Windows, MacOS

## 1. 克隆项目

```bash
git clone https://github.com/Zeyi-Lin/HivisionIDPhotos.git
cd  HivisionIDPhotos
```

## 2. 安装依赖环境

> 建议 conda 创建一个 python3.10 虚拟环境后，执行以下命令

```bash
pip install -r requirements.txt
pip install -r requirements-app.txt
```

## 3. 下载人像抠图模型权重文件

**方式一：脚本下载**

```bash
python scripts/download_model.py --models all
# 如需指定下载某个模型
# python scripts/download_model.py --models modnet_photographic_portrait_matting
```

**方式二：直接下载**

模型均存到项目的`hivision/creator/weights`目录下：

| 人像抠图模型 | 介绍 | 下载 |
| -- | -- | -- |
| MODNet | [MODNet](https://github.com/ZHKKKe/MODNet)官方权重 | [下载](https://github.com/Zeyi-Lin/HivisionIDPhotos/releases/download/pretrained-model/modnet_photographic_portrait_matting.onnx)(24.7MB)|
| hivision_modnet | 对纯色换底适配性更好的抠图模型 | [下载](https://github.com/Zeyi-Lin/HivisionIDPhotos/releases/download/pretrained-model/hivision_modnet.onnx)(24.7MB) |
| rmbg-1.4 | [BRIA AI](https://huggingface.co/briaai/RMBG-1.4) 开源的抠图模型 | [下载](https://huggingface.co/briaai/RMBG-1.4/resolve/main/onnx/model.onnx?download=true)(176.2MB)后重命名为`rmbg-1.4.onnx` |
| birefnet-v1-lite | [ZhengPeng7](https://github.com/ZhengPeng7/BiRefNet) 开源的抠图模型，拥有最好的分割精度 | [下载](https://github.com/ZhengPeng7/BiRefNet/releases/download/v1/BiRefNet-general-bb_swin_v1_tiny-epoch_232.onnx)(224MB)后重命名为`birefnet-v1-lite.onnx` |

> 如果下载网速不顺利：前往[SwanHub](https://swanhub.co/ZeYiLin/HivisionIDPhotos_models/tree/main)下载。


## 4. 人脸检测模型配置（可选）

| 拓展人脸检测模型 | 介绍 | 使用文档 |
| -- | -- | -- |
| MTCNN | **离线**人脸检测模型，高性能CPU推理（毫秒级），为默认模型，检测精度较低 | Clone此项目后直接使用 |
| RetinaFace | **离线**人脸检测模型，CPU推理速度中等（秒级），精度较高| [下载](https://github.com/Zeyi-Lin/HivisionIDPhotos/releases/download/pretrained-model/retinaface-resnet50.onnx)后放到`hivision/creator/retinaface/weights`目录下 |
| Face++ | 旷视推出的在线人脸检测API，检测精度较高，[官方文档](https://console.faceplusplus.com.cn/documents/4888373) | [使用文档](docs/face++_CN.md)|

## 5. 性能参考

> 测试环境为Mac M1 Max 64GB，非GPU加速，测试图片分辨率为 512x715(1) 与 764×1146(2)。

| 模型组合 | 内存占用 | 推理时长(1) | 推理时长(2) |
| -- | -- | -- | -- |
| MODNet + mtcnn | 410MB | 0.207s | 0.246s |
| MODNet + retinaface | 405MB | 0.571s | 0.971s |
| birefnet-v1-lite + retinaface | 6.20GB | 7.063s | 7.128s |

## 6. GPU推理加速（可选）

在当前版本，可被英伟达GPU加速的模型为`birefnet-v1-lite`，并请确保你有16GB左右的显存。

如需使用英伟达GPU加速推理，在确保你已经安装[CUDA](https://developer.nvidia.com/cuda-downloads)与[cuDNN](https://developer.nvidia.com/cudnn)后，根据[onnxruntime-gpu文档](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#cuda-12x)找到对应的`onnxruntime-gpu`版本安装，以及根据[pytorch官网](https://pytorch.org/get-started/locally/)找到对应的`torch`版本安装。

```bash
# 假如你的电脑安装的是CUDA 12.x, cuDNN 8
# 安装torch是可选的，如果你始终配置不好cuDNN，那么试试安装torch
pip install onnxruntime-gpu==1.18.0
pip install torch --index-url https://download.pytorch.org/whl/cu121
```

完成安装后，调用`birefnet-v1-lite`模型即可利用GPU加速推理。

> TIPS: CUDA 支持向下兼容。比如你的 CUDA 版本为 12.6，`torch` 官方目前支持的最高版本为 12.4（<12.6），`torch`仍可以正常使用CUDA。



# ⚡️ 运行 Gradio Demo

```bash
python app.py
```

运行程序将生成一个本地 Web 页面，在页面中可完成证件照的操作与交互。





# 🚀 Python 推理

核心参数：

- `-i`: 输入图像路径
- `-o`: 保存图像路径
- `-t`: 推理类型，有idphoto、human_matting、add_background、generate_layout_photos可选
- `--matting_model`: 人像抠图模型权重选择
- `--face_detect_model`: 人脸检测模型选择

更多参数可通过`python inference.py --help`查看

## 1. 证件照制作

输入 1 张照片，获得 1 张标准证件照和 1 张高清证件照的 4 通道透明 png

```python
python inference.py -i demo/images/test0.jpg -o ./idphoto.png --height 413 --width 295
```

## 2. 人像抠图

输入 1 张照片，获得 1张 4 通道透明 png

```python
python inference.py -t human_matting -i demo/images/test0.jpg -o ./idphoto_matting.png --matting_model hivision_modnet
```

## 3. 透明图增加底色

输入 1 张 4 通道透明 png，获得 1 张增加了底色的 3通道图像

```python
python inference.py -t add_background -i ./idphoto.png -o ./idphoto_ab.jpg  -c 4f83ce -k 30 -r 1
```

## 4. 得到六寸排版照

输入 1 张 3 通道照片，获得 1 张六寸排版照

```python
python inference.py -t generate_layout_photos -i ./idphoto_ab.jpg -o ./idphoto_layout.jpg  --height 413 --width 295 -k 200
```

## 5. 证件照裁剪

输入 1 张 4 通道照片（抠图好的图像），获得 1 张标准证件照和 1 张高清证件照的 4 通道透明 png

```python
python inference.py -t idphoto_crop -i ./idphoto_matting.png -o ./idphoto_crop.png --height 413 --width 295
```




# ⚡️ 部署 API 服务

## 启动后端

```
python deploy_api.py
```

## 请求 API 服务

详细请求方式请参考 [API 文档](docs/api_CN.md)，包含以下请求示例：
- [cURL](docs/api_CN.md#curl-请求示例)
- [Python](docs/api_CN.md#python-请求示例)



# 🐳 Docker 部署

## 1. 拉取或构建镜像

> 以下方式三选一

**方式一：拉取最新镜像：**

```bash
docker pull linzeyi/hivision_idphotos
```

**方式二：Dockrfile 直接构建镜像：**

在确保将至少一个[抠图模型权重文件](#3-下载权重文件)放到`hivision/creator/weights`下后，在项目根目录执行：

```bash
docker build -t linzeyi/hivision_idphotos .
```

**方式三：Docker compose 构建：**

在确保将至少一个[抠图模型权重文件](#3-下载权重文件)放到`hivision/creator/weights`下后，在项目根目录下执行：

```bash
docker compose build
```

## 2. 运行服务

**启动 Gradio Demo 服务**

运行下面的命令，在你的本地访问 [http://127.0.0.1:7860](http://127.0.0.1:7860/) 即可使用。

```bash
docker run -d -p 7860:7860 linzeyi/hivision_idphotos
```

**启动 API 后端服务**

```bash
docker run -d -p 8080:8080 linzeyi/hivision_idphotos python3 deploy_api.py
```

**两个服务同时启动**

```bash
docker compose up -d
```

## 环境变量

本项目提供了一些额外的配置项，使用环境变量进行设置：

| 环境变量 | 类型	| 描述 | 示例 |
|--|--|--|--|
| FACE_PLUS_API_KEY	 | 可选	| 这是你在 Face++ 控制台申请的 API 密钥	 | `7-fZStDJ····` |
| FACE_PLUS_API_SECRET	 | 可选	| Face++ API密钥对应的Secret | `VTee824E····` |
| RUN_MODE | 可选 | 运行模式，可选值为`beast`(野兽模式)。野兽模式下人脸检测和抠图模型将不释放内存，从而获得更快的二次推理速度。建议内存16GB以上尝试。 | `beast` |
| DEFAULT_LANG | 可选 | Gradio Demo启动时的默认语言| `en` |

docker使用环境变量示例：
```bash
docker run  -d -p 7860:7860 \
    -e FACE_PLUS_API_KEY=7-fZStDJ···· \
    -e FACE_PLUS_API_SECRET=VTee824E···· \
    -e RUN_MODE=beast \
    -e DEFAULT_LANG=en \
    linzeyi/hivision_idphotos  
```



# FAQ

## 1. 如何修改预设尺寸和颜色？

- 尺寸：修改[size_list_CN.csv](demo/assets/size_list_CN.csv)后再次运行 `app.py` 即可，其中第一列为尺寸名，第二列为高度，第三列为宽度。
- 颜色：修改[color_list_CN.csv](demo/assets/color_list_CN.csv)后再次运行 `app.py` 即可，其中第一列为颜色名，第二列为Hex值。

## 2. 如何修改水印字体？

1. 将字体文件放到`hivision/plugin/font`文件夹下
2. 修改`hivision/plugin/watermark.py`的`font_file`参数值为字体文件名

## 3. 如何添加社交媒体模板照？

1. 将模板图片放到`hivision/plugin/template/assets`文件夹下。模板图片是一个4通道的透明png。
2. 在`hivision/plugin/template/assets/template_config.json`文件中添加最新的模板信息，其中`width`为模板图宽度(px)，`height`为模板图高度(px)，`anchor_points`为模板中透明区域的四个角的坐标(px)；`rotation`为透明区域相对于垂直方向的旋转角度，>0为逆时针，<0为顺时针。
3. 在`demo/processor.py`的`_generate_image_template`函数中的`TEMPLATE_NAME_LIST`变量添加最新的模板名



## 4. 如何修改Gradio Demo的顶部导航栏？

- 修改`demo/assets/title.md`

## 5. 如何添加/修改「打印排版」中的尺寸？

- 修改`demo/locales.py`中的`print_switch`字典，添加/修改新的尺寸名称和尺寸参数，然后重新运行`python app.py`



# 📧 联系我们

如果您有任何问题，请发邮件至 zeyi.lin@swanhub.co



# 🙏 感谢支持

[](https://github.com/Zeyi-Lin/HivisionIDPhotos/stargazers)

[](https://github.com/Zeyi-Lin/HivisionIDPhotos/network/members)

[](https://star-history.com/#Zeyi-Lin/HivisionIDPhotos&Date)

贡献者们：

<a href="https://github.com/Zeyi-Lin/HivisionIDPhotos/graphs/contributors">
  
</a>

[Zeyi-Lin](https://github.com/Zeyi-Lin)、[SAKURA-CAT](https://github.com/SAKURA-CAT)、[Feudalman](https://github.com/Feudalman)、[swpfY](https://github.com/swpfY)、[Kaikaikaifang](https://github.com/Kaikaikaifang)、[ShaohonChen](https://github.com/ShaohonChen)、[KashiwaByte](https://github.com/KashiwaByte)



# 📜 Lincese

This repository is licensed under the [Apache-2.0 License](LICENSE).



# 📚 引用

如果您在研究或项目中使用了HivisionIDPhotos，请考虑引用我们的工作。您可以使用以下BibTeX条目：

```bibtex
@misc{hivisionidphotos,
      title={{HivisionIDPhotos: A Lightweight and Efficient AI ID Photos Tool}},
      author={Zeyi Lin and SwanLab Team},
      year={2024},
      publisher={GitHub},
      url = {\url{https://github.com/Zeyi-Lin/HivisionIDPhotos}},
}
```




[github-stars-shield]: https://img.shields.io/github/stars/zeyi-lin/hivisionidphotos?color=ffcb47&labelColor=black&style=flat-square
[github-stars-link]: https://github.com/zeyi-lin/hivisionidphotos/stargazers

[swanhub-demo-shield]: https://swanhub.co/git/repo/SwanHub%2FAuto-README/file/preview?ref=main&path=swanhub.svg
[swanhub-demo-link]: https://swanhub.co/ZeYiLin/HivisionIDPhotos/demo

[spaces-shield]: https://img.shields.io/badge/🤗-Open%20in%20Spaces-blue
[spaces-link]: https://huggingface.co/spaces/TheEeeeLin/HivisionIDPhotos


[wechat-shield]: https://img.shields.io/badge/WeChat-微信-4cb55e
[wechat-link]: https://docs.qq.com/doc/DUkpBdk90eWZFS2JW


[release-shield]: https://img.shields.io/github/v/release/zeyi-lin/hivisionidphotos?color=369eff&labelColor=black&logo=github&style=flat-square
[release-link]: https://github.com/zeyi-lin/hivisionidphotos/releases

[license-shield]: https://img.shields.io/badge/license-apache%202.0-white?labelColor=black&style=flat-square
[license-link]: https://github.com/Zeyi-Lin/HivisionIDPhotos/blob/master/LICENSE

[github-issues-shield]: https://img.shields.io/github/issues/zeyi-lin/hivisionidphotos?color=ff80eb&labelColor=black&style=flat-square
[github-issues-link]: https://github.com/zeyi-lin/hivisionidphotos/issues

[dockerhub-shield]: https://img.shields.io/docker/v/linzeyi/hivision_idphotos?color=369eff&label=docker&labelColor=black&logoColor=white&style=flat-square
[dockerhub-link]: https://hub.docker.com/r/linzeyi/hivision_idphotos/tags

[trendshift-shield]: https://trendshift.io/api/badge/repositories/11622
[trendshift-link]: https://trendshift.io/repositories/11622

[hellogithub-shield]: https://abroad.hellogithub.com/v1/widgets/recommend.svg?rid=8ea1457289fb4062ba661e5299e733d6&claim_uid=Oh5UaGjfrblg0yZ
[hellogithub-link]: https://hellogithub.com/repository/8ea1457289fb4062ba661e5299e733d6

[github-contributors-shield]: https://img.shields.io/github/contributors/zeyi-lin/hivisionidphotos?color=c4f042&labelColor=black&style=flat-square
[github-contributors-link]: https://github.com/zeyi-lin/hivisionidphotos/graphs/contributors

[github-forks-shield]: https://img.shields.io/github/forks/zeyi-lin/hivisionidphotos?color=8ae8ff&labelColor=black&style=flat-square
[github-forks-link]: https://github.com/zeyi-lin/hivisionidphotos/network/members

[modelscope-shield]: https://img.shields.io/badge/Demo_on_ModelScope-purple?logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjIzIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KCiA8Zz4KICA8dGl0bGU+TGF5ZXIgMTwvdGl0bGU+CiAgPHBhdGggaWQ9InN2Z18xNCIgZmlsbD0iIzYyNGFmZiIgZD0ibTAsODkuODRsMjUuNjUsMGwwLDI1LjY0OTk5bC0yNS42NSwwbDAsLTI1LjY0OTk5eiIvPgogIDxwYXRoIGlkPSJzdmdfMTUiIGZpbGw9IiM2MjRhZmYiIGQ9Im05OS4xNCwxMTUuNDlsMjUuNjUsMGwwLDI1LjY1bC0yNS42NSwwbDAsLTI1LjY1eiIvPgogIDxwYXRoIGlkPSJzdmdfMTYiIGZpbGw9IiM2MjRhZmYiIGQ9Im0xNzYuMDksMTQxLjE0bC0yNS42NDk5OSwwbDAsMjIuMTlsNDcuODQsMGwwLC00Ny44NGwtMjIuMTksMGwwLDI1LjY1eiIvPgogIDxwYXRoIGlkPSJzdmdfMTciIGZpbGw9IiMzNmNmZDEiIGQ9Im0xMjQuNzksODkuODRsMjUuNjUsMGwwLDI1LjY0OTk5bC0yNS42NSwwbDAsLTI1LjY0OTk5eiIvPgogIDxwYXRoIGlkPSJzdmdfMTgiIGZpbGw9IiMzNmNmZDEiIGQ9Im0wLDY0LjE5bDI1LjY1LDBsMCwyNS42NWwtMjUuNjUsMGwwLC0yNS42NXoiLz4KICA8cGF0aCBpZD0ic3ZnXzE5IiBmaWxsPSIjNjI0YWZmIiBkPSJtMTk4LjI4LDg5Ljg0bDI1LjY0O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iIGZpbGw9IiNERTA0MjkiLz4KPHBhdGggZD0iTTYwLjg3OTkgMzEuNTU3Nkg0NC42OTkyVjQ3LjMzNjNINjAuODc5OVYzMS41NTc2WiIgZmlsbD0iI0RFMDQyOSIvPgo8cGF0aCBkPSJNNzkuNjIwMSAzMS41NTc2SDYzLjQzOTVWNDcuMzM2M0g3OS42MjAxVjMxLjU1NzZaIiBmaWxsPSIjREUwNDI5Ii8+CjxwYXRoIGQ9Ik0xMTUuODI1IDMxLjU1NzZIOTkuNjQ0NVY0Ny4zMzYzSDExNS44MjVWMzEuNTU3NloiIGZpbGw9IiNERTA0MjkiLz4KPHBhdGggZD0iTTcwLjI1NDkgNDcuMzM1OUg1NC4wNzQyVjYzLjExNDdINzAuMjU0OVY0Ny4zMzU5WiIgZmlsbD0iI0RFMDQyOSIvPgo8L3N2Zz4=&labelColor=white
[modelers-link]: https://modelers.cn/spaces/SwanLab/HivisionIDPhotos

[compshare-shield]: https://www-s.ucloud.cn/2025/02/dbef8b07ea3d316006d9c22765c3cd53_1740104342584.svg
[compshare-link]: https://www.compshare.cn/images-detail?ImageID=compshareImage-17jacgm4ju16&ytag=HG_GPU_HivisionIDPhotos

[atomgit-shield]: https://atomgit.com/ZeYiLin/HivisionIDPhotos/star/badge.svg
[atomgit-link]: https://atomgit.com/ZeYiLin/HivisionIDPhotos


[community-hivision-comfyui]: https://github.com/AIFSH/HivisionIDPhotos-ComfyUI
[community-hivision-wechat]: https://github.com/no1xuan/HivisionIDPhotos-wechat-weapp
[community-hivision-uniapp]: https://github.com/soulerror/HivisionIDPhotos-Uniapp
[community-hivision-cpp]: https://github.com/zjkhahah/HivisionIDPhotos-cpp
[community-hivision-windows-gui]: https://github.com/zhaoyun0071/HivisionIDPhotos-windows-GUI
[community-hivision-nas]: https://github.com/ONG-Leo/HivisionIDPhotos-NAS

---

## File: docs/api_CN.md

# API Docs

[English](api_EN.md) / 中文


## 目录

- [开始之前：开启后端服务](#开始之前开启后端服务)
- [接口功能说明](#接口功能说明)
  - [1.生成证件照(底透明)](#1生成证件照底透明)
  - [2.添加背景色](#2添加背景色)
  - [3.生成六寸排版照](#3生成六寸排版照)
  - [4.人像抠图](#4人像抠图)
  - [5.图像加水印](#5图像加水印)
  - [6.设置图像KB大小](#6设置图像KB大小)
  - [7.证件照裁切](#7证件照裁切)
- [cURL 请求示例](#curl-请求示例)
- [Python 请求示例](#python-请求示例)

## 开始之前：开启后端服务

在请求 API 之前，请先运行后端服务

```bash
python deploy_api.py
```



## 接口功能说明

### 1.生成证件照(底透明)

接口名：`idphoto`

`生成证件照`接口的逻辑是发送一张 RGB 图像，输出一张标准证件照和一张高清证件照：

- **高清证件照**：根据`size`的宽高比例制作的证件照，文件名为`output_image_dir`增加`_hd`后缀
- **标准证件照**：尺寸等于`size`，由高清证件照缩放而来，文件名为`output_image_dir`

需要注意的是，生成的两张照片都是透明的（RGBA 四通道图像），要生成完整的证件照，还需要下面的`添加背景色`接口。

> 问：为什么这么设计？  
> 答：因为在实际产品中，经常用户会频繁切换底色预览效果，直接给透明底图像，由前端 js 代码合成颜色是更好体验的做法。

**请求参数：**

| 参数名 | 类型 | 必填 | 说明 |
| :--- | :--- | :--- | :--- |
| input_image | file | 和`input_image_base64`二选一 | 传入的图像文件，图像文件为需为RGB三通道图像。 |
| input_image_base64 | str | 和`input_image`二选一 | 传入的图像文件的base64编码，图像文件为需为RGB三通道图像。 |
| height | int | 否 | 标准证件照高度，默认为`413` |
| width | int | 否 | 标准证件照宽度，默认为`295` |
| human_matting_model | str | 否 | 人像分割模型，默认为`modnet_photographic_portrait_matting`。可选值为`modnet_photographic_portrait_matting`、`hivision_modnet`、`rmbg-1.4`、`birefnet-v1-lite` |
| face_detect_model | str | 否 | 人脸检测模型，默认为`mtcnn`。可选值为`mtcnn`、`face_plusplus`、`retinaface-resnet50` |
| hd | bool | 否 | 是否生成高清证件照，默认为`true` |
| dpi | int | 否 | 图像分辨率，默认为`300` |
| face_alignment | bool | 否 | 是否进行人脸对齐，默认为`true` |
| head_measure_ratio | float | 否 | 面部面积与照片面积的比例，默认为`0.2` |
| head_height_ratio | float | 否 | 面部中心与照片顶部的高度比例，默认为`0.45` |
| top_distance_max | float | 否 | 头部与照片顶部距离的比例最大值，默认为`0.12` |
| top_distance_min | float | 否 | 头部与照片顶部距离的比例最小值，默认为`0.1` |
| brightness_strength | float | 否 | 亮度调整强度，默认为`0` |
| contrast_strength | float | 否 | 对比度调整强度，默认为`0` |
| sharpen_strength | float | 否 | 锐化调整强度，默认为`0` |
| saturation_strength | float | 否 | 饱和度调整强度，默认为`0` |

**返回参数：**

| 参数名 | 类型 | 说明 |
| :--- | :--- | :--- |
| status | int | 状态码，`true`表示成功 |
| image_base64_standard | str | 标准证件照的base64编码 |
| image_base64_hd | str | 高清证件照的base64编码。如`hd`参数为`false`，则不返回该参数 |



### 2.添加背景色

接口名：`add_background`

`添加背景色`接口的逻辑是接收一张 RGBA 图像（透明图），根据`color`添加背景色，合成一张 JPG 图像。

**请求参数：**

| 参数名 | 类型 | 必填 | 说明 |
| :--- | :--- | :--- | :--- |
| input_image | file | 和`input_image_base64`二选一 | 传入的图像文件，图像文件为需为RGBA四通道图像。 |
| input_image_base64 | str | 和`input_image`二选一 | 传入的图像文件的base64编码，图像文件为需为RGBA四通道图像。 |
| color | str | 否 | 背景色HEX值，默认为`000000` |
| kb | int | 否 | 输出照片的 KB 值，默认为`None`，即不对图像进行KB调整。|
| render | int | 否 | 渲染模式，默认为`0`。可选值为`0`、`1`、`2`，分别对应`纯色`、`上下渐变`、`中心渐变`。 |
| dpi | int | 否 | 图像分辨率，默认为`300` |

**返回参数：**

| 参数名 | 类型 | 说明 |
| :--- | :--- | :--- |
| status | int | 状态码，`true`表示成功 |
| image_base64 | str | 添加背景色之后的图像的base64编码 |



### 3.生成六寸排版照

接口名：`generate_layout_photos`

`生成六寸排版照`接口的逻辑是接收一张 RGB 图像（一般为添加背景色之后的证件照），根据`size`进行照片排布，然后生成一张六寸排版照。

**请求参数：**

| 参数名 | 类型 | 必填 | 说明 |
| :--- | :--- | :--- | :--- |
| input_image | file | 和`input_image_base64`二选一 | 传入的图像文件，图像文件为需为RGB三通道图像。 |
| input_image_base64 | str | 和`input_image`二选一 | 传入的图像文件的base64编码，图像文件为需为RGB三通道图像。 |
| height | int | 否 | 输入图像的高度，默认为`413` |
| width | int | 否 | 输入图像的宽度，默认为`295` |
| kb | int | 否 | 输出照片的 KB 值，默认为`None`，即不对图像进行KB调整。|
| dpi | int | 否 | 图像分辨率，默认为`300` |

**返回参数：**

| 参数名 | 类型 | 说明 |
| :--- | :--- | :--- |
| status | int | 状态码，`true`表示成功 |
| image_base64 | str | 六寸排版照的base64编码 |



### 4.人像抠图

接口名：`human_matting`

`人像抠图`接口的逻辑是接收一张 RGB 图像，输出一张标准抠图人像照和高清抠图人像照（无任何背景填充）。

**请求参数：**

| 参数名 | 类型 | 必填 | 说明 |
| :--- | :--- | :--- | :--- |
| input_image | file | 是 | 传入的图像文件，图像文件为需为RGB三通道图像。 |
| human_matting_model | str | 否 | 人像分割模型，默认为`modnet_photographic_portrait_matting`。可选值为`modnet_photographic_portrait_matting`、`hivision_modnet`、`rmbg-1.4`、`birefnet-v1-lite` |
| dpi | int | 否 | 图像分辨率，默认为`300` |

**返回参数：**

| 参数名 | 类型 | 说明 |
| :--- | :--- | :--- |
| status | int | 状态码，`true`表示成功 |
| image_base64 | str | 抠图人像照的base64编码 |



### 5.图像加水印

接口名：`watermark`

`图像加水印`接口的功能是接收一个水印文本，然后在原图上添加指定的水印。用户可以指定水印的位置、透明度和大小等属性，以便将水印无缝地融合到原图中。

**请求参数：**

| 参数名 | 类型 | 必填 | 说明 |
| :--- | :--- | :--- | :--- |
| input_image | file | 和`input_image_base64`二选一 | 传入的图像文件，图像文件为需为RGB三通道图像。 |
| input_image_base64 | str | 和`input_image`二选一 | 传入的图像文件的base64编码，图像文件为需为RGB三通道图像。 |
| text | str | 否 | 水印文本，默认为`Hello` |
| size | int | 否 | 水印字体大小，默认为`20` |
| opacity | float | 否 | 水印透明度，默认为`0.5` |
| angle | int | 否 | 水印旋转角度，默认为`30` |
| color | str | 否 | 水印颜色，默认为`#000000` |
| space | int | 否 | 水印间距，默认为`25` |
| dpi | int | 否 | 图像分辨率，默认为`300` |

**返回参数：**

| 参数名 | 类型 | 说明 |
| :--- | :--- | :--- |
| status | int | 状态码，`true`表示成功 |
| image_base64 | str | 添加水印之后的图像的base64编码 |



### 6.设置图像KB大小

接口名：`set_kb`

`设置图像KB大小`接口的功能是接收一张图像和目标文件大小（以KB为单位），如果设置的KB值小于原文件，则调整压缩率；如果设置的KB值大于源文件，则通过给文件头添加信息的方式调大KB值，目标是让图像的最终大小与设置的KB值一致。

**请求参数：**

| 参数名 | 类型 | 必填 | 说明 |
| :--- | :--- | :--- | :--- |
| input_image | file | 和`input_image_base64`二选一 | 传入的图像文件，图像文件为需为RGB三通道图像。 |
| input_image_base64 | str | 和`input_image`二选一 | 传入的图像文件的base64编码，图像文件为需为RGB三通道图像。 |
| kb | int | 否 | 输出照片的 KB 值，默认为`None`，即不对图像进行KB调整。|
| dpi | int | 否 | 图像分辨率，默认为`300` |

**返回参数：**

| 参数名 | 类型 | 说明 |
| :--- | :--- | :--- |
| status | int | 状态码，`true`表示成功 |
| image_base64 | str | 设置KB大小之后的图像的base64编码 |



### 7.证件照裁切

接口名：`idphoto_crop`

`证件照裁切`接口的功能是接收一张 RBGA 图像（透明图），输出一张标准证件照和一张高清证件照。

**请求参数：**

| 参数名 | 类型 | 必填 | 说明 |
| :--- | :--- | :--- | :--- |
| input_image | file | 和`input_image_base64`二选一 | 传入的图像文件，图像文件为需为RGBA四通道图像。 |
| input_image_base64 | str | 和`input_image`二选一 | 传入的图像文件的base64编码，图像文件为需为RGBA四通道图像。 |
| height | int | 否 | 标准证件照高度，默认为`413` |
| width | int | 否 | 标准证件照宽度，默认为`295` |
| face_detect_model | str | 否 | 人脸检测模型，默认为`mtcnn`。可选值为`mtcnn`、`face_plusplus`、`retinaface-resnet50` |
| hd | bool | 否 | 是否生成高清证件照，默认为`true` |
| dpi | int | 否 | 图像分辨率，默认为`300` |
| head_measure_ratio | float | 否 | 面部面积与照片面积的比例，默认为`0.2` |
| head_height_ratio | float | 否 | 面部中心与照片顶部的高度比例，默认为`0.45` |
| top_distance_max | float | 否 | 头部与照片顶部距离的比例最大值，默认为`0.12` |
| top_distance_min | float | 否 | 头部与照片顶部距离的比例最小值，默认为`0.1` |

**返回参数：**

| 参数名 | 类型 | 说明 |
| :--- | :--- | :--- |
| status | int | 状态码，`true`表示成功 |
| image_base64 | str | 证件照裁切之后的图像的base64编码 |
| image_base64_hd | str | 高清证件照裁切之后的图像的base64编码，如`hd`参数为`false`，则不返回该参数 |



## cURL 请求示例

cURL 是一个命令行工具，用于使用各种网络协议传输数据。以下是使用 cURL 调用这些 API 的示例。

### 1. 生成证件照(底透明)

```bash
curl -X POST "http://127.0.0.1:8080/idphoto" \
-F "input_image=@demo/images/test0.jpg" \
-F "height=413" \
-F "width=295" \
-F "human_matting_model=modnet_photographic_portrait_matting" \
-F "face_detect_model=mtcnn" \
-F "hd=true" \
-F "dpi=300" \
-F "face_alignment=true" \
-F 'head_height_ratio=0.45' \
-F 'head_measure_ratio=0.2' \
-F 'top_distance_min=0.1' \
-F 'top_distance_max=0.12' \
-F 'sharpen_strength=0' \
-F 'saturation_strength=0' \
-F 'brightness_strength=10' \
-F 'contrast_strength=0'
```

### 2. 添加背景色

```bash
curl -X POST "http://127.0.0.1:8080/add_background" \
-F "input_image=@test.png" \
-F "color=638cce" \
-F "kb=200" \
-F "render=0" \
-F "dpi=300"
```

### 3. 生成六寸排版照

```bash
curl -X POST "http://127.0.0.1:8080/generate_layout_photos" \
-F "input_image=@test.jpg" \
-F "height=413" \
-F "width=295" \
-F "kb=200" \
-F "dpi=300"
```

### 4. 人像抠图

```bash
curl -X POST "http://127.0.0.1:8080/human_matting" \
-F "input_image=@demo/images/test0.jpg" \
-F "human_matting_model=modnet_photographic_portrait_matting" \
-F "dpi=300"
```

### 5. 图片加水印
```bash
curl -X 'POST' \
  'http://127.0.0.1:8080/watermark?size=20&opacity=0.5&angle=30&color=%23000000&space=25' \
  -H 'accept: application/json' \
  -H 'Content-Type: multipart/form-data' \
  -F 'input_image=@demo/images/test0.jpg;type=image/jpeg' \
  -F 'text=Hello' \
  -F 'dpi=300'
```

### 6. 设置图像KB大小
```bash
curl -X 'POST' \
  'http://127.0.0.1:8080/set_kb' \
  -H 'accept: application/json' \
  -H 'Content-Type: multipart/form-data' \
  -F 'input_image=@demo/images/test0.jpg;type=image/jpeg' \
  -F 'kb=50' \
  -F 'dpi=300'
```

### 7. 证件照裁切
```bash
curl -X 'POST' 'http://127.0.0.1:8080/idphoto_crop' \
  -H 'accept: application/json' \
  -H 'Content-Type: multipart/form-data' \
  -F 'input_image=@idphoto_matting.png;type=image/png' \
  -F 'height=413' \
  -F 'width=295' \
  -F 'face_detect_model=mtcnn' \
  -F 'hd=true' \
  -F 'dpi=300' \
  -F 'head_height_ratio=0.45' \
  -F 'head_measure_ratio=0.2' \
  -F 'top_distance_min=0.1' \
  -F 'top_distance_max=0.12'
```



## Python 请求示例

#### 1.生成证件照(底透明)
```python
import requests

url = "http://127.0.0.1:8080/idphoto"
input_image_path = "demo/images/test0.jpg"

files = {"input_image": open(input_image_path, "rb")}
data = {
    "height": 413,
    "width": 295,
    "human_matting_model": "modnet_photographic_portrait_matting",
    "face_detect_model": "mtcnn",
    "hd": True,
    "dpi": 300,
    "face_alignment": True,
    "head_measure_ratio": 0.2,
    "head_height_ratio": 0.45,
    "top_distance_max": 0.12,
    "top_distance_min": 0.1,
    "brightness_strength": 0,
    "contrast_strength": 0,
    "sharpen_strength": 0,
    "saturation_strength": 0,
}

response = requests.post(url, params=params, files=files, data=data).json()

# response为一个json格式字典，包含status、image_base64_standard和image_base64_hd三项
print(response)
```

#### 2.添加背景色

```python
import requests

url = "http://127.0.0.1:8080/add_background"
input_image_path = "test.png"

files = {"input_image": open(input_image_path, "rb")}
data = {
    "color": '638cce',
    "kb": None,
    "render": 0,
    "dpi": 300,
}

response = requests.post(url, files=files, data=data).json()

# response为一个json格式字典，包含status和image_base64
print(response)
```

#### 3.生成六寸排版照

```python
import requests

url = "http://127.0.0.1:8080/generate_layout_photos"
input_image_path = "test.jpg"

files = {"input_image": open(input_image_path, "rb")}
data = {
    "height": 413,
    "width": 295,
    "kb": 200,
    "dpi": 300,
}

response = requests.post(url, files=files, data=data).json()

# response为一个json格式字典，包含status和image_base64
print(response)
```

#### 4.人像抠图

```python
import requests

url = "http://127.0.0.1:8080/human_matting"
input_image_path = "test.jpg"

files = {"input_image": open(input_image_path, "rb")}
data = {
    "human_matting_model": "modnet_photographic_portrait_matting",
    "dpi": 300,
}

response = requests.post(url, files=files, data=data).json()

# response为一个json格式字典，包含status和image_base64
print(response)
```

#### 5.图片加水印

```python
import requests

# 设置请求的 URL 和参数
url = "http://127.0.0.1:8080/watermark"
params = {
    "size": 20,
    "opacity": 0.5,
    "angle": 30,
    "color": "#000000",
    "space": 25,
}

# 设置文件和其他表单数据
input_image_path = "demo/images/test0.jpg"
files = {"input_image": open(input_image_path, "rb")}
data = {"text": "Hello", "dpi": 300}

# 发送 POST 请求
response = requests.post(url, params=params, files=files, data=data)

# 检查响应
if response.ok:
    # 输出响应内容
    print(response.json())
else:
    # 输出错误信息
    print(f"Request failed with status code {response.status_code}: {response.text}")
```

### 6. 设置图像KB大小

```python
import requests

# 设置请求的 URL
url = "http://127.0.0.1:8080/set_kb"

# 设置文件和其他表单数据
input_image_path = "demo/images/test0.jpg"
files = {"input_image": open(input_image_path, "rb")}
data = {"kb": 50, "dpi": 300}

# 发送 POST 请求
response = requests.post(url, files=files, data=data)

# 检查响应
if response.ok:
    # 输出响应内容
    print(response.json())
else:
    # 输出错误信息
    print(f"Request failed with status code {response.status_code}: {response.text}")
```

### 7. 证件照裁切

```python
import requests

# 设置请求的 URL
url = "http://127.0.0.1:8080/idphoto_crop"

# 设置文件和其他表单数据
input_image_path = "idphoto_matting.png"
files = {"input_image": ("idphoto_matting.png", open(input_image_path, "rb"), "image/png")}
data = {
    "height": 413,
    "width": 295,
    "face_detect_model": "mtcnn",
    "hd": "true",
    "dpi": 300,
    "head_measure_ratio": 0.2,
    "head_height_ratio": 0.45,
    "top_distance_max": 0.12,
    "top_distance_min": 0.1,
}

# 发送 POST 请求
response = requests.post(url, files=files, data=data)

# 检查响应
if response.ok:
    # 输出响应内容
    print(response.json())
else:
    # 输出错误信息
    print(f"Request failed with status code {response.status_code}: {response.text}")
```

---

## File: docs/api_EN.md

# API Docs

English / [中文](api_CN.md)

## Table of Contents

- [Before You Start: Start the Backend Service](#before-you-start-start-the-backend-service)
- [API Functionality Description](#api-functionality-description)
  - [1. Generate ID Photo (Transparent Background)](#1-generate-id-photo-transparent-background)
  - [2. Add Background Color](#2-add-background-color)
  - [3. Generate Six-Inch Layout Photo](#3-generate-six-inch-layout-photo)
  - [4. Human Matting](#4-human-matting)
  - [5. Add Watermark to Image](#5-add-watermark-to-image)
  - [6. Set Image KB Size](#6-set-image-kb-size)
  - [7. ID Photo Cropping](#7-id-photo-cropping)
- [cURL Request Examples](#curl-request-examples)
- [Python Request Examples](#python-request-examples)

## Before You Start: Start the Backend Service

Before making API requests, please run the backend service.

```bash
python deploy_api.py
```



## API Functionality Description

### 1. Generate ID Photo (Transparent Background)

API Name: `idphoto`

The logic of the `Generate ID Photo` API is to send an RGB image and output a standard ID photo and a high-definition ID photo:

- **High-definition ID Photo**: An ID photo created based on the aspect ratio of `size`, with the filename having `_hd` appended to `output_image_dir`.
- **Standard ID Photo**: The size equals `size`, scaled from the high-definition ID photo, with the filename as `output_image_dir`.

It is important to note that both generated photos are transparent (RGBA four-channel images). To create a complete ID photo, you will also need to use the `Add Background Color` API below.

> Q: Why is it designed this way?  
> A: Because in actual products, users frequently switch background color preview effects, providing a transparent background image for the front-end JS code to composite colors is a better experience.

**Request Parameters:**

| Parameter Name | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| input_image | file | Choose one of `input_image` or `input_image_base64` | The input image file, which needs to be an RGB three-channel image. |
| input_image_base64 | str | Choose one of `input_image` or `input_image_base64` | The base64 encoding of the input image file, which needs to be an RGB three-channel image. |
| height | int | No | The height of the standard ID photo, with a default value of `413`. |
| width | int | No | The width of the standard ID photo, with a default value of `295`. |
| human_matting_model | str | No | The human segmentation model, with a default value of `modnet_photographic_portrait_matting`. Available values are `modnet_photographic_portrait_matting`, `hivision_modnet`, `rmbg-1.4`, and `birefnet-v1-lite`. |
| face_detect_model | str | No | The face detection model, with a default value of `mtcnn`. Available values are `mtcnn`, `face_plusplus`, and `retinaface-resnet50`. |
| hd | bool | No | Whether to generate a high-definition ID photo, with a default value of `true`. |
| dpi | int | No | The image resolution, with a default value of `300`. |
| face_alignment | bool | No | Whether to perform face alignment, with a default value of `true`. |
| head_measure_ratio | float | No | The ratio of the face area to the photo area, with a default value of `0.2`. |
| head_height_ratio | float | No | The ratio of the face center to the top of the photo, with a default value of `0.45`. |
| top_distance_max | float | No | The maximum ratio of the head to the top of the photo, with a default value of `0.12`. |
| top_distance_min | float | No | The minimum ratio of the head to the top of the photo, with a default value of `0.1`. |
| brightness_strength | float | No | Brightness adjustment strength, default is `0` |
| contrast_strength | float | No | Contrast adjustment strength, default is `0` |
| sharpen_strength | float | No | Sharpening adjustment strength, default is `0` |
| saturation_strength | float | No | Saturation adjustment strength, default is `0` |

**Return Parameters:**

| Parameter Name | Type | Description |
| :--- | :--- | :--- |
| status | str | The status of the request, with a default value of `success`. |
| image_base64_standard | str | The base64 encoding of the standard ID photo. |
| image_base64_hd | str | The base64 encoding of the high-definition ID photo. |

### 2. Add Background Color

API Name: `add_background`

The logic of the `Add Background Color` API is to receive an RGBA image (transparent image) and add a background color based on `color`, composing a JPG image.

**Request Parameters:**

| Parameter Name | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| input_image | file | Choose one of `input_image` or `input_image_base64` | The input image file, which needs to be an RGB three-channel image. |
| input_image_base64 | str | Choose one of `input_image` or `input_image_base64` | The base64 encoding of the input image file, which needs to be an RGB three-channel image. |
| color | str | Yes | The background color in hexadecimal format, e.g., `#000000` for black. |
| kb | int | No | The target file size in KB. If the specified KB value is less than the original file, it adjusts the compression rate. If the specified KB value is greater than the source file, it increases the KB value by adding information to the file header, aiming for the final size of the image to match the specified KB value. |
| render | int | No | The rendering mode, with a default value of `0`. Available values are `0`, `1`, and `2`. |
| dpi | int | No | The image resolution, with a default value of `300`. |

**Return Parameters:**

| Parameter Name | Type | Description |
| :--- | :--- | :--- |
| status | str | The status of the request, with a default value of `success`. |
| image_base64 | str | The base64 encoding of the image with the background color added. |



### 3. Generate Six-Inch Layout Photo

API Name: `generate_layout_photos`

The logic of the `Generate Six-Inch Layout Photo` API is to receive an RGB image (usually the ID photo after adding background color), arrange the photos based on `size`, and then generate a six-inch layout photo.

**Request Parameters:**

| Parameter Name | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| input_image | file | Choose one of `input_image` or `input_image_base64` | The input image file, which needs to be an RGB three-channel image. |
| input_image_base64 | str | Choose one of `input_image` or `input_image_base64` | The base64 encoding of the input image file, which needs to be an RGB three-channel image. |
| height | int | No | The height of the standard ID photo, with a default value of `413`. |
| width | int | No | The width of the standard ID photo, with a default value of `295`. |
| kb | int | No | The target file size in KB. If the specified KB value is less than the original file, it adjusts the compression rate. If the specified KB value is greater than the source file, it increases the KB value by adding information to the file header, aiming for the final size of the image to match the specified KB value. |
| dpi | int | No | The image resolution, with a default value of `300`. |

**Return Parameters:**

| Parameter Name | Type | Description |
| :--- | :--- | :--- |
| status | str | The status of the request, with a default value of `success`. |
| image_base64 | str | The base64 encoding of the six-inch layout photo. |




### 4. Human Matting

API Name: `human_matting`

The logic of the `Human Matting` API is to receive an RGB image and output a standard matting portrait and a high-definition matting portrait (without any background filling).

**Request Parameters:**

| Parameter Name | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| input_image | file | Choose one of `input_image` or `input_image_base64` | The input image file, which needs to be an RGB three-channel image. |
| input_image_base64 | str | Choose one of `input_image` or `input_image_base64` | The base64 encoding of the input image file, which needs to be an RGB three-channel image. |
| human_matting_model | str | No | The human segmentation model, with a default value of `modnet_photographic_portrait_matting`. Available values are `modnet_photographic_portrait_matting`, `hivision_modnet`, `rmbg-1.4`, and `birefnet-v1-lite`. |
| dpi | int | No | The image resolution, with a default value of `300`. |

**Return Parameters:**

| Parameter Name | Type | Description |
| :--- | :--- | :--- |
| status | str | The status of the request, with a default value of `success`. |
| image_base64 | str | The base64 encoding of the human matting portrait. |




### 5. Add Watermark to Image

API Name: `watermark`

The functionality of the `Add Watermark to Image` API is to receive a watermark text and add the specified watermark to the original image. Users can specify attributes such as the watermark's position, opacity, and size to seamlessly blend the watermark into the original image.

**Request Parameters:**

| Parameter Name | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| input_image | file | Choose one of `input_image` or `input_image_base64` | The input image file, which needs to be an RGB three-channel image. |
| input_image_base64 | str | Choose one of `input_image` or `input_image_base64` | The base64 encoding of the input image file, which needs to be an RGB three-channel image. |
| text | str | Yes | The watermark text to be added. |
| size | int | No | The size of the watermark text, with a default value of `20`. |
| opacity | float | No | The opacity of the watermark text, with a default value of `0.5`. |
| angle | int | No | The angle of the watermark text, with a default value of `30`. |
| color | str | No | The color of the watermark text, with a default value of `#000000`. |
| space | int | No | The space between the watermark text and the image, with a default value of `25`. |
| dpi | int | No | The image resolution, with a default value of `300`. |

**Return Parameters:**

| Parameter Name | Type | Description |
| :--- | :--- | :--- |
| status | str | The status of the request, with a default value of `success`. |



### 6. Set Image KB Size

API Name: `set_kb`

The functionality of the `Set Image KB Size` API is to receive an image and a target file size (in KB). If the specified KB value is less than the original file, it adjusts the compression rate. If the specified KB value is greater than the source file, it increases the KB value by adding information to the file header, aiming for the final size of the image to match the specified KB value.

**Request Parameters:**

| Parameter Name | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| input_image | file | Choose one of `input_image` or `input_image_base64` | The input image file, which needs to be an RGB three-channel image. |
| input_image_base64 | str | Choose one of `input_image` or `input_image_base64` | The base64 encoding of the input image file, which needs to be an RGB three-channel image. |
| kb | int | Yes | The target file size in KB. |
| dpi | int | No | The image resolution, with a default value of `300`. |

**Return Parameters:**

| Parameter Name | Type | Description |
| :--- | :--- | :--- |
| status | str | The status of the request, with a default value of `success`. |
| image_base64 | str | The base64 encoding of the image with the specified KB size. |




### 7. ID Photo Cropping

API Name: `idphoto_crop`

The functionality of the `ID Photo Cropping` API is to receive an RGBA image (transparent image) and output a standard ID photo and a high-definition ID photo.

**Request Parameters:**

| Parameter Name | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| input_image | file | Choose one of `input_image` or `input_image_base64` | The input image file, which needs to be an RGB three-channel image. |
| input_image_base64 | str | Choose one of `input_image` or `input_image_base64` | The base64 encoding of the input image file, which needs to be an RGB three-channel image. |
| height | int | Yes | The height of the standard ID photo. |
| width | int | Yes | The width of the standard ID photo. |
| face_detect_model | str | No | The face detection model, with a default value of `mtcnn`. Available values are `mtcnn`, `face_plusplus`, and `retinaface-resnet50`. |
| hd | bool | No | Whether to generate a high-definition ID photo, with a default value of `true`. |
| dpi | int | No | The image resolution, with a default value of `300`. |
| head_measure_ratio | float | No | The ratio of the face area to the photo area, with a default value of `0.2`. |
| head_height_ratio | float | No | The ratio of the face center to the top of the photo, with a default value of `0.45`. |
| top_distance_max | float | No | The maximum ratio of the head to the top of the photo, with a default value of `0.12`. |
| top_distance_min | float | No | The minimum ratio of the head to the top of the photo, with a default value of `0.1`. |

**Return Parameters:**

| Parameter Name | Type | Description |
| :--- | :--- | :--- |
| status | str | The status of the request, with a default value of `success`. |
| image_base64 | str | The base64 encoding of the ID photo. |





## cURL Request Examples

cURL is a command-line tool for transferring data using various network protocols. Here are examples of using cURL to call these APIs.

### 1. Generate ID Photo (Transparent Background)

```bash
curl -X POST "http://127.0.0.1:8080/idphoto" \
-F "input_image=@demo/images/test0.jpg" \
-F "height=413" \
-F "width=295" \
-F "human_matting_model=modnet_photographic_portrait_matting" \
-F "face_detect_model=mtcnn" \
-F "hd=true" \
-F "dpi=300" \
-F "face_alignment=true"
```

### 2. Add Background Color

```bash
curl -X POST "http://127.0.0.1:8080/add_background" \
-F "input_image=@test.png" \
-F "color=638cce" \
-F "kb=200" \
-F "render=0" \
-F "dpi=300"
```

### 3. Generate Six-Inch Layout Photo

```bash
curl -X POST "http://127.0.0.1:8080/generate_layout_photos" \
-F "input_image=@test.jpg" \
-F "height=413" \
-F "width=295" \
-F "kb=200" \
-F "dpi=300"
```

### 4. Human Matting

```bash
curl -X POST "http://127.0.0.1:8080/human_matting" \
-F "input_image=@demo/images/test0.jpg" \
-F "human_matting_model=modnet_photographic_portrait_matting" \
-F "dpi=300"
```

### 5. Add Watermark to Image
```bash
curl -X 'POST' \
  'http://127.0.0.1:8080/watermark?size=20&opacity=0.5&angle=30&color=%23000000&space=25' \
  -H 'accept: application/json' \
  -H 'Content-Type: multipart/form-data' \
  -F 'input_image=@demo/images/test0.jpg;type=image/jpeg' \
  -F 'text=Hello' \
  -F 'dpi=300'
```

### 6. Set Image KB Size
```bash
curl -X 'POST' \
  'http://127.0.0.1:8080/set_kb' \
  -H 'accept: application/json' \
  -H 'Content-Type: multipart/form-data' \
  -F 'input_image=@demo/images/test0.jpg;type=image/jpeg' \
  -F 'kb=50' \
  -F 'dpi=300'
```

### 7. ID Photo Cropping
```bash
curl -X 'POST' \
  'http://127.0.0.1:8080/idphoto_crop?head_measure_ratio=0.2&head_height_ratio=0.45&top_distance_max=0.12&top_distance_min=0.1' \
  -H 'accept: application/json' \
  -H 'Content-Type: multipart/form-data' \
  -F 'input_image=@idphoto_matting.png;type=image/png' \
  -F 'height=413' \
  -F 'width=295' \
  -F 'face_detect_model=mtcnn' \
  -F 'hd=true' \
  -F 'dpi=300'
```



## Python Request Examples

#### 1. Generate ID Photo (Transparent Background)
```python
import requests

url = "http://127.0.0.1:8080/idphoto"
input_image_path = "demo/images/test0.jpg"

# Set request parameters
files = {"input_image": open(input_image_path, "rb")}
data = {
    "height": 413,
    "width": 295,
    "human_matting_model": "modnet_photographic_portrait_matting",
    "face_detect_model": "mtcnn",
    "hd": True,
    "dpi": 300,
    "face_alignment": True,
    "head_measure_ratio": 0.2,
    "head_height_ratio": 0.45,
    "top_distance_max": 0.12,
    "top_distance_min": 0.1,
    "brightness_strength": 0,
    "contrast_strength": 0,
    "sharpen_strength": 0,
    "saturation_strength": 0,
}

response = requests.post(url, files=files, data=data).json()

# response is a JSON formatted dictionary containing status, image_base64_standard, and image_base64_hd
print(response)
```

#### 2. Add Background Color

```python
import requests

url = "http://127.0.0.1:8080/add_background"
input_image_path = "test.png"

files = {"input_image": open(input_image_path, "rb")}
data = {
    "color": '638cce',
    "kb": None,
    "render": 0,
    "dpi": 300,
}

response = requests.post(url, files=files, data=data).json()

# response is a JSON formatted dictionary containing status and image_base64
print(response)
```

#### 3. Generate Six-Inch Layout Photo

```python
import requests

url = "http://127.0.0.1:8080/generate_layout_photos"
input_image_path = "test.jpg"

files = {"input_image": open(input_image_path, "rb")}
data = {
    "height": 413,
    "width": 295,
    "kb": 200,
    "dpi": 300,
}

response = requests.post(url, files=files, data=data).json()

# response is a JSON formatted dictionary containing status and image_base64
print(response)
```

#### 4. Human Matting

```python
import requests

url = "http://127.0.0.1:8080/human_matting"
input_image_path = "test.jpg"

files = {"input_image": open(input_image_path, "rb")}
data = {
    "human_matting_model": "modnet_photographic_portrait_matting",
    "dpi": 300,
}

response = requests.post(url, files=files, data=data).json()

# response is a JSON formatted dictionary containing status and image_base64
print(response)
```

#### 5. Add Watermark to Image

```python
import requests

# Set the request URL and parameters
url = "http://127.0.0.1:8080/watermark"
params = {
    "size": 20,
    "opacity": 0.5,
    "angle": 30,
    "color": "#000000",
    "space": 25,
}

# Set file and other form data
input_image_path = "demo/images/test0.jpg"
files = {"input_image": open(input_image_path, "rb")}
data = {"text": "Hello", "dpi": 300}

# Send POST request
response = requests.post(url, params=params, files=files, data=data)

# Check response
if response.ok:
    # Output response content
    print(response.json())
else:
    # Output error message
    print(f"Request failed with status code {response.status_code}: {response.text}")
```

### 6. Set Image KB Size

```python
import requests

# Set the request URL
url = "http://127.0.0.1:8080/set_kb"

# Set file and other form data
input_image_path = "demo/images/test0.jpg"
files = {"input_image": open(input_image_path, "rb")}
data = {"kb": 50, "dpi": 300}

# Send POST request
response = requests.post(url, files=files, data=data)

# Check response
if response.ok:
    # Output response content
    print(response.json())
else:
    # Output error message
    print(f"Request failed with status code {response.status_code}: {response.text}")
```

### 7. ID Photo Cropping

```python
import requests

# Set the request URL
url = "http://127.0.0.1:8080/idphoto_crop"

# Set file and other form data
input_image_path = "idphoto_matting.png"
files = {"input_image": ("idphoto_matting.png", open(input_image_path, "rb"), "image/png")}
data = {
    "height": 413,
    "width": 295,
    "face_detect_model": "mtcnn",
    "hd": "true",
    "dpi": 300,
    "head_measure_ratio": 0.2,
    "head_height_ratio": 0.45,
    "top_distance_max": 0.12,
    "top_distance_min": 0.1,
}

# Send POST request
response = requests.post(url, files=files, data=data)

# Check response
if response.ok:
    # Output response content
    print(response.json())
else:
    # Output error message
    print(f"Request failed with status code {response.status_code}: {response.text}")
```

---

## File: docs/face++_CN.md

# Face++ 人脸检测配置文档

[Face++官方文档](https://console.faceplusplus.com.cn/documents/4888373)

## 1. 注册Face++账号
要使用 Face++ 的人脸检测 API，您首先需要在 Face++ 的官方网站上注册一个账号。注册后，您将能够访问 API 控制台和相关服务。

### 步骤：
1. 访问 [Face++ 官网](https://www.faceplusplus.com.cn/)。
2. 点击“注册”按钮，填写相关信息以创建您的账号。

## 2. 获取API KEY和API SECRET
注册并登录后，您需要获取用于身份验证的 API Key 和 API Secret。这些信息是调用 API 时必需的。

### 步骤：
1. 登录到您的 Face++ 账号。
2. 进入 控制台 -> 应用管理 -> API Key。
3. 在控制台中，您将看到您的 API Key 和 API Secret。

## 3. 设置环境变量
为了在代码中安全地使用 API Key 和 API Secret，建议将它们设置为环境变量。这样可以避免在代码中硬编码敏感信息。

### 在不同操作系统中设置环境变量的步骤：
- **Windows**:
    1. 打开命令提示符。
    2. 输入以下命令并按回车：
       ```cmd
       set FACE_PLUS_API_KEY="您的API_KEY"
       set FACE_PLUS_API_SECRET="您的API_SECRET"
       ```

- **Linux / macOS**:
    1. 打开终端。
    2. 输入以下命令并按回车：
       ```bash
       export FACE_PLUS_API_KEY="你的API_KEY"
       export FACE_PLUS_API_SECRET="你的API_SECRET"
       ```

> **注意**: 您可能需要在启动应用程序之前运行上述命令，或者将这些命令添加到您的 shell 配置文件（例如 `.bashrc` 或 `.bash_profile`）中，以便每次启动终端时自动加载。

## 4. 启动Gradio服务

运行gradio服务，在「人脸检测模型」中选择「face++」即可。

```bash
python app.py
```



## 错误码的解释

https://console.faceplusplus.com.cn/documents/4888373

---

## File: docs/face++_EN.md

Here's the translated document in English:

# Face++ Face Detection Configuration Document

[Face++ Official Documentation](https://console.faceplusplus.com.cn/documents/4888373)

## 1. Register a Face++ Account
To use the Face++ Face Detection API, you first need to register an account on the Face++ official website. After registration, you will be able to access the API console and related services.

### Steps:
1. Visit the [Face++ Official Website](https://www.faceplusplus.com.cn/).
2. Click the "Register" button and fill in the relevant information to create your account.

## 2. Obtain API KEY and API SECRET
After registering and logging in, you need to obtain the API Key and API Secret for authentication. This information is necessary for calling the API.

### Steps:
1. Log in to your Face++ account.
2. Go to Console -> Application Management -> API Key.
3. In the console, you will see your API Key and API Secret.

## 3. Set Environment Variables
To securely use the API Key and API Secret in your code, it is recommended to set them as environment variables. This avoids hardcoding sensitive information in your code.

### Steps to Set Environment Variables on Different Operating Systems:
- **Windows**:
    1. Open the Command Prompt.
    2. Enter the following commands and press Enter:
       ```cmd
       set FACE_PLUS_API_KEY="Your_API_KEY"
       set FACE_PLUS_API_SECRET="Your_API_SECRET"
       ```

- **Linux / macOS**:
    1. Open the terminal.
    2. Enter the following commands and press Enter:
       ```bash
       export FACE_PLUS_API_KEY="Your_API_KEY"
       export FACE_PLUS_API_SECRET="Your_API_SECRET"
       ```

> **Note**: You may need to run the above commands before starting your application, or add these commands to your shell configuration file (e.g., `.bashrc` or `.bash_profile`) so that they are automatically loaded each time you start the terminal.

## 4. Start Gradio Service
Run the Gradio service, and select "face++" in the "Face Detection Model".

```bash
python app.py
```



## Explanation of error codes

https://console.faceplusplus.com.cn/documents/4888373

---

## File: README_EN.md

> **Related Projects**：
>
> - [SwanLab](https://github.com/SwanHubX/SwanLab): Used throughout the training of the portrait matting model for analysis and monitoring, as well as collaboration with lab colleagues, significantly improving training efficiency.



# Table of Contents

- [Recent Updates](#-recent-updates)
- [Project Overview](#-project-overview)
- [Community](#-community)
- [Preparation](#-preparation)
- [Demo Startup](#-run-gradio-demo)
- [Python Inference](#-python-inference)
- [API Service Deployment](#️-deploy-api-service)
- [Docker Deployment](#-docker-deployment)
- [Contact Us](#-contact-us)
- [Q&A](#qa)
- [Contributors](#contributors)
- [Thanks for support](#thanks-for-support)
- [License](#lincese)



# 🤩 Recent Updates

- Online Experience: [](https://swanhub.co/ZeYiLin/HivisionIDPhotos/demo)、[](https://huggingface.co/spaces/TheEeeeLin/HivisionIDPhotos)、[![][modelscope-shield]][modelscope-link]、[![][compshare-shield]][compshare-link]

- 2024.11.20: Gradio Demo adds **Print Layout** option, supports six-inch, five-inch, A4, 3R, and 4R layout sizes
- 2024.11.16: API interface adds beauty effect parameter
- 2024.09.24: API interface adds base64 image input option | Gradio Demo adds **Layout Photo Cropping Lines** feature
- 2024.09.22: Gradio Demo adds **Beast Mode** and **DPI** parameter
- 2024.09.18: Gradio Demo adds **Share Template Photos** feature and **American Style** background option
- 2024.09.17: Gradio Demo adds **Custom Background Color-HEX Input** feature | **(Community Contribution) C++ Version** - [HivisionIDPhotos-cpp](https://github.com/zjkhahah/HivisionIDPhotos-cpp) contributed by [zjkhahah](https://github.com/zjkhahah)
- 2024.09.16: Gradio Demo adds **Face Rotation Alignment** feature, custom size input supports **millimeters**
- 2024.09.14: Gradio Demo adds **Custom DPI** feature, adds Japanese and Korean support, adds **Adjust Brightness, Contrast, Sharpness** feature



# Project Overview

> 🚀 Thank you for your interest in our work. You may also want to check out our other achievements in the field of image processing, feel free to reach out: zeyi.lin@swanhub.co.

HivisionIDPhoto aims to develop a practical and systematic intelligent algorithm for producing ID photos.

It utilizes a comprehensive AI model workflow to recognize various user photo-taking scenarios, perform matting, and generate ID photos.

**HivisionIDPhoto can achieve:**

1. Lightweight matting (purely offline, fast inference with **CPU** only)
2. Generate standard ID photos and six-inch layout photos based on different size specifications
3. Support pure offline or edge-cloud inference
4. Beauty effects (waiting)
5. Intelligent formal wear change (waiting)



---

If HivisionIDPhoto helps you, please star this repo or recommend it to your friends to solve the urgent ID photo production problem!



# 🏠 Community

We have shared some interesting applications and extensions of HivisionIDPhotos built by the community:

- [HivisionIDPhotos-ComfyUI](https://github.com/AIFSH/HivisionIDPhotos-ComfyUI): ComfyUI ID photo processing workflow built by [AIFSH](https://github.com/AIFSH/HivisionIDPhotos-ComfyUI) 

[](https://github.com/AIFSH/HivisionIDPhotos-ComfyUI)

- [HivisionIDPhotos-wechat-weapp](https://github.com/no1xuan/HivisionIDPhotos-wechat-weapp): WeChat ID photo mini program, powered by the HivisionIDphotos algorithm, contributed by [no1xuan](https://github.com/no1xuan)

[](https://github.com/no1xuan/HivisionIDPhotos-wechat-weapp)

- [HivisionIDPhotos-Uniapp](https://github.com/soulerror/HivisionIDPhotos-Uniapp): Front-end of WeChat ID photo mini program based on uniapp, powered by the HivisionIDphotos algorithm, contributed by [soulerror](https://github.com/soulerror)

[](https://github.com/soulerror/HivisionIDPhotos-Uniapp)

- [HivisionIDPhotos-cpp](https://github.com/zjkhahah/HivisionIDPhotos-cpp): C++ version of HivisionIDphotos, built by [zjkhahah](https://github.com/zjkhahah)
- [HivisionIDPhotos-windows-GUI](https://github.com/zhaoyun0071/HivisionIDPhotos-windows-GUI): Windows client application built by [zhaoyun0071](https://github.com/zhaoyun0071)
- [HivisionIDPhotos-NAS](https://github.com/ONG-Leo/HivisionIDPhotos-NAS): Chinese tutorial for Synology NAS deployment, contributed by [ONG-Leo](https://github.com/ONG-Leo)



# 🔧 Preparation

Environment installation and dependencies:
- Python >= 3.7 (project primarily tested on Python 3.10)
- OS: Linux, Windows, MacOS

## 1. Clone the Project

```bash
git clone https://github.com/Zeyi-Lin/HivisionIDPhotos.git
cd  HivisionIDPhotos
```

## 2. Install Dependency Environment

> It is recommended to create a python3.10 virtual environment using conda, then execute the following commands

```bash
pip install -r requirements.txt
pip install -r requirements-app.txt
```

## 3. Download Weight Files

**Method 1: Script Download**

```bash
python scripts/download_model.py --models all
```

**Method 2: Direct Download**

Store in the project's `hivision/creator/weights` directory:
- `modnet_photographic_portrait_matting.onnx` (24.7MB): Official weights of [MODNet](https://github.com/ZHKKKe/MODNet), [download](https://github.com/Zeyi-Lin/HivisionIDPhotos/releases/download/pretrained-model/modnet_photographic_portrait_matting.onnx)
- `hivision_modnet.onnx` (24.7MB): Matting model with better adaptability for pure color background replacement, [download](https://github.com/Zeyi-Lin/HivisionIDPhotos/releases/download/pretrained-model/hivision_modnet.onnx)
- `rmbg-1.4.onnx` (176.2MB): Open-source matting model from [BRIA AI](https://huggingface.co/briaai/RMBG-1.4), [download](https://huggingface.co/briaai/RMBG-1.4/resolve/main/onnx/model.onnx?download=true) and rename to `rmbg-1.4.onnx`
- `birefnet-v1-lite.onnx`(224MB): Open-source matting model from [ZhengPeng7](https://github.com/ZhengPeng7/BiRefNet), [download](https://github.com/ZhengPeng7/BiRefNet/releases/download/v1/BiRefNet-general-bb_swin_v1_tiny-epoch_232.onnx) and rename to `birefnet-v1-lite.onnx`

## 4. Face Detection Model Configuration (Optional)

| Extended Face Detection Model | Description | Documentation |
| -- | -- | -- |
| MTCNN | **Offline** face detection model, high-performance CPU inference, default model, lower detection accuracy | Use it directly after cloning this project |
| RetinaFace | **Offline** face detection model, moderate CPU inference speed (in seconds), and high accuracy | [Download](https://github.com/Zeyi-Lin/HivisionIDPhotos/releases/download/pretrained-model/retinaface-resnet50.onnx) and place it in the `hivision/creator/retinaface/weights` directory |
| Face++ | Online face detection API launched by Megvii, higher detection accuracy, [official documentation](https://console.faceplusplus.com.cn/documents/4888373) | [Usage Documentation](docs/face++_EN.md)|

## 5. Performance Reference

> Test environment: Mac M1 Max 64GB, non-GPU acceleration, test image resolution: 512x715(1) and 764×1146(2).

| Model Combination | Memory Occupation | Inference Time (1) | Inference Time (2) |
| -- | -- | -- | -- |
| MODNet + mtcnn | 410MB | 0.207s | 0.246s |
| MODNet + retinaface | 405MB | 0.571s | 0.971s |
| birefnet-v1-lite + retinaface | 6.20GB | 7.063s | 7.128s |

## 6. GPU Inference Acceleration (Optional)

In the current version, the model that can be accelerated by NVIDIA GPUs is `birefnet-v1-lite`, and please ensure you have around 16GB of VRAM.

If you want to use NVIDIA GPU acceleration for inference, after ensuring you have installed CUDA and cuDNN, find the corresponding `onnxruntime-gpu` version to install according to the [onnxruntime-gpu documentation](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#cuda-12x), and find the corresponding `pytorch` version to install according to the [pytorch official website](https://pytorch.org/get-started/locally/).

```bash
# If your computer is installed with CUDA 12.x and cuDNN 8
# Installing torch is optional. If you can't configure cuDNN, try installing torch
pip install onnxruntime-gpu==1.18.0
pip install torch --index-url https://download.pytorch.org/whl/cu121
```

After completing the installation, call the `birefnet-v1-lite` model to utilize GPU acceleration for inference.

> TIP: CUDA installations are backward compatible. For example, if your CUDA version is 12.6 but the highest version currently matched by torch is 12.4, it's still possible to install version 12.4 on your computer.


# 🚀 Run Gradio Demo

```bash
python app.py
```

Running the program will generate a local web page where you can perform operations and interact with ID photos.





# 🚀 Python Inference

Core parameters:

- `-i`: Input image path
- `-o`: Output image path
- `-t`: Inference type, options are idphoto, human_matting, add_background, generate_layout_photos
- `--matting_model`: Portrait matting model weight selection
- `--face_detect_model`: Face detection model selection

More parameters can be viewed by running `python inference.py --help`

## 1. ID Photo Creation

Input 1 photo to obtain 1 standard ID photo and 1 high-definition ID photo in 4-channel transparent PNG.

```python
python inference.py -i demo/images/test0.jpg -o ./idphoto.png --height 413 --width 295
```

## 2. Portrait Matting

Input 1 photo to obtain 1 4-channel transparent PNG.

```python
python inference.py -t human_matting -i demo/images/test0.jpg -o ./idphoto_matting.png --matting_model hivision_modnet
```

## 3. Add Background Color to Transparent Image

Input 1 4-channel transparent PNG to obtain 1 3-channel image with added background color.

```python
python inference.py -t add_background -i ./idphoto.png -o ./idphoto_ab.jpg -c 4f83ce -k 30 -r 1
```

## 4. Generate Six-Inch Layout Photo

Input 1 3-channel photo to obtain 1 six-inch layout photo.

```python
python inference.py -t generate_layout_photos -i ./idphoto_ab.jpg -o ./idphoto_layout.jpg --height 413 --width 295 -k 200
```

## 5. ID Photo Cropping

Input 1 4-channel photo (the image after matting) to obtain 1 standard ID photo and 1 high-definition ID photo in 4-channel transparent PNG.

```python
python inference.py -t idphoto_crop -i ./idphoto_matting.png -o ./idphoto_crop.png --height 413 --width 295
```



# ⚡️ Deploy API Service

## Start Backend

```
python deploy_api.py
```

## Request API Service

For detailed request methods, please refer to the [API Documentation](docs/api_EN.md), which includes the following request examples:
- [cURL](docs/api_EN.md#curl-request-examples)
- [Python](docs/api_EN.md#python-request-example)



# 🐳 Docker Deployment

## 1. Pull or Build Image

> Choose one of the following methods

**Method 1: Pull the latest image:**

```bash
docker pull linzeyi/hivision_idphotos
```

**Method 2: Directly build the image from Dockerfile:**

After ensuring that at least one [matting model weight file](#3-download-weight-files) is placed in the `hivision/creator/weights` directory, execute the following in the project root directory:

```bash
docker build -t linzeyi/hivision_idphotos .
```

**Method 3: Build using Docker Compose:**

After ensuring that at least one [matting model weight file](#3-download-weight-files) is placed in the `hivision/creator/weights` directory, execute the following in the project root directory:

```bash
docker compose build
```

## 2. Run Services

**Start Gradio Demo Service**

Run the following command, and you can access it locally at [http://127.0.0.1:7860](http://127.0.0.1:7860/).

```bash
docker run -d -p 7860:7860 linzeyi/hivision_idphotos
```

**Start API Backend Service**

```bash
docker run -d -p 8080:8080 linzeyi/hivision_idphotos python3 deploy_api.py
```

**Start Both Services Simultaneously**

```bash
docker compose up -d
```

## Environment Variables

This project provides some additional configuration options, which can be set using environment variables:

| Environment Variable | Type | Description | Example |
|--|--|--|--|
| FACE_PLUS_API_KEY | Optional | This is your API key obtained from the Face++ console | `7-fZStDJ····` |
| FACE_PLUS_API_SECRET | Optional | Secret corresponding to the Face++ API key | `VTee824E····` |
| RUN_MODE | Optional | Running mode, with the option of `beast` (beast mode). In beast mode, the face detection and matting models will not release memory, achieving faster secondary inference speeds. It is recommended to try to have at least 16GB of memory. | `beast` |

Example of using environment variables in Docker:
```bash
docker run  -d -p 7860:7860 \
    -e FACE_PLUS_API_KEY=7-fZStDJ···· \
    -e FACE_PLUS_API_SECRET=VTee824E···· \
    -e RUN_MODE=beast \
    linzeyi/hivision_idphotos 
```



# 📖 Cite Projects

1. MTCNN:

```bibtex
@software{ipazc_mtcnn_2021,
    author = {ipazc},
    title = {{MTCNN}},
    url = {https://github.com/ipazc/mtcnn},
    year = {2021},
    publisher = {GitHub}
}
```

2. ModNet:

```bibtex
@software{zhkkke_modnet_2021,
    author = {ZHKKKe},
    title = {{ModNet}},
    url = {https://github.com/ZHKKKe/MODNet},
    year = {2021},
    publisher = {GitHub}
}
```



# Q&A

## 1. How to modify preset sizes and colors?

- Size: After modifying [size_list_EN.csv](demo/assets/size_list_EN.csv), run `app.py` again. The first column is the size name, the second column is the height, and the third column is the width.
- Color: After modifying [color_list_EN.csv](demo/assets/color_list_EN.csv), run `app.py` again. The first column is the color name, and the second column is the Hex value.

## 2. How to Change the Watermark Font?

1. Place the font file in the `hivision/plugin/font` folder.
2. Change the `font_file` parameter value in `hivision/plugin/watermark.py` to the name of the font file.

## 3. How to Add Social Media Template Photos?

1. Place the template image in the `hivision/plugin/template/assets` folder. The template image should be a 4-channel transparent PNG.
2. Add the latest template information to the `hivision/plugin/template/assets/template_config.json` file. Here, `width` is the template image width (px), `height` is the template image height (px), `anchor_points` are the coordinates (px) of the four corners of the transparent area in the template; `rotation` is the rotation angle of the transparent area relative to the vertical direction, where >0 is counterclockwise and <0 is clockwise.
3. Add the name of the latest template to the `TEMPLATE_NAME_LIST` variable in the `_generate_image_template` function of `demo/processor.py`.



## 4. How to Modify the Top Navigation Bar of the Gradio Demo?

- Modify the `demo/assets/title.md` file.



# 📧 Contact Us

If you have any questions, please email zeyi.lin@swanhub.co



# Contributors

<a href="https://github.com/Zeyi-Lin/HivisionIDPhotos/graphs/contributors">
  
</a>

[Zeyi-Lin](https://github.com/Zeyi-Lin)、[SAKURA-CAT](https://github.com/SAKURA-CAT)、[Feudalman](https://github.com/Feudalman)、[swpfY](https://github.com/swpfY)、[Kaikaikaifang](https://github.com/Kaikaikaifang)、[ShaohonChen](https://github.com/ShaohonChen)、[KashiwaByte](https://github.com/KashiwaByte)



# Thanks for support

[](https://github.com/Zeyi-Lin/HivisionIDPhotos/stargazers)

[](https://github.com/Zeyi-Lin/HivisionIDPhotos/network/members)

[](https://star-history.com/#Zeyi-Lin/HivisionIDPhotos&Date)

# Lincese

This repository is licensed under the [Apache-2.0 License](LICENSE).

[github-stars-shield]: https://img.shields.io/github/stars/zeyi-lin/hivisionidphotos?color=ffcb47&labelColor=black&style=flat-square
[github-stars-link]: https://github.com/zeyi-lin/hivisionidphotos/stargazers

[swanhub-demo-shield]: https://swanhub.co/git/repo/SwanHub%2FAuto-README/file/preview?ref=main&path=swanhub.svg
[swanhub-demo-link]: https://swanhub.co/ZeYiLin/HivisionIDPhotos/demo

[spaces-shield]: https://img.shields.io/badge/🤗-Open%20in%20Spaces-blue
[spaces-link]: https://huggingface.co/spaces/TheEeeeLin/HivisionIDPhotos


[wechat-shield]: https://img.shields.io/badge/WeChat-微信-4cb55e
[wechat-link]: https://docs.qq.com/doc/DUkpBdk90eWZFS2JW


[release-shield]: https://img.shields.io/github/v/release/zeyi-lin/hivisionidphotos?color=369eff&labelColor=black&logo=github&style=flat-square
[release-link]: https://github.com/zeyi-lin/hivisionidphotos/releases

[license-shield]: https://img.shields.io/badge/license-apache%202.0-white?labelColor=black&style=flat-square
[license-link]: https://github.com/Zeyi-Lin/HivisionIDPhotos/blob/master/LICENSE

[github-issues-shield]: https://img.shields.io/github/issues/zeyi-lin/hivisionidphotos?color=ff80eb&labelColor=black&style=flat-square
[github-issues-link]: https://github.com/zeyi-lin/hivisionidphotos/issues

[dockerhub-shield]: https://img.shields.io/docker/v/linzeyi/hivision_idphotos?color=369eff&label=docker&labelColor=black&logoColor=white&style=flat-square
[dockerhub-link]: https://hub.docker.com/r/linzeyi/hivision_idphotos/tags

[trendshift-shield]: https://trendshift.io/api/badge/repositories/11622
[trendshift-link]: https://trendshift.io/repositories/11622

[hellogithub-shield]: https://abroad.hellogithub.com/v1/widgets/recommend.svg?rid=8ea1457289fb4062ba661e5299e733d6&claim_uid=Oh5UaGjfrblg0yZ
[hellogithub-link]: https://hellogithub.com/repository/8ea1457289fb4062ba661e5299e733d6

[github-contributors-shield]: https://img.shields.io/github/contributors/zeyi-lin/hivisionidphotos?color=c4f042&labelColor=black&style=flat-square
[github-contributors-link]: https://github.com/zeyi-lin/hivisionidphotos/graphs/contributors

[github-forks-shield]: https://img.shields.io/github/forks/zeyi-lin/hivisionidphotos?color=8ae8ff&labelColor=black&style=flat-square
[github-forks-link]: https://github.com/zeyi-lin/hivisionidphotos/network/members

[modelscope-shield]: https://img.shields.io/badge/Demo_on_ModelScope-purple?logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjIzIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KCiA8Zz4KICA8dGl0bGU+TGF5ZXIgMTwvdGl0bGU+CiAgPHBhdGggaWQ9InN2Z18xNCIgZmlsbD0iIzYyNGFmZiIgZD0ibTAsODkuODRsMjUuNjUsMGwwLDI1LjY0OTk5bC0yNS42NSwwbDAsLTI1LjY0OTk5eiIvPgogIDxwYXRoIGlkPSJzdmdfMTUiIGZpbGw9IiM2MjRhZmYiIGQ9Im05OS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/2025/02/dbef8b07ea3d316006d9c22765c3cd53_1740104342584.svg
[compshare-link]: https://www.compshare.cn/images-detail?ImageID=compshareImage-17jacgm4ju16&ytag=HG_GPU_HivisionIDPhotos

---

## File: README_JP.md

> **関連プロジェクト**：
>
> - [SwanLab](https://github.com/SwanHubX/SwanLab)：人物切り抜きモデルの訓練を通じて、分析と監視、ラボの仲間との協力と交流を行い、訓練効率を大幅に向上させました。



# 目次

- [最近の更新](#-最近の更新)
- [プロジェクト概要](#-プロジェクト概要)
- [コミュニティ](#-コミュニティ)
- [準備作業](#-準備作業)
- [デモの起動](#-デモの起動)
- [Python推論](#-python推論)
- [APIサービスのデプロイ](#️-APIサービスのデプロイ)
- [Dockerデプロイ](#-dockerデプロイ)
- [お問い合わせ](#-お問い合わせ)
- [貢献者](#貢献者)



# 🤩 最近の更新

- オンライン体験： [](https://swanhub.co/ZeYiLin/HivisionIDPhotos/demo)、[](https://huggingface.co/spaces/TheEeeeLin/HivisionIDPhotos)、[![][modelscope-shield]][modelscope-link]、[![][compshare-shield]][compshare-link]

- 2024.11.20: Gradioデモに**印刷レイアウト**オプションを追加、六つ切り、五つ切り、A4、3R、4Rレイアウトサイズをサポート
- 2024.11.16: APIインターフェースに美顔効果パラメータを追加
- 2024.09.24: APIインターフェースにbase64画像入力オプションを追加 | Gradioデモに**レイアウト写真トリミングライン**機能を追加
- 2024.09.22: Gradioデモに**ビーストモード**と**DPI**パラメータを追加
- 2024.09.18: Gradioデモに**テンプレート写真の共有**機能を追加、**米国式**背景オプションを追加
- 2024.09.17: Gradioデモに**カスタム底色-HEX入力**機能を追加 | **（コミュニティ貢献）C++バージョン** - [HivisionIDPhotos-cpp](https://github.com/zjkhahah/HivisionIDPhotos-cpp) 貢献 by [zjkhahah](https://github.com/zjkhahah)
- 2024.09.16: Gradioデモに**顔回転対応**機能を追加、カスタムサイズ入力に**ミリメートル**をサポート



# プロジェクト概要

> 🚀 私たちの仕事に興味を持っていただきありがとうございます。画像分野における他の成果もぜひご覧ください。お問い合わせは、zeyi.lin@swanhub.co まで。

HivisionIDPhotoは、実用的で体系的な証明写真のスマート制作アルゴリズムを開発することを目的としています。

さまざまなユーザー撮影シーンの認識、切り抜きおよび証明写真の生成を実現するために、一連の洗練されたAIモデル作業フローを利用しています。

**HivisionIDPhotoは以下のことができます：**

1. 軽量切り抜き（完全オフラインで、**CPU**のみで迅速に推論可能）
2. 異なるサイズ仕様に基づいて異なる標準証明写真、六寸レイアウト写真を生成
3. 完全オフラインまたはエッジクラウド推論をサポート
4. 美顔（待機中）
5. スマートな正装変更（待機中）



---

HivisionIDPhotoがあなたに役立つ場合は、このリポジトリをスターしたり、友人に推薦したりして、証明写真の緊急制作の問題を解決してください！



# 🏠 コミュニティ

私たちは、コミュニティによって構築されたHivisionIDPhotosの興味深いアプリケーションや拡張機能をいくつか共有しています：

- [HivisionIDPhotos-ComfyUI](https://github.com/AIFSH/HivisionIDPhotos-ComfyUI)：ComfyUI証明写真処理ワークフロー、[AIFSH](https://github.com/AIFSH/HivisionIDPhotos-ComfyUI)によって構築 

[](https://github.com/AIFSH/HivisionIDPhotos-ComfyUI)

- [HivisionIDPhotos-wechat-weapp](https://github.com/no1xuan/HivisionIDPhotos-wechat-weapp)：WeChat証明写真ミニプログラム、HivisionIDphotosアルゴリズムに基づく、[no1xuan](https://github.com/no1xuan)による貢献

[](https://github.com/no1xuan/HivisionIDPhotos-wechat-weapp)

- [HivisionIDPhotos-Uniapp](https://github.com/soulerror/HivisionIDPhotos-Uniapp)：基本のuniapp証明写真ミニプログラムの前部、HivisionIDphotosアルゴリズムに基づく、[soulerror](https://github.com/soulerror)による貢献

[](https://github.com/soulerror/HivisionIDPhotos-Uniapp)

- [HivisionIDPhotos-cpp](https://github.com/zjkhahah/HivisionIDPhotos-cpp)：HivisionIDphotos C++バージョン、[zjkhahah](https://github.com/zjkhahah)によって構築
- [HivisionIDPhotos-windows-GUI](https://github.com/zhaoyun0071/HivisionIDPhotos-windows-GUI)：Windowsクライアントアプリケーション、[zhaoyun0071](https://github.com/zhaoyun0071)によって構築
- [HivisionIDPhotos-NAS](https://github.com/ONG-Leo/HivisionIDPhotos-NAS)：Synology NAS導入の中国語チュートリアル、[ONG-Leo](https://github.com/ONG-Leo)による貢献



# 🔧 準備作業

環境のインストールと依存関係：
- Python >= 3.7（プロジェクトは主にpython 3.10でテストされています）
- OS: Linux, Windows, MacOS

## 1. プロジェクトをクローンする

```bash
git clone https://github.com/Zeyi-Lin/HivisionIDPhotos.git
cd  HivisionIDPhotos
```

## 2. 依存環境をインストールする

> condaでpython3.10の仮想環境を作成することをお勧めします。その後、以下のコマンドを実行してください。

```bash
pip install -r requirements.txt
pip install -r requirements-app.txt
```

## 3. 重みファイルをダウンロードする

**方法一：スクリプトでダウンロード**

```bash
python scripts/download_model.py --models all
```

**方法二：直接ダウンロード**

プロジェクトの`hivision/creator/weights`ディレクトリに保存します：
- `modnet_photographic_portrait_matting.onnx` (24.7MB): [MODNet](https://github.com/ZHKKKe/MODNet)公式の重み、[ダウンロード](https://github.com/Zeyi-Lin/HivisionIDPhotos/releases/download/pretrained-model/modnet_photographic_portrait_matting.onnx)
- `hivision_modnet.onnx` (24.7MB): 単色背景に対して適応性の高い切り抜きモデル、[ダウンロード](https://github.com/Zeyi-Lin/HivisionIDPhotos/releases/download/pretrained-model/hivision_modnet.onnx)
- `rmbg-1.4.onnx` (176.2MB): [BRIA AI](https://huggingface.co/briaai/RMBG-1.4)のオープンソース切り抜きモデル、[ダウンロード](https://huggingface.co/briaai/RMBG-1.4/resolve/main/onnx/model.onnx?download=true)後に`rmbg-1.4.onnx`にリネーム
- `birefnet-v1-lite.onnx`(224MB): [ZhengPeng7](https://github.com/ZhengPeng7/BiRefNet)のオープンソース切り抜きモデル、[ダウンロード](https://github.com/ZhengPeng7/BiRefNet/releases/download/v1/BiRefNet-general-bb_swin_v1_tiny-epoch_232.onnx)後に`birefnet-v1-lite.onnx`にリネーム

## 4. 顔検出モデルの設定（オプション）

| 拡張顔検出モデル | 説明 | 使用文書 |
| -- | -- | -- |
| MTCNN | **オフライン**顔検出モデル、高性能CPU推論、デフォルトモデル、検出精度は低い | このプロジェクトをクローン後、直接使用 |
| Face++ | Megviiが提供するオンライン顔検出API、高精度の検出、[公式文書](https://console.faceplusplus.com.cn/documents/4888373) | [使用文書](docs/face++_EN.md)|

## 5. パフォーマンスリファレンス

> テスト環境はMac M1 Max 64GB、非GPU加速、テスト画像の解像度は512x715(1)と764×1146(2)。

| モデルの組み合わせ | メモリ使用量 | 推論時間(1) | 推論時間(2) |
| -- | -- | -- | -- |
| MODNet + mtcnn | 410MB | 0.207秒 | 0.246秒 |
| MODNet + retinaface | 405MB | 0.571秒 | 0.971秒 |
| birefnet-v1-lite + retinaface | 6.20GB | 7.063秒 | 7.128秒 |

## 6. GPU推論の加速（オプション）

現在のバージョンでは、NVIDIA GPUで加速可能なモデルは`birefnet-v1-lite`です。約16GBのVRAMが必要であることにご注意ください。

NVIDIA GPUを使用して推論を加速したい場合は、CUDAとcuDNNがインストールされていることを確認した上で、[onnxruntime-gpuのドキュメント](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#cuda-12x)に従って適切な`onnxruntime-gpu`バージョンをインストールし、[PyTorchの公式サイト](https://pytorch.org/get-started/locally/)から適切な`pytorch`バージョンをインストールしてください。

```bash
# もしコンピュータにCUDA 12.xとcuDNN 8がインストールされている場合
# torchのインストールは任意です。cuDNNが設定できない場合は、torchを試してみてください
pip install onnxruntime-gpu==1.18.0
pip install torch --index-url https://download.pytorch.org/whl/cu121
```

インストールが完了したら、`birefnet-v1-lite`モデルを呼び出してGPU加速推論を利用します。

> TIPS: CUDAのインストールは下位互換性があります。たとえば、CUDAのバージョンが12.6で、torchが現在対応している最高バージョンが12.4である場合、コンピュータに12.4のバージョンをインストールすることも可能です。



# 🚀 デモの起動

```bash
python app.py
```

プログラムを実行すると、ローカルWebページが生成され、ページ内で証明写真の操作と対話が可能になります。





# 🚀 Python推論

核心パラメータ：

- `-i`: 入力画像のパス
- `-o`: 保存画像のパス
- `-t`: 推論タイプ、idphoto、human_matting、add_background、generate_layout_photosから選択可能
- `--matting_model`: 人物切り抜きモデルの重み選択
- `--face_detect_model`: 顔検出モデルの選択

詳細なパラメータは`python inference.py --help`で確認できます。

## 1. 証明写真の作成

1枚の写真を入力し、1枚の標準証明写真と1枚の高解像度証明写真の4チャンネル透明PNGを取得します。

```python
python inference.py -i demo/images/test0.jpg -o ./idphoto.png --height 413 --width 295
```

## 2. 人物切り抜き

1枚の写真を入力し、1枚の4チャンネル透明PNGを取得します。

```python
python inference.py -t human_matting -i demo/images/test0.jpg -o ./idphoto_matting.png --matting_model hivision_modnet
```

## 3. 透明画像に背景色を追加

1枚の4チャンネル透明PNGを入力し、背景色を追加した3チャンネル画像を取得します。

```python
python inference.py -t add_background -i ./idphoto.png -o ./idphoto_ab.jpg -c 4f83ce -k 30 -r 1
```

## 4. 六寸レイアウト写真の取得

1枚の3チャンネル写真を入力し、1枚の六寸レイアウト写真を取得します。

```python
python inference.py -t generate_layout_photos -i ./idphoto_ab.jpg -o ./idphoto_layout.jpg --height 413 --width 295 -k 200
```

## 5. 証明写真のトリミング

1枚の4チャンネル写真（切り抜き済みの画像）を入力し、1枚の標準証明写真と1枚の高解像度証明写真の4チャンネル透明PNGを取得します。

```python
python inference.py -t idphoto_crop -i ./idphoto_matting.png -o ./idphoto_crop.png --height 413 --width 295
```



# ⚡️ APIサービスのデプロイ

## バックエンドを起動

```
python deploy_api.py
```

## APIサービスにリクエスト

詳細なリクエスト方法は[APIドキュメント](docs/api_EN.md)を参照してください。以下のリクエスト例が含まれます：
- [cURL](docs/api_EN.md#curl-request-examples)
- [Python](docs/api_EN.md#python-request-example)



# 🐳 Dockerデプロイ

## 1. イメージをプルまたはビルドする

> 以下の方法から3つを選択してください。

**方法一：最新のイメージをプル：**

```bash
docker pull linzeyi/hivision_idphotos
```

**方法二：Dockerfileから直接イメージをビルド：**

`hivision/creator/weights` ディレクトリに少なくとも1つの[マスキングモデルの重みファイル](#3-重みファイルのダウンロード)があることを確認してから、プロジェクトのルートディレクトリで以下を実行してください：

```bash
docker build -t linzeyi/hivision_idphotos .
```

**方法三：Docker composeでビルド：**

`hivision/creator/weights` ディレクトリに少なくとも1つの[マスキングモデルの重みファイル](#3-重みファイルのダウンロード)があることを確認してから、プロジェクトのルートディレクトリで以下を実行してください：

```bash
docker compose build
```

## 2. サービスを実行

**Gradioデモサービスを起動**

次のコマンドを実行し、ローカルで [http://127.0.0.1:7860](http://127.0.0.1:7860/) にアクセスすると使用可能です。

```bash
docker run -d -p 7860:7860 linzeyi/hivision_idphotos
```

**APIバックエンドサービスを起動**

```bash
docker run -d -p 8080:8080 linzeyi/hivision_idphotos python3 deploy_api.py
```

**2つのサービスを同時に起動**

```bash
docker compose up -d
```

## 環境変数

本プロジェクトは、いくつかの追加設定項目を提供し、環境変数を使用して設定します：

| 環境変数 | タイプ	| 説明 | 例 |
|--|--|--|--|
| FACE_PLUS_API_KEY	 | オプション	| これはFace++コンソールで申請したAPIキーです。	 | `7-fZStDJ····` |
| FACE_PLUS_API_SECRET	 | オプション	| Face++ APIキーに対応するSecret | `VTee824E····` |

dockerでの環境変数使用例：
```bash
docker run  -d -p 7860:7860 \
    -e FACE_PLUS_API_KEY=7-fZStDJ···· \
    -e FACE_PLUS_API_SECRET=VTee824E···· \
    linzeyi/hivision_idphotos 
```



# 📖 プロジェクトの引用

1. MTCNN:

```bibtex
@software{ipazc_mtcnn_2021,
    author = {ipazc},
    title = {{MTCNN}},
    url = {https://github.com/ipazc/mtcnn},
    year = {2021},
    publisher = {GitHub}
}
```

2. ModNet:

```bibtex
@software{zhkkke_modnet_2021,
    author = {ZHKKKe},
    title = {{ModNet}},
    url = {https://github.com/ZHKKKe/MODNet},
    year = {2021},
    publisher = {GitHub}
}
```



# よくある質問 (FAQ)

## 1. 基本的なサイズと色をどのように変更しますか？

- サイズ: [size_list_EN.csv](demo/assets/size_list_EN.csv) ファイルを修正した後、`app.py`を再実行すれば大丈夫です。最初の列はサイズ名、二番目の列は高さ、三番目の列は幅です。
- 色: [color_list_EN.csv](demo/assets/color_list_EN.csv) ファイルを修正した後、`app.py`を再実行すれば大丈夫です。最初の列は色名、二番目の列はHex値です。

## 2. ウォーターマークのフォントをどのように変更しますか？

1. フォントファイルを`hivision/plugin/font`フォルダーに置きます。
2. `hivision/plugin/watermark.py`ファイル内の`font_file`パラメータの値をフォントファイル名に変更します。

## 3. ソーシャルメディアのテンプレート画像をどのように追加しますか？

1. テンプレート画像を`hivision/plugin/template/assets`フォルダーに置きます。テンプレート画像は4チャンネルの透明PNGです。
2. `hivision/plugin/template/assets/template_config.json`ファイルに最新のテンプレート情報を追加します。ここで`width`はテンプレート画像の幅(px)、`height`はテンプレート画像の高さ(px)、`anchor_points`はテンプレートの透明領域の4つの隅の座標(px)です。`rotation`は透明領域の垂直方向に対する回転角度で、>0は反時計回り、<0は時計回りです。
3. `demo/processor.py`の`_generate_image_template`関数内の`TEMPLATE_NAME_LIST`変数に最新のテンプレート名を追加します。



## 4. Gradio Demoの上部ナビゲーションバーをどのように変更しますか？

- `demo/assets/title.md`ファイルを修正します。



# 📧 お問い合わせ

ご不明な点がございましたら、zeyi.lin@swanhub.coまでメールをお送りください。



# 貢献者

<a href="https://github.com/Zeyi-Lin/HivisionIDPhotos/graphs/contributors">
  
</a>

[Zeyi-Lin](https://github.com/Zeyi-Lin)、[SAKURA-CAT](https://github.com/SAKURA-CAT)、[Feudalman](https://github.com/Feudalman)、[swpfY](https://github.com/swpfY)、[Kaikaikaifang](https://github.com/Kaikaikaifang)、[ShaohonChen](https://github.com/ShaohonChen)、[KashiwaByte](https://github.com/KashiwaByte)



# Thanks for support

[](https://github.com/Zeyi-Lin/HivisionIDPhotos/stargazers)

[](https://github.com/Zeyi-Lin/HivisionIDPhotos/network/members)

[](https://star-history.com/#Zeyi-Lin/HivisionIDPhotos&Date)



# Lincese

This repository is licensed under the [Apache-2.0 License](LICENSE).

[github-stars-shield]: https://img.shields.io/github/stars/zeyi-lin/hivisionidphotos?color=ffcb47&labelColor=black&style=flat-square
[github-stars-link]: https://github.com/zeyi-lin/hivisionidphotos/stargazers

[swanhub-demo-shield]: https://swanhub.co/git/repo/SwanHub%2FAuto-README/file/preview?ref=main&path=swanhub.svg
[swanhub-demo-link]: https://swanhub.co/ZeYiLin/HivisionIDPhotos/demo

[spaces-shield]: https://img.shields.io/badge/🤗-Open%20in%20Spaces-blue
[spaces-link]: https://huggingface.co/spaces/TheEeeeLin/HivisionIDPhotos


[wechat-shield]: https://img.shields.io/badge/WeChat-微信-4cb55e
[wechat-link]: https://docs.qq.com/doc/DUkpBdk90eWZFS2JW


[release-shield]: https://img.shields.io/github/v/release/zeyi-lin/hivisionidphotos?color=369eff&labelColor=black&logo=github&style=flat-square
[release-link]: https://github.com/zeyi-lin/hivisionidphotos/releases

[license-shield]: https://img.shields.io/badge/license-apache%202.0-white?labelColor=black&style=flat-square
[license-link]: https://github.com/Zeyi-Lin/HivisionIDPhotos/blob/master/LICENSE

[github-issues-shield]: https://img.shields.io/github/issues/zeyi-lin/hivisionidphotos?color=ff80eb&labelColor=black&style=flat-square
[github-issues-link]: https://github.com/zeyi-lin/hivisionidphotos/issues

[dockerhub-shield]: https://img.shields.io/docker/v/linzeyi/hivision_idphotos?color=369eff&label=docker&labelColor=black&logoColor=white&style=flat-square
[dockerhub-link]: https://hub.docker.com/r/linzeyi/hivision_idphotos/tags

[trendshift-shield]: https://trendshift.io/api/badge/repositories/11622
[trendshift-link]: https://trendshift.io/repositories/11622

[hellogithub-shield]: https://abroad.hellogithub.com/v1/widgets/recommend.svg?rid=8ea1457289fb4062ba661e5299e733d6&claim_uid=Oh5UaGjfrblg0yZ
[hellogithub-link]: https://hellogithub.com/repository/8ea1457289fb4062ba661e5299e733d6

[github-contributors-shield]: https://img.shields.io/github/contributors/zeyi-lin/hivisionidphotos?color=c4f042&labelColor=black&style=flat-square
[github-contributors-link]: https://github.com/zeyi-lin/hivisionidphotos/graphs/contributors

[github-forks-shield]: https://img.shields.io/github/forks/zeyi-lin/hivisionidphotos?color=8ae8ff&labelColor=black&style=flat-square
[github-forks-link]: https://github.com/zeyi-lin/hivisionidphotos/network/members

[modelscope-shield]: https://img.shields.io/badge/Demo_on_ModelScope-purple?logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjIzIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KCiA8Zz4KICA8dGl0bGU+TGF5ZXIgMTwvdGl0bGU+CiAgPHBhdGggaWQ9InN2Z18xNCIgZmlsbD0iIzYyNGFmZiIgZD0ibTAsODkuODRsMjUuNjUsMGwwLDI1LjY0OTk5bC0yNS42NSwwbDAsLTI1LjY0OTk5eiIvPgogIDxwYXRoIGlkPSJzdmdfMTUiIGZpbGw9IiM2MjRhZmYiIGQ9Im05OS4xNCwxMTUuNDlsMjUuNjUsMGwwLDI1LjY1bC0yNS42NSwwbDAsLTI1LjY1eiIvPgogIDxwYXRoIGlkPSJzdmdfMTYiIGZpbGw9IiM2MjRhZmYiIGQ9Im0xNzYuMDksMTQxLjE0bC0yNS42NDk5OSwwbDAsMjIuMTlsNDcuODQsMGwwLC00Ny44NGwtMjIuMTksMGwwLDI1LjY1eiIvPgogIDxwYXRoIGlkPSJzdmdfMTciIGZpbGw9IiMzNmNmZDEiIGQ9Im0xMjQuNzksODkuODRsMjUuNjUsMGwwLDI1LjY0OTk5bC0yNS42NSwwbDAsLTI1LjY0OTk5eiIvPgogIDxwYXRoIGlkPSJzdmdfMTgiIGZpbGw9IiMzNmNmZDEiIGQ9Im0wLDY0LjE5bDI1LjY1LDBsMCwyNS42NWwtMjUuNjUsMGwwLC0yNS42NXoiLz4KICA8cGF0aCBpZD0ic3ZnXzE5IiBmaWxsPSIjNjI0YWZmIiBkPSJtMTk4LjI4LDg5Ljg0bDI1LjY0OTk5LDBsMCwyNS42NDk5OWwtMjUuNjQ5OTksMGwwL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Ljg3OTkgMzEuNTU3Nkg0NC42OTkyVjQ3LjMzNjNINjAuODc5OVYzMS41NTc2WiIgZmlsbD0iI0RFMDQyOSIvPgo8cGF0aCBkPSJNNzkuNjIwMSAzMS41NTc2SDYzLjQzOTVWNDcuMzM2M0g3OS42MjAxVjMxLjU1NzZaIiBmaWxsPSIjREUwNDI5Ii8+CjxwYXRoIGQ9Ik0xMTUuODI1IDMxLjU1NzZIOTkuNjQ0NVY0Ny4zMzYzSDExNS44MjVWMzEuNTU3NloiIGZpbGw9IiNERTA0MjkiLz4KPHBhdGggZD0iTTcwLjI1NDkgNDcuMzM1OUg1NC4wNzQyVjYzLjExNDdINzAuMjU0OVY0Ny4zMzU5WiIgZmlsbD0iI0RFMDQyOSIvPgo8L3N2Zz4=&labelColor=white
[modelers-link]: https://modelers.cn/spaces/SwanLab/HivisionIDPhotos

[compshare-shield]: https://www-s.ucloud.cn/2025/02/dbef8b07ea3d316006d9c22765c3cd53_1740104342584.svg
[compshare-link]: https://www.compshare.cn/images-detail?ImageID=compshareImage-17jacgm4ju16&ytag=HG_GPU_HivisionIDPhotos

---

## File: README_KO.md

> **관련 프로젝트**：
>
> - [SwanLab](https://github.com/SwanHubX/SwanLab)：인물 컷아웃 모델의 훈련을 통해, 분석과 감시, 연구실 동료들과의 협력 및 교류를 진행하여 훈련 효율성을 크게 향상시켰습니다.



# 목차

- [최근 업데이트](#-최근-업데이트)
- [프로젝트 개요](#-프로젝트-개요)
- [커뮤니티](#-커뮤니티)
- [준비 작업](#-준비-작업)
- [데모 실행](#-데모-실행)
- [Python 추론](#-python-추론)
- [API 서비스 배포](#️-API-서비스-배포)
- [Docker 배포](#-docker-배포)
- [문의하기](#-문의하기)
- [기여자](#기여자)



# 🤩 최근 업데이트

- 온라인 체험: [](https://swanhub.co/ZeYiLin/HivisionIDPhotos/demo)、[](https://huggingface.co/spaces/TheEeeeLin/HivisionIDPhotos)、[![][modelscope-shield]][modelscope-link]、[![][compshare-shield]][compshare-link]

- 2024.11.20: Gradio 데모에 **인쇄 레이아웃** 옵션 추가, 6인치, 5인치, A4, 3R, 4R 레이아웃 크기 지원
- 2024.11.16: API 인터페이스에 뷰티 효과 매개변수 추가
- 2024.09.24: API 인터페이스에 base64 이미지 입력 옵션 추가 | Gradio 데모에 **레이아웃 사진 자르기 선** 기능 추가
- 2024.09.22: Gradio Demo에 **버스트 모드** 및 **DPI** 매개변수 추가
- 2024.09.18: Gradio Demo에 **템플릿 사진 공유** 기능 추가, **미국식** 배경 옵션 추가
- 2024.09.17: Gradio Demo에 **커스텀 배경색-HEX 입력** 기능 추가 | **(커뮤니티 기여) C++ 버전** - [HivisionIDPhotos-cpp](https://github.com/zjkhahah/HivisionIDPhotos-cpp) 기여 by [zjkhahah](https://github.com/zjkhahah)
- 2024.09.16: Gradio Demo에 **얼굴 회전 정렬** 기능 추가, 커스텀 사이즈 입력에 **밀리미터** 단위 추가



# 프로젝트 개요

> 🚀 우리의 작업에 관심을 가져 주셔서 감사합니다. 이미지 분야의 다른 성과도 꼭 확인해 주시기 바랍니다. 문의는 zeyi.lin@swanhub.co로 해주세요.

HivisionIDPhoto는 실용적이고 체계적인 증명사진의 스마트 제작 알고리즘을 개발하는 것을 목표로 합니다.

다양한 사용자 촬영 장면의 인식, 컷아웃 및 증명사진 생성을 실현하기 위해 일련의 세련된 AI 모델 작업 흐름을 활용하고 있습니다.

**HivisionIDPhoto는 다음과 같은 기능을 제공합니다:**

1. 경량 컷아웃 (완전 오프라인에서, **CPU**만으로 신속한 추론 가능)
2. 다양한 사이즈 사양에 따라 다양한 표준 증명사진, 육寸 레이아웃 사진 생성
3. 완전 오프라인 또는 엣지 클라우드 추론 지원
4. 미용 (대기 중)
5. 스마트한 정장 변경 (대기 중)



---

HivisionIDPhoto가 여러분에게 도움이 된다면, 이 리포지토리를 스타하거나 친구에게 추천하여 증명사진의 긴급 제작 문제를 해결해 주세요!



# 🏠 커뮤니티

우리는 커뮤니티에 의해 구축된 HivisionIDPhotos의 흥미로운 애플리케이션 및 확장 기능을 몇 가지 공유합니다:

- [HivisionIDPhotos-ComfyUI](https://github.com/AIFSH/HivisionIDPhotos-ComfyUI): ComfyUI 증명사진 처리 워크플로우, [AIFSH](https://github.com/AIFSH/HivisionIDPhotos-ComfyUI)가 구축

[](https://github.com/AIFSH/HivisionIDPhotos-ComfyUI)

- [HivisionIDPhotos-wechat-weapp](https://github.com/no1xuan/HivisionIDPhotos-wechat-weapp): WeChat 증명사진 미니 프로그램, HivisionIDphotos 알고리즘 기반, [no1xuan](https://github.com/no1xuan)이 기여

[](https://github.com/no1xuan/HivisionIDPhotos-wechat-weapp)

- [HivisionIDPhotos-Uniapp](https://github.com/soulerror/HivisionIDPhotos-Uniapp): 기본 uniapp 증명사진 미니 프로그램 전면, HivisionIDphotos 알고리즘 기반, [soulerror](https://github.com/soulerror)이 기여

[](https://github.com/soulerror/HivisionIDPhotos-Uniapp)

- [HivisionIDPhotos-cpp](https://github.com/zjkhahah/HivisionIDPhotos-cpp): HivisionIDphotos C++ 버전, [zjkhahah](https://github.com/zjkhahah)이 구축
- [HivisionIDPhotos-windows-GUI](https://github.com/zhaoyun0071/HivisionIDPhotos-windows-GUI): Windows 클라이언트 애플리케이션, [zhaoyun0071](https://github.com/zhaoyun0071)이 구축
- [HivisionIDPhotos-NAS](https://github.com/ONG-Leo/HivisionIDPhotos-NAS): Synology NAS 배포 중국어 튜토리얼, [ONG-Leo](https://github.com/ONG-Leo)가 기여




# 🔧 준비 작업

환경 설치 및 의존성:
- Python >= 3.7 (프로젝트는 주로 python 3.10으로 테스트되었습니다)
- OS: Linux, Windows, MacOS

## 1. 프로젝트 클론하기

```bash
git clone https://github.com/Zeyi-Lin/HivisionIDPhotos.git
cd  HivisionIDPhotos
```

## 2. 의존 환경 설치하기

> conda로 python3.10 가상 환경을 만드는 것을 권장합니다. 그 후, 아래의 명령어를 실행해 주세요.

```bash
pip install -r requirements.txt
pip install -r requirements-app.txt
```

## 3. 가중치 파일 다운로드하기

**방법 1: 스크립트를 통해 다운로드**

```bash
python scripts/download_model.py --models all
```

**방법 2: 직접 다운로드**

프로젝트의 `hivision/creator/weights` 디렉토리에 저장합니다:
- `modnet_photographic_portrait_matting.onnx` (24.7MB): [MODNet](https://github.com/ZHKKKe/MODNet) 공식 가중치, [다운로드](https://github.com/Zeyi-Lin/HivisionIDPhotos/releases/download/pretrained-model/modnet_photographic_portrait_matting.onnx)
- `hivision_modnet.onnx` (24.7MB): 단색 배경에 적응성이 높은 컷아웃 모델, [다운로드](https://github.com/Zeyi-Lin/HivisionIDPhotos/releases/download/pretrained-model/hivision_modnet.onnx)
- `rmbg-1.4.onnx` (176.2MB): [BRIA AI](https://huggingface.co/briaai/RMBG-1.4)의 오픈 소스 컷아웃 모델, [다운로드](https://huggingface.co/briaai/RMBG-1.4/resolve/main/onnx/model.onnx?download=true) 후에 `rmbg-1.4.onnx`로 이름 변경
- `birefnet-v1-lite.onnx`(224MB): [ZhengPeng7](https://github.com/ZhengPeng7/BiRefNet)의 오픈 소스 컷아웃 모델, [다운로드](https://github.com/ZhengPeng7/BiRefNet/releases/download/v1/BiRefNet-general-bb_swin_v1_tiny-epoch_232.onnx) 후에 `birefnet-v1-lite.onnx`로 이름 변경

## 4. 얼굴 검출 모델 설정하기 (선택 사항)

| 확장 얼굴 검출 모델 | 설명 | 사용 문서 |
| -- | -- | -- |
| MTCNN | **오프라인** 얼굴 검출 모델, 고성능 CPU 추론, 기본 모델, 검출 정확도가 낮음 | 이 프로젝트를 클론한 후 직접 사용 |
| Face++ | Megvii에서 제공하는 온라인 얼굴 검출 API, 고정밀 검출, [공식 문서](https://console.faceplusplus.com.cn/documents/4888373) | [사용 문서](docs/face++_EN.md)|

## 5. 성능 참조

> 테스트 환경은 Mac M1 Max 64GB, 비GPU 가속, 테스트 이미지 해상도는 512x715(1) 및 764×1146(2)입니다.

| 모델 조합 | 메모리 사용량 | 추론 시간(1) | 추론 시간(2) |
| -- | -- | -- | -- |
| MODNet + mtcnn | 410MB | 0.207초 | 0.246초 |
| MODNet + retinaface | 405MB | 0.571초 | 0.971초 |
| birefnet-v1-lite + retinaface | 6.20GB | 7.063초 | 7.128초 |

## 6. GPU 추론 가속 (선택 사항)

현재 버전에서 NVIDIA GPU로 가속화할 수 있는 모델은 `birefnet-v1-lite`입니다. 약 16GB의 VRAM이 필요합니다.

NVIDIA GPU를 사용하여 추론을 가속화하려면, CUDA와 cuDNN이 설치되어 있는지 확인한 후, [onnxruntime-gpu 문서](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#cuda-12x)에서 해당하는 `onnxruntime-gpu` 버전을 찾아 설치하고, [PyTorch 공식 웹사이트](https://pytorch.org/get-started/locally/)에서 해당하는 `pytorch` 버전을 찾아 설치하세요.

```bash
# 컴퓨터에 CUDA 12.x와 cuDNN 8이 설치되어 있는 경우
# 설치 중 torch를 설치하는 것은 선택 사항입니다. cuDNN을 설정할 수 없는 경우 torch를 설치해 보세요.
pip install onnxruntime-gpu==1.18.0
pip install torch --index-url https://download.pytorch.org/whl/cu121
```

설치 완료 후, `birefnet-v1-lite` 모델을 호출하면 GPU에 의한 추론 가속이 이용됩니다.

> TIPS: CUDA 설치는 하위 호환성이 있습니다. 예를 들어, CUDA 버전이 12.6이고, torch가 현재 지원하는 최대 버전이 12.4인 경우, 컴퓨터에 12.4 버전을 설치할 수 있습니다.



# 🚀 데모 실행

```bash
python app.py
```

프로그램을 실행하면 로컬 웹 페이지가 생성되어 페이지 내에서 증명사진의 조작 및 상호작용이 가능합니다.





# 🚀 Python 추론

핵심 매개변수:

- `-i`: 입력 이미지 경로
- `-o`: 저장 이미지 경로
- `-t`: 추론 유형, idphoto, human_matting, add_background, generate_layout_photos 중 선택
- `--matting_model`: 인물 마스크 모델 가중치 선택
- `--face_detect_model`: 얼굴 감지 모델 선택

더 많은 매개변수는 `python inference.py --help`를 통해 확인할 수 있습니다.

## 1. 증명사진 제작

1장의 사진을 입력하여 1장의 표준 증명사진과 1장의 고화질 증명사진의 4채널 투명 PNG를 얻습니다.

```python
python inference.py -i demo/images/test0.jpg -o ./idphoto.png --height 413 --width 295
```

## 2. 인물 마스크

1장의 사진을 입력하여 1장의 4채널 투명 PNG를 얻습니다.

```python
python inference.py -t human_matting -i demo/images/test0.jpg -o ./idphoto_matting.png --matting_model hivision_modnet
```

## 3. 투명 이미지에 배경색 추가

1장의 4채널 투명 PNG를 입력하여 1장의 배경색이 추가된 3채널 이미지를 얻습니다.

```python
python inference.py -t add_background -i ./idphoto.png -o ./idphoto_ab.jpg  -c 4f83ce -k 30 -r 1
```

## 4. 6인치 배치 사진 생성

1장의 3채널 사진을 입력하여 1장의 6인치 배치 사진을 얻습니다.

```python
python inference.py -t generate_layout_photos -i ./idphoto_ab.jpg -o ./idphoto_layout.jpg  --height 413 --width 295 -k 200
```

## 5. 증명사진 자르기

1장의 4채널 사진(마스크 처리된 이미지)을 입력하여 1장의 표준 증명사진과 1장의 고화질 증명사진의 4채널 투명 PNG를 얻습니다.

```python
python inference.py -t idphoto_crop -i ./idphoto_matting.png -o ./idphoto_crop.png --height 413 --width 295
```



# ⚡️ API 서비스 배포

## 백엔드 시작

```
python deploy_api.py
```

## API 서비스에 요청

자세한 요청 방법은 [API 문서](docs/api_EN.md)를 참조해 주세요. 아래의 요청 예시가 포함됩니다:
- [cURL](docs/api_EN.md#curl-request-examples)
- [Python](docs/api_EN.md#python-request-example)
- [Java](docs/api_EN.md#java-request-example)
- [Javascript](docs/api_EN.md#javascript-request-examples)



# 🐳 Docker 배포

## 1. 이미지 풀 또는 빌드하기

> 아래의 방법 중 3가지를 선택해 주세요.

**방법 1: 최신 이미지 풀하기:**

```bash
docker pull linzeyi/hivision_idphotos
```

**방법 2: Dockerfile에서 직접 이미지 빌드하기:**

`hivision/creator/weights` 디렉토리에 최소한 하나의 [마스킹 모델 가중치 파일](#3-가중치-파일-다운로드)이 있는지 확인한 후, 프로젝트 루트 디렉토리에서 다음을 실행하세요:

```bash
docker build -t linzeyi/hivision_idphotos .
```

**방법 3: Docker compose로 빌드하기:**

`hivision/creator/weights` 디렉토리에 최소한 하나의 [마스킹 모델 가중치 파일](#3-가중치-파일-다운로드)이 있는지 확인한 후, 프로젝트 루트 디렉토리에서 다음을 실행하세요:

```bash
docker compose build
```

## 2. 서비스 실행

**Gradio 데모 서비스를 시작합니다**

다음 명령어를 실행하여 로컬에서 [http://127.0.0.1:7860](http://127.0.0.1:7860/)에 접근하면 사용 가능합니다.

```bash
docker run -d -p 7860:7860 linzeyi/hivision_idphotos
```

**API 백엔드 서비스를 시작합니다**

```bash
docker run -d -p 8080:8080 linzeyi/hivision_idphotos python3 deploy_api.py
```

**두 개의 서비스를 동시에 시작합니다**

```bash
docker compose up -d
```

## 환경 변수

본 프로젝트는 몇 가지 추가 설정 항목을 제공하며, 환경 변수를 사용하여 설정합니다:

| 환경 변수 | 유형	| 설명 | 예 |
|--|--|--|--|
| FACE_PLUS_API_KEY	 | 선택 사항	| 이는 Face++ 콘솔에서 신청한 API 키입니다.	 | `7-fZStDJ····` |
| FACE_PLUS_API_SECRET	 | 선택 사항	| Face++ API 키에 대응하는 Secret | `VTee824E····` |

docker에서 환경 변수 사용 예:
```bash
docker run  -d -p 7860:7860 \
    -e FACE_PLUS_API_KEY=7-fZStDJ···· \
    -e FACE_PLUS_API_SECRET=VTee824E···· \
    linzeyi/hivision_idphotos 
```



# 📖 프로젝트 인용

1. MTCNN:

```bibtex
@software{ipazc_mtcnn_2021,
    author = {ipazc},
    title = {{MTCNN}},
    url = {https://github.com/ipazc/mtcnn},
    year = {2021},
    publisher = {GitHub}
}
```

2. ModNet:

```bibtex
@software{zhkkke_modnet_2021,
    author = {ZHKKKe},
    title = {{ModNet}},
    url = {https://github.com/ZHKKKe/MODNet},
    year = {2021},
    publisher = {GitHub}
}
```



# 자주 묻는 질문 (FAQ)

## 1. 기본 크기와 색상을 어떻게 수정하나요?

- 크기: [size_list_EN.csv](demo/assets/size_list_EN.csv) 파일을 수정한 후 `app.py`를 다시 실행하면 됩니다. 첫 번째 열은 크기 이름, 두 번째 열은 높이, 세 번째 열은 너비입니다.
- 색상: [color_list_EN.csv](demo/assets/color_list_EN.csv) 파일을 수정한 후 `app.py`를 다시 실행하면 됩니다. 첫 번째 열은 색상 이름, 두 번째 열은 Hex 값입니다.

## 2. 워터마크 글꼴을 어떻게 수정하나요?

1. 글꼴 파일을 `hivision/plugin/font` 폴더에 넣습니다.
2. `hivision/plugin/watermark.py` 파일에서 `font_file` 매개변수 값을 글꼴 파일 이름으로 수정합니다.

## 3. 소셜 미디어 템플릿 사진을 어떻게 추가하나요?

1. 템플릿 이미지를 `hivision/plugin/template/assets` 폴더에 넣습니다. 템플릿 이미지는 4채널 투명 PNG입니다.
2. `hivision/plugin/template/assets/template_config.json` 파일에 최신 템플릿 정보를 추가합니다. 여기서 `width`는 템플릿 이미지의 너비(px), `height`는 템플릿 이미지의 높이(px), `anchor_points`는 템플릿의 투명 영역 네 모서리의 좌표(px)입니다. `rotation`은 투명 영역의 수직 방향에 대한 회전 각도로, >0은 반시계 방향, <0은 시계 방향입니다.
3. `demo/processor.py`의 `_generate_image_template` 함수 내의 `TEMPLATE_NAME_LIST` 변수에 최신 템플릿 이름을 추가합니다.



## 4. Gradio Demo의 상단 내비게이션 바를 어떻게 수정하나요?

- `demo/assets/title.md` 파일을 수정합니다.



# 📧 문의하기

궁금한 점이 있으시면 zeyi.lin@swanhub.co로 이메일을 보내 주세요.



# 기여자

<a href="https://github.com/Zeyi-Lin/HivisionIDPhotos/graphs/contributors">
  
</a>

[Zeyi-Lin](https://github.com/Zeyi-Lin)、[SAKURA-CAT](https://github.com/SAKURA-CAT)、[Feudalman](https://github.com/Feudalman)、[swpfY](https://github.com/swpfY)、[Kaikaikaifang](https://github.com/Kaikaikaifang)、[ShaohonChen](https://github.com/ShaohonChen)、[KashiwaByte](https://github.com/KashiwaByte)



# Thanks for support

[](https://github.com/Zeyi-Lin/HivisionIDPhotos/stargazers)

[](https://github.com/Zeyi-Lin/HivisionIDPhotos/network/members)

[](https://star-history.com/#Zeyi-Lin/HivisionIDPhotos&Date)



# Lincese

This repository is licensed under the [Apache-2.0 License](LICENSE).

[github-stars-shield]: https://img.shields.io/github/stars/zeyi-lin/hivisionidphotos?color=ffcb47&labelColor=black&style=flat-square
[github-stars-link]: https://github.com/zeyi-lin/hivisionidphotos/stargazers

[swanhub-demo-shield]: https://swanhub.co/git/repo/SwanHub%2FAuto-README/file/preview?ref=main&path=swanhub.svg
[swanhub-demo-link]: https://swanhub.co/ZeYiLin/HivisionIDPhotos/demo

[spaces-shield]: https://img.shields.io/badge/🤗-Open%20in%20Spaces-blue
[spaces-link]: https://huggingface.co/spaces/TheEeeeLin/HivisionIDPhotos


[wechat-shield]: https://img.shields.io/badge/WeChat-微信-4cb55e
[wechat-link]: https://docs.qq.com/doc/DUkpBdk90eWZFS2JW


[release-shield]: https://img.shields.io/github/v/release/zeyi-lin/hivisionidphotos?color=369eff&labelColor=black&logo=github&style=flat-square
[release-link]: https://github.com/zeyi-lin/hivisionidphotos/releases

[license-shield]: https://img.shields.io/badge/license-apache%202.0-white?labelColor=black&style=flat-square
[license-link]: https://github.com/Zeyi-Lin/HivisionIDPhotos/blob/master/LICENSE

[github-issues-shield]: https://img.shields.io/github/issues/zeyi-lin/hivisionidphotos?color=ff80eb&labelColor=black&style=flat-square
[github-issues-link]: https://github.com/zeyi-lin/hivisionidphotos/issues

[dockerhub-shield]: https://img.shields.io/docker/v/linzeyi/hivision_idphotos?color=369eff&label=docker&labelColor=black&logoColor=white&style=flat-square
[dockerhub-link]: https://hub.docker.com/r/linzeyi/hivision_idphotos/tags

[trendshift-shield]: https://trendshift.io/api/badge/repositories/11622
[trendshift-link]: https://trendshift.io/repositories/11622

[hellogithub-shield]: https://abroad.hellogithub.com/v1/widgets/recommend.svg?rid=8ea1457289fb4062ba661e5299e733d6&claim_uid=Oh5UaGjfrblg0yZ
[hellogithub-link]: https://hellogithub.com/repository/8ea1457289fb4062ba661e5299e733d6

[github-contributors-shield]: https://img.shields.io/github/contributors/zeyi-lin/hivisionidphotos?color=c4f042&labelColor=black&style=flat-square
[github-contributors-link]: https://github.com/zeyi-lin/hivisionidphotos/graphs/contributors

[github-forks-shield]: https://img.shields.io/github/forks/zeyi-lin/hivisionidphotos?color=8ae8ff&labelColor=black&style=flat-square
[github-forks-link]: https://github.com/zeyi-lin/hivisionidphotos/network/members

[modelscope-shield]: https://img.shields.io/badge/Demo_on_ModelScope-purple?logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjIzIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KCiA8Zz4KICA8dGl0bGU+TGF5ZXIgMTwvdGl0bGU+CiAgPHBhdGggaWQ9InN2Z18xNCIgZmlsbD0iIzYyNGFmZiIgZD0ibTAsODkuODRsMjUuNjUsMGwwLDI1LjY0OTk5bC0yNS42NSwwbDAsLTI1LjY0OTk5eiIvPgogIDxwYXRoIGlkPSJzdmdfMTUiIGZpbGw9IiM2MjRhZmYiIGQ9Im05OS4xNCwxMTUuNDlsMjUuNjUsMGwwLDI1LjY1bC0yNS42NSwwbDAsLTI1LjY1eiIvPgogIDxwYXRoIGlkPSJzdmdfMTYiIGZpbGw9IiM2MjRhZmYiIGQ9Im0xNzYuMDksMTQxLjE0bC0yNS42NDk5OSwwbDAsMjIuMTlsNDcuODQsMGwwLC00Ny44NGwtMjIuMTksMGwwLDI1LjY1eiIvPgogIDxwYXRoIGlkPSJzdmdfMTciIGZpbGw9IiMzNmNmZDEiIGQ9Im0xMjQuNzksODkuODRsMjUuNjUsMGwwLDI1LjY0OTk5bC0yNS42NSwwbDAsLTI1LjY0OTk5eiIvPgogIDxwYXRoIGlkPSJzdmdfMTgiIGZpbGw9IiMzNmNmZDEiIGQ9Im0wLDY0LjE5bDI1LjY1LDBsMCwyNS42NWwtMjUuNjUsMGwwLC0yNS42NXoiLz4KICA8cGF0aCBpZD0ic3ZnXzE5IiBmaWxsPS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ZIOC40OTQxNFY0Ny4zMzYzSDI0LjY3NDhWMzEuNTU3NloiIGZpbGw9IiNERTA0MjkiLz4KPHBhdGggZD0iTTYwLjg3OTkgMzEuNTU3Nkg0NC42OTkyVjQ3LjMzNjNINjAuODc5OVYzMS41NTc2WiIgZmlsbD0iI0RFMDQyOSIvPgo8cGF0aCBkPSJNNzkuNjIwMSAzMS41NTc2SDYzLjQzOTVWNDcuMzM2M0g3OS42MjAxVjMxLjU1NzZaIiBmaWxsPSIjREUwNDI5Ii8+CjxwYXRoIGQ9Ik0xMTUuODI1IDMxLjU1NzZIOTkuNjQ0NVY0Ny4zMzYzSDExNS44MjVWMzEuNTU3NloiIGZpbGw9IiNERTA0MjkiLz4KPHBhdGggZD0iTTcwLjI1NDkgNDcuMzM1OUg1NC4wNzQyVjYzLjExNDdINzAuMjU0OVY0Ny4zMzU5WiIgZmlsbD0iI0RFMDQyOSIvPgo8L3N2Zz4=&labelColor=white
[modelers-link]: https://modelers.cn/spaces/SwanLab/HivisionIDPhotos

[compshare-shield]: https://www-s.ucloud.cn/2025/02/dbef8b07ea3d316006d9c22765c3cd53_1740104342584.svg
[compshare-link]: https://www.compshare.cn/images-detail?ImageID=compshareImage-17jacgm4ju16&ytag=HG_GPU_HivisionIDPhotos