File: README.md
相关项目:
- TRIO:一个新型的AI计算平台(Tinker Like),让模型训练者无需维护复杂GPU基础设施,在个人电脑就可以轻松做llm sft/rl训练,训推均按token计费而非GPU时,支持弹性扩展,同时开20个实验不再困难。
目录
🤩 最近更新
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 贡献 by zjkhahah
2024.09.16: Gradio Demo增加人脸旋转对齐功能,自定义尺寸输入支持毫米单位
项目简介
🚀 谢谢你对我们的工作感兴趣。您可能还想查看我们在图像领域的其他成果,欢迎来信:[email protected].
HivisionIDPhoto 旨在开发一种实用、系统性的证件照智能制作算法。
它利用一套完善的AI模型工作流程,实现对多种用户拍照场景的识别、抠图与证件照生成。
HivisionIDPhoto 可以做到:
- 轻量级抠图(纯离线,仅需 CPU 即可快速推理)
- 根据不同尺寸规格生成不同的标准证件照、六寸排版照
- 支持 纯离线 或 端云 推理
- 美颜
- 智能换正装(waiting)
如果 HivisionIDPhoto 对你有帮助,请 star 这个 repo 或推荐给你的朋友,解决证件照应急制作问题!
🏠 社区
我们分享了一些由社区构建的HivisionIDPhotos的有趣应用和扩展:
| HivisionIDPhotos-ComfyUI | HivisionIDPhotos-wechat-weapp |
|---|---|
| ComfyUI证件照处理工作流 | 证件照微信小程序(JAVA后端+原生前端) |
| HivisionIDPhotos-Uniapp | HivisionIDPhotos-web |
|---|---|
| 证件照微信小程序(uniapp) | 证件照应用网页版 |
- HivisionIDPhotos-cpp: HivisionIDphotos C++版本,由 zjkhahah 构建
- ai-idphoto: HivisionIDPhotos-wechat-weapp 的uniapp多端兼容版,由 wmlcjj 贡献
- HivisionIDPhotos-uniapp-WeChat-gpto1: 由gpt-o1辅助完成开发的证件照微信小程序,由 jkm199 贡献
- HivisionIDPhotos-windows-GUI:Windows客户端应用,由 zhaoyun0071 构建
- HivisionIDPhotos-NAS: 群晖NAS部署中文教程,由 ONG-Leo 贡献
🔧 准备工作
环境安装与依赖:
- Python >= 3.7(项目主要测试在 python 3.10)
- OS: Linux, Windows, MacOS
1. 克隆项目
git clone https://github.com/Zeyi-Lin/HivisionIDPhotos.git
cd HivisionIDPhotos2. 安装依赖环境
建议 conda 创建一个 python3.10 虚拟环境后,执行以下命令
pip install -r requirements.txt
pip install -r requirements-app.txt3. 下载人像抠图模型权重文件
方式一:脚本下载
python scripts/download_model.py --models all
# 如需指定下载某个模型
# python scripts/download_model.py --models modnet_photographic_portrait_matting方式二:直接下载
模型均存到项目的hivision/creator/weights目录下:
| 人像抠图模型 | 介绍 | 下载 |
|---|---|---|
| MODNet | MODNet官方权重 | 下载(24.7MB) |
| hivision_modnet | 对纯色换底适配性更好的抠图模型 | 下载(24.7MB) |
| rmbg-1.4 | BRIA AI 开源的抠图模型 | 下载(176.2MB)后重命名为rmbg-1.4.onnx |
| birefnet-v1-lite | ZhengPeng7 开源的抠图模型,拥有最好的分割精度 | 下载(224MB)后重命名为birefnet-v1-lite.onnx |
如果下载网速不顺利:前往SwanHub下载。
4. 人脸检测模型配置(可选)
| 拓展人脸检测模型 | 介绍 | 使用文档 |
|---|---|---|
| MTCNN | 离线人脸检测模型,高性能CPU推理(毫秒级),为默认模型,检测精度较低 | Clone此项目后直接使用 |
| RetinaFace | 离线人脸检测模型,CPU推理速度中等(秒级),精度较高 | 下载后放到hivision/creator/retinaface/weights目录下 |
| Face++ | 旷视推出的在线人脸检测API,检测精度较高,官方文档 | 使用文档 |
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与cuDNN后,根据onnxruntime-gpu文档找到对应的onnxruntime-gpu版本安装,以及根据pytorch官网找到对应的torch版本安装。
# 假如你的电脑安装的是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
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 inference.py -i demo/images/test0.jpg -o ./idphoto.png --height 413 --width 2952. 人像抠图
输入 1 张照片,获得 1张 4 通道透明 png
python inference.py -t human_matting -i demo/images/test0.jpg -o ./idphoto_matting.png --matting_model hivision_modnet3. 透明图增加底色
输入 1 张 4 通道透明 png,获得 1 张增加了底色的 3通道图像
python inference.py -t add_background -i ./idphoto.png -o ./idphoto_ab.jpg -c 4f83ce -k 30 -r 14. 得到六寸排版照
输入 1 张 3 通道照片,获得 1 张六寸排版照
python inference.py -t generate_layout_photos -i ./idphoto_ab.jpg -o ./idphoto_layout.jpg --height 413 --width 295 -k 2005. 证件照裁剪
输入 1 张 4 通道照片(抠图好的图像),获得 1 张标准证件照和 1 张高清证件照的 4 通道透明 png
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 文档,包含以下请求示例:
🐳 Docker 部署
1. 拉取或构建镜像
以下方式三选一
方式一:拉取最新镜像:
docker pull linzeyi/hivision_idphotos方式二:Dockrfile 直接构建镜像:
在确保将至少一个抠图模型权重文件放到hivision/creator/weights下后,在项目根目录执行:
docker build -t linzeyi/hivision_idphotos .方式三:Docker compose 构建:
在确保将至少一个抠图模型权重文件放到hivision/creator/weights下后,在项目根目录下执行:
docker compose build2. 运行服务
启动 Gradio Demo 服务
运行下面的命令,在你的本地访问 http://127.0.0.1:7860 即可使用。
docker run -d -p 7860:7860 linzeyi/hivision_idphotos启动 API 后端服务
docker run -d -p 8080:8080 linzeyi/hivision_idphotos python3 deploy_api.py两个服务同时启动
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使用环境变量示例:
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_idphotosFAQ
1. 如何修改预设尺寸和颜色?
- 尺寸:修改size_list_CN.csv后再次运行
app.py即可,其中第一列为尺寸名,第二列为高度,第三列为宽度。 - 颜色:修改color_list_CN.csv后再次运行
app.py即可,其中第一列为颜色名,第二列为Hex值。
2. 如何修改水印字体?
- 将字体文件放到
hivision/plugin/font文件夹下 - 修改
hivision/plugin/watermark.py的font_file参数值为字体文件名
3. 如何添加社交媒体模板照?
- 将模板图片放到
hivision/plugin/template/assets文件夹下。模板图片是一个4通道的透明png。 - 在
hivision/plugin/template/assets/template_config.json文件中添加最新的模板信息,其中width为模板图宽度(px),height为模板图高度(px),anchor_points为模板中透明区域的四个角的坐标(px);rotation为透明区域相对于垂直方向的旋转角度,>0为逆时针,<0为顺时针。 - 在
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
📧 联系我们
如果您有任何问题,请发邮件至 [email protected]
🙏 感谢支持
贡献者们:
Zeyi-Lin、SAKURA-CAT、Feudalman、swpfY、Kaikaikaifang、ShaohonChen、KashiwaByte
📜 Lincese
This repository is licensed under the Apache-2.0 License.
📚 引用
如果您在研究或项目中使用了HivisionIDPhotos,请考虑引用我们的工作。您可以使用以下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}},
}File: docs/api_CN.md
API Docs
English / 中文
目录
开始之前:开启后端服务
在请求 API 之前,请先运行后端服务
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. 生成证件照(底透明)
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. 添加背景色
curl -X POST "http://127.0.0.1:8080/add_background" \
-F "[email protected]" \
-F "color=638cce" \
-F "kb=200" \
-F "render=0" \
-F "dpi=300"3. 生成六寸排版照
curl -X POST "http://127.0.0.1:8080/generate_layout_photos" \
-F "[email protected]" \
-F "height=413" \
-F "width=295" \
-F "kb=200" \
-F "dpi=300"4. 人像抠图
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. 图片加水印
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大小
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. 证件照裁切
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.生成证件照(底透明)
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.添加背景色
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.生成六寸排版照
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.人像抠图
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.图片加水印
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大小
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. 证件照裁切
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 / 中文
Table of Contents
- Before You Start: Start the Backend Service
- API Functionality Description
- cURL Request Examples
- Python Request Examples
Before You Start: Start the Backend Service
Before making API requests, please run the backend service.
python deploy_api.pyAPI 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_hdappended tooutput_image_dir. - Standard ID Photo: The size equals
size, scaled from the high-definition ID photo, with the filename asoutput_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)
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
curl -X POST "http://127.0.0.1:8080/add_background" \
-F "[email protected]" \
-F "color=638cce" \
-F "kb=200" \
-F "render=0" \
-F "dpi=300"3. Generate Six-Inch Layout Photo
curl -X POST "http://127.0.0.1:8080/generate_layout_photos" \
-F "[email protected]" \
-F "height=413" \
-F "width=295" \
-F "kb=200" \
-F "dpi=300"4. Human Matting
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
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
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
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)
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
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
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
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
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
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
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++ 人脸检测配置文档
1. 注册Face++账号
要使用 Face++ 的人脸检测 API,您首先需要在 Face++ 的官方网站上注册一个账号。注册后,您将能够访问 API 控制台和相关服务。
步骤:
- 访问 Face++ 官网。
- 点击“注册”按钮,填写相关信息以创建您的账号。
2. 获取API KEY和API SECRET
注册并登录后,您需要获取用于身份验证的 API Key 和 API Secret。这些信息是调用 API 时必需的。
步骤:
- 登录到您的 Face++ 账号。
- 进入 控制台 -> 应用管理 -> API Key。
- 在控制台中,您将看到您的 API Key 和 API Secret。
3. 设置环境变量
为了在代码中安全地使用 API Key 和 API Secret,建议将它们设置为环境变量。这样可以避免在代码中硬编码敏感信息。
在不同操作系统中设置环境变量的步骤:
Windows:
- 打开命令提示符。
- 输入以下命令并按回车:cmd
set FACE_PLUS_API_KEY="您的API_KEY" set FACE_PLUS_API_SECRET="您的API_SECRET"
Linux / macOS:
- 打开终端。
- 输入以下命令并按回车:bash
export FACE_PLUS_API_KEY="你的API_KEY" export FACE_PLUS_API_SECRET="你的API_SECRET"
注意: 您可能需要在启动应用程序之前运行上述命令,或者将这些命令添加到您的 shell 配置文件(例如
.bashrc或.bash_profile)中,以便每次启动终端时自动加载。
4. 启动Gradio服务
运行gradio服务,在「人脸检测模型」中选择「face++」即可。
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
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:
- Visit the Face++ Official Website.
- 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:
- Log in to your Face++ account.
- Go to Console -> Application Management -> API Key.
- 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:
- Open the Command Prompt.
- 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:
- Open the terminal.
- 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.,
.bashrcor.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".
python app.pyExplanation of error codes
https://console.faceplusplus.com.cn/documents/4888373
File: README_EN.md
Related Projects:
- 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
- Project Overview
- Community
- Preparation
- Demo Startup
- Python Inference
- API Service Deployment
- Docker Deployment
- Contact Us
- Q&A
- Contributors
- Thanks for support
- License
🤩 Recent Updates
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 contributed by 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: [email protected].
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:
- Lightweight matting (purely offline, fast inference with CPU only)
- Generate standard ID photos and six-inch layout photos based on different size specifications
- Support pure offline or edge-cloud inference
- Beauty effects (waiting)
- 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: ComfyUI ID photo processing workflow built by AIFSH
- HivisionIDPhotos-wechat-weapp: WeChat ID photo mini program, powered by the HivisionIDphotos algorithm, contributed by no1xuan
- HivisionIDPhotos-Uniapp: Front-end of WeChat ID photo mini program based on uniapp, powered by the HivisionIDphotos algorithm, contributed by soulerror
- HivisionIDPhotos-cpp: C++ version of HivisionIDphotos, built by zjkhahah
- HivisionIDPhotos-windows-GUI: Windows client application built by zhaoyun0071
- HivisionIDPhotos-NAS: Chinese tutorial for Synology NAS deployment, contributed by 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
git clone https://github.com/Zeyi-Lin/HivisionIDPhotos.git
cd HivisionIDPhotos2. Install Dependency Environment
It is recommended to create a python3.10 virtual environment using conda, then execute the following commands
pip install -r requirements.txt
pip install -r requirements-app.txt3. Download Weight Files
Method 1: Script Download
python scripts/download_model.py --models allMethod 2: Direct Download
Store in the project's hivision/creator/weights directory:
modnet_photographic_portrait_matting.onnx(24.7MB): Official weights of MODNet, downloadhivision_modnet.onnx(24.7MB): Matting model with better adaptability for pure color background replacement, downloadrmbg-1.4.onnx(176.2MB): Open-source matting model from BRIA AI, download and rename tormbg-1.4.onnxbirefnet-v1-lite.onnx(224MB): Open-source matting model from ZhengPeng7, download and rename tobirefnet-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 and place it in the hivision/creator/retinaface/weights directory |
| Face++ | Online face detection API launched by Megvii, higher detection accuracy, official documentation | Usage Documentation |
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, and find the corresponding pytorch version to install according to the pytorch official website.
# 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/cu121After 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
python app.pyRunning 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 inference.py -i demo/images/test0.jpg -o ./idphoto.png --height 413 --width 2952. Portrait Matting
Input 1 photo to obtain 1 4-channel transparent PNG.
python inference.py -t human_matting -i demo/images/test0.jpg -o ./idphoto_matting.png --matting_model hivision_modnet3. Add Background Color to Transparent Image
Input 1 4-channel transparent PNG to obtain 1 3-channel image with added background color.
python inference.py -t add_background -i ./idphoto.png -o ./idphoto_ab.jpg -c 4f83ce -k 30 -r 14. Generate Six-Inch Layout Photo
Input 1 3-channel photo to obtain 1 six-inch layout photo.
python inference.py -t generate_layout_photos -i ./idphoto_ab.jpg -o ./idphoto_layout.jpg --height 413 --width 295 -k 2005. 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 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.pyRequest API Service
For detailed request methods, please refer to the API Documentation, which includes the following request examples:
🐳 Docker Deployment
1. Pull or Build Image
Choose one of the following methods
Method 1: Pull the latest image:
docker pull linzeyi/hivision_idphotosMethod 2: Directly build the image from Dockerfile:
After ensuring that at least one matting model weight file is placed in the hivision/creator/weights directory, execute the following in the project root directory:
docker build -t linzeyi/hivision_idphotos .Method 3: Build using Docker Compose:
After ensuring that at least one matting model weight file is placed in the hivision/creator/weights directory, execute the following in the project root directory:
docker compose build2. Run Services
Start Gradio Demo Service
Run the following command, and you can access it locally at http://127.0.0.1:7860.
docker run -d -p 7860:7860 linzeyi/hivision_idphotosStart API Backend Service
docker run -d -p 8080:8080 linzeyi/hivision_idphotos python3 deploy_api.pyStart Both Services Simultaneously
docker compose up -dEnvironment 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:
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
- MTCNN:
@software{ipazc_mtcnn_2021,
author = {ipazc},
title = {{MTCNN}},
url = {https://github.com/ipazc/mtcnn},
year = {2021},
publisher = {GitHub}
}- ModNet:
@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, run
app.pyagain. 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, run
app.pyagain. The first column is the color name, and the second column is the Hex value.
2. How to Change the Watermark Font?
- Place the font file in the
hivision/plugin/fontfolder. - Change the
font_fileparameter value inhivision/plugin/watermark.pyto the name of the font file.
3. How to Add Social Media Template Photos?
- Place the template image in the
hivision/plugin/template/assetsfolder. The template image should be a 4-channel transparent PNG. - Add the latest template information to the
hivision/plugin/template/assets/template_config.jsonfile. Here,widthis the template image width (px),heightis the template image height (px),anchor_pointsare the coordinates (px) of the four corners of the transparent area in the template;rotationis the rotation angle of the transparent area relative to the vertical direction, where >0 is counterclockwise and <0 is clockwise. - Add the name of the latest template to the
TEMPLATE_NAME_LISTvariable in the_generate_image_templatefunction ofdemo/processor.py.
4. How to Modify the Top Navigation Bar of the Gradio Demo?
- Modify the
demo/assets/title.mdfile.
📧 Contact Us
If you have any questions, please email [email protected]
Contributors
Zeyi-Lin、SAKURA-CAT、Feudalman、swpfY、Kaikaikaifang、ShaohonChen、KashiwaByte
Thanks for support
Lincese
This repository is licensed under the Apache-2.0 License.
File: README_JP.md
関連プロジェクト:
- SwanLab:人物切り抜きモデルの訓練を通じて、分析と監視、ラボの仲間との協力と交流を行い、訓練効率を大幅に向上させました。
目次
🤩 最近の更新
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 貢献 by zjkhahah
2024.09.16: Gradioデモに顔回転対応機能を追加、カスタムサイズ入力にミリメートルをサポート
プロジェクト概要
🚀 私たちの仕事に興味を持っていただきありがとうございます。画像分野における他の成果もぜひご覧ください。お問い合わせは、[email protected] まで。
HivisionIDPhotoは、実用的で体系的な証明写真のスマート制作アルゴリズムを開発することを目的としています。
さまざまなユーザー撮影シーンの認識、切り抜きおよび証明写真の生成を実現するために、一連の洗練されたAIモデル作業フローを利用しています。
HivisionIDPhotoは以下のことができます:
- 軽量切り抜き(完全オフラインで、CPUのみで迅速に推論可能)
- 異なるサイズ仕様に基づいて異なる標準証明写真、六寸レイアウト写真を生成
- 完全オフラインまたはエッジクラウド推論をサポート
- 美顔(待機中)
- スマートな正装変更(待機中)
HivisionIDPhotoがあなたに役立つ場合は、このリポジトリをスターしたり、友人に推薦したりして、証明写真の緊急制作の問題を解決してください!
🏠 コミュニティ
私たちは、コミュニティによって構築されたHivisionIDPhotosの興味深いアプリケーションや拡張機能をいくつか共有しています:
- HivisionIDPhotos-ComfyUI:ComfyUI証明写真処理ワークフロー、AIFSHによって構築
- HivisionIDPhotos-wechat-weapp:WeChat証明写真ミニプログラム、HivisionIDphotosアルゴリズムに基づく、no1xuanによる貢献
- HivisionIDPhotos-Uniapp:基本のuniapp証明写真ミニプログラムの前部、HivisionIDphotosアルゴリズムに基づく、soulerrorによる貢献
- HivisionIDPhotos-cpp:HivisionIDphotos C++バージョン、zjkhahahによって構築
- HivisionIDPhotos-windows-GUI:Windowsクライアントアプリケーション、zhaoyun0071によって構築
- HivisionIDPhotos-NAS:Synology NAS導入の中国語チュートリアル、ONG-Leoによる貢献
🔧 準備作業
環境のインストールと依存関係:
- Python >= 3.7(プロジェクトは主にpython 3.10でテストされています)
- OS: Linux, Windows, MacOS
1. プロジェクトをクローンする
git clone https://github.com/Zeyi-Lin/HivisionIDPhotos.git
cd HivisionIDPhotos2. 依存環境をインストールする
condaでpython3.10の仮想環境を作成することをお勧めします。その後、以下のコマンドを実行してください。
pip install -r requirements.txt
pip install -r requirements-app.txt3. 重みファイルをダウンロードする
方法一:スクリプトでダウンロード
python scripts/download_model.py --models all方法二:直接ダウンロード
プロジェクトのhivision/creator/weightsディレクトリに保存します:
modnet_photographic_portrait_matting.onnx(24.7MB): MODNet公式の重み、ダウンロードhivision_modnet.onnx(24.7MB): 単色背景に対して適応性の高い切り抜きモデル、ダウンロードrmbg-1.4.onnx(176.2MB): BRIA AIのオープンソース切り抜きモデル、ダウンロード後にrmbg-1.4.onnxにリネームbirefnet-v1-lite.onnx(224MB): ZhengPeng7のオープンソース切り抜きモデル、ダウンロード後にbirefnet-v1-lite.onnxにリネーム
4. 顔検出モデルの設定(オプション)
| 拡張顔検出モデル | 説明 | 使用文書 |
|---|---|---|
| MTCNN | オフライン顔検出モデル、高性能CPU推論、デフォルトモデル、検出精度は低い | このプロジェクトをクローン後、直接使用 |
| Face++ | Megviiが提供するオンライン顔検出API、高精度の検出、公式文書 | 使用文書 |
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のドキュメントに従って適切なonnxruntime-gpuバージョンをインストールし、PyTorchの公式サイトから適切なpytorchバージョンをインストールしてください。
# もしコンピュータに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のバージョンをインストールすることも可能です。
🚀 デモの起動
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 inference.py -i demo/images/test0.jpg -o ./idphoto.png --height 413 --width 2952. 人物切り抜き
1枚の写真を入力し、1枚の4チャンネル透明PNGを取得します。
python inference.py -t human_matting -i demo/images/test0.jpg -o ./idphoto_matting.png --matting_model hivision_modnet3. 透明画像に背景色を追加
1枚の4チャンネル透明PNGを入力し、背景色を追加した3チャンネル画像を取得します。
python inference.py -t add_background -i ./idphoto.png -o ./idphoto_ab.jpg -c 4f83ce -k 30 -r 14. 六寸レイアウト写真の取得
1枚の3チャンネル写真を入力し、1枚の六寸レイアウト写真を取得します。
python inference.py -t generate_layout_photos -i ./idphoto_ab.jpg -o ./idphoto_layout.jpg --height 413 --width 295 -k 2005. 証明写真のトリミング
1枚の4チャンネル写真(切り抜き済みの画像)を入力し、1枚の標準証明写真と1枚の高解像度証明写真の4チャンネル透明PNGを取得します。
python inference.py -t idphoto_crop -i ./idphoto_matting.png -o ./idphoto_crop.png --height 413 --width 295⚡️ APIサービスのデプロイ
バックエンドを起動
python deploy_api.pyAPIサービスにリクエスト
詳細なリクエスト方法はAPIドキュメントを参照してください。以下のリクエスト例が含まれます:
🐳 Dockerデプロイ
1. イメージをプルまたはビルドする
以下の方法から3つを選択してください。
方法一:最新のイメージをプル:
docker pull linzeyi/hivision_idphotos方法二:Dockerfileから直接イメージをビルド:
hivision/creator/weights ディレクトリに少なくとも1つのマスキングモデルの重みファイルがあることを確認してから、プロジェクトのルートディレクトリで以下を実行してください:
docker build -t linzeyi/hivision_idphotos .方法三:Docker composeでビルド:
hivision/creator/weights ディレクトリに少なくとも1つのマスキングモデルの重みファイルがあることを確認してから、プロジェクトのルートディレクトリで以下を実行してください:
docker compose build2. サービスを実行
Gradioデモサービスを起動
次のコマンドを実行し、ローカルで http://127.0.0.1:7860 にアクセスすると使用可能です。
docker run -d -p 7860:7860 linzeyi/hivision_idphotosAPIバックエンドサービスを起動
docker run -d -p 8080:8080 linzeyi/hivision_idphotos python3 deploy_api.py2つのサービスを同時に起動
docker compose up -d環境変数
本プロジェクトは、いくつかの追加設定項目を提供し、環境変数を使用して設定します:
| 環境変数 | タイプ | 説明 | 例 |
|---|---|---|---|
| FACE_PLUS_API_KEY | オプション | これはFace++コンソールで申請したAPIキーです。 | 7-fZStDJ···· |
| FACE_PLUS_API_SECRET | オプション | Face++ APIキーに対応するSecret | VTee824E···· |
dockerでの環境変数使用例:
docker run -d -p 7860:7860 \
-e FACE_PLUS_API_KEY=7-fZStDJ···· \
-e FACE_PLUS_API_SECRET=VTee824E···· \
linzeyi/hivision_idphotos📖 プロジェクトの引用
- MTCNN:
@software{ipazc_mtcnn_2021,
author = {ipazc},
title = {{MTCNN}},
url = {https://github.com/ipazc/mtcnn},
year = {2021},
publisher = {GitHub}
}- ModNet:
@software{zhkkke_modnet_2021,
author = {ZHKKKe},
title = {{ModNet}},
url = {https://github.com/ZHKKKe/MODNet},
year = {2021},
publisher = {GitHub}
}よくある質問 (FAQ)
1. 基本的なサイズと色をどのように変更しますか?
- サイズ: size_list_EN.csv ファイルを修正した後、
app.pyを再実行すれば大丈夫です。最初の列はサイズ名、二番目の列は高さ、三番目の列は幅です。 - 色: color_list_EN.csv ファイルを修正した後、
app.pyを再実行すれば大丈夫です。最初の列は色名、二番目の列はHex値です。
2. ウォーターマークのフォントをどのように変更しますか?
- フォントファイルを
hivision/plugin/fontフォルダーに置きます。 hivision/plugin/watermark.pyファイル内のfont_fileパラメータの値をフォントファイル名に変更します。
3. ソーシャルメディアのテンプレート画像をどのように追加しますか?
- テンプレート画像を
hivision/plugin/template/assetsフォルダーに置きます。テンプレート画像は4チャンネルの透明PNGです。 hivision/plugin/template/assets/template_config.jsonファイルに最新のテンプレート情報を追加します。ここでwidthはテンプレート画像の幅(px)、heightはテンプレート画像の高さ(px)、anchor_pointsはテンプレートの透明領域の4つの隅の座標(px)です。rotationは透明領域の垂直方向に対する回転角度で、>0は反時計回り、<0は時計回りです。demo/processor.pyの_generate_image_template関数内のTEMPLATE_NAME_LIST変数に最新のテンプレート名を追加します。
4. Gradio Demoの上部ナビゲーションバーをどのように変更しますか?
demo/assets/title.mdファイルを修正します。
📧 お問い合わせ
ご不明な点がございましたら、[email protected]までメールをお送りください。
貢献者
Zeyi-Lin、SAKURA-CAT、Feudalman、swpfY、Kaikaikaifang、ShaohonChen、KashiwaByte
Thanks for support
Lincese
This repository is licensed under the Apache-2.0 License.
File: README_KO.md
관련 프로젝트:
- SwanLab:인물 컷아웃 모델의 훈련을 통해, 분석과 감시, 연구실 동료들과의 협력 및 교류를 진행하여 훈련 효율성을 크게 향상시켰습니다.
목차
🤩 최근 업데이트
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 기여 by zjkhahah
2024.09.16: Gradio Demo에 얼굴 회전 정렬 기능 추가, 커스텀 사이즈 입력에 밀리미터 단위 추가
프로젝트 개요
🚀 우리의 작업에 관심을 가져 주셔서 감사합니다. 이미지 분야의 다른 성과도 꼭 확인해 주시기 바랍니다. 문의는 [email protected]로 해주세요.
HivisionIDPhoto는 실용적이고 체계적인 증명사진의 스마트 제작 알고리즘을 개발하는 것을 목표로 합니다.
다양한 사용자 촬영 장면의 인식, 컷아웃 및 증명사진 생성을 실현하기 위해 일련의 세련된 AI 모델 작업 흐름을 활용하고 있습니다.
HivisionIDPhoto는 다음과 같은 기능을 제공합니다:
- 경량 컷아웃 (완전 오프라인에서, CPU만으로 신속한 추론 가능)
- 다양한 사이즈 사양에 따라 다양한 표준 증명사진, 육寸 레이아웃 사진 생성
- 완전 오프라인 또는 엣지 클라우드 추론 지원
- 미용 (대기 중)
- 스마트한 정장 변경 (대기 중)
HivisionIDPhoto가 여러분에게 도움이 된다면, 이 리포지토리를 스타하거나 친구에게 추천하여 증명사진의 긴급 제작 문제를 해결해 주세요!
🏠 커뮤니티
우리는 커뮤니티에 의해 구축된 HivisionIDPhotos의 흥미로운 애플리케이션 및 확장 기능을 몇 가지 공유합니다:
- HivisionIDPhotos-ComfyUI: ComfyUI 증명사진 처리 워크플로우, AIFSH가 구축
- HivisionIDPhotos-wechat-weapp: WeChat 증명사진 미니 프로그램, HivisionIDphotos 알고리즘 기반, no1xuan이 기여
- HivisionIDPhotos-Uniapp: 기본 uniapp 증명사진 미니 프로그램 전면, HivisionIDphotos 알고리즘 기반, soulerror이 기여
- HivisionIDPhotos-cpp: HivisionIDphotos C++ 버전, zjkhahah이 구축
- HivisionIDPhotos-windows-GUI: Windows 클라이언트 애플리케이션, zhaoyun0071이 구축
- HivisionIDPhotos-NAS: Synology NAS 배포 중국어 튜토리얼, ONG-Leo가 기여
🔧 준비 작업
환경 설치 및 의존성:
- Python >= 3.7 (프로젝트는 주로 python 3.10으로 테스트되었습니다)
- OS: Linux, Windows, MacOS
1. 프로젝트 클론하기
git clone https://github.com/Zeyi-Lin/HivisionIDPhotos.git
cd HivisionIDPhotos2. 의존 환경 설치하기
conda로 python3.10 가상 환경을 만드는 것을 권장합니다. 그 후, 아래의 명령어를 실행해 주세요.
pip install -r requirements.txt
pip install -r requirements-app.txt3. 가중치 파일 다운로드하기
방법 1: 스크립트를 통해 다운로드
python scripts/download_model.py --models all방법 2: 직접 다운로드
프로젝트의 hivision/creator/weights 디렉토리에 저장합니다:
modnet_photographic_portrait_matting.onnx(24.7MB): MODNet 공식 가중치, 다운로드hivision_modnet.onnx(24.7MB): 단색 배경에 적응성이 높은 컷아웃 모델, 다운로드rmbg-1.4.onnx(176.2MB): BRIA AI의 오픈 소스 컷아웃 모델, 다운로드 후에rmbg-1.4.onnx로 이름 변경birefnet-v1-lite.onnx(224MB): ZhengPeng7의 오픈 소스 컷아웃 모델, 다운로드 후에birefnet-v1-lite.onnx로 이름 변경
4. 얼굴 검출 모델 설정하기 (선택 사항)
| 확장 얼굴 검출 모델 | 설명 | 사용 문서 |
|---|---|---|
| MTCNN | 오프라인 얼굴 검출 모델, 고성능 CPU 추론, 기본 모델, 검출 정확도가 낮음 | 이 프로젝트를 클론한 후 직접 사용 |
| Face++ | Megvii에서 제공하는 온라인 얼굴 검출 API, 고정밀 검출, 공식 문서 | 사용 문서 |
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 문서에서 해당하는 onnxruntime-gpu 버전을 찾아 설치하고, PyTorch 공식 웹사이트에서 해당하는 pytorch 버전을 찾아 설치하세요.
# 컴퓨터에 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 버전을 설치할 수 있습니다.
🚀 데모 실행
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 inference.py -i demo/images/test0.jpg -o ./idphoto.png --height 413 --width 2952. 인물 마스크
1장의 사진을 입력하여 1장의 4채널 투명 PNG를 얻습니다.
python inference.py -t human_matting -i demo/images/test0.jpg -o ./idphoto_matting.png --matting_model hivision_modnet3. 투명 이미지에 배경색 추가
1장의 4채널 투명 PNG를 입력하여 1장의 배경색이 추가된 3채널 이미지를 얻습니다.
python inference.py -t add_background -i ./idphoto.png -o ./idphoto_ab.jpg -c 4f83ce -k 30 -r 14. 6인치 배치 사진 생성
1장의 3채널 사진을 입력하여 1장의 6인치 배치 사진을 얻습니다.
python inference.py -t generate_layout_photos -i ./idphoto_ab.jpg -o ./idphoto_layout.jpg --height 413 --width 295 -k 2005. 증명사진 자르기
1장의 4채널 사진(마스크 처리된 이미지)을 입력하여 1장의 표준 증명사진과 1장의 고화질 증명사진의 4채널 투명 PNG를 얻습니다.
python inference.py -t idphoto_crop -i ./idphoto_matting.png -o ./idphoto_crop.png --height 413 --width 295⚡️ API 서비스 배포
백엔드 시작
python deploy_api.pyAPI 서비스에 요청
자세한 요청 방법은 API 문서를 참조해 주세요. 아래의 요청 예시가 포함됩니다:
🐳 Docker 배포
1. 이미지 풀 또는 빌드하기
아래의 방법 중 3가지를 선택해 주세요.
방법 1: 최신 이미지 풀하기:
docker pull linzeyi/hivision_idphotos방법 2: Dockerfile에서 직접 이미지 빌드하기:
hivision/creator/weights 디렉토리에 최소한 하나의 마스킹 모델 가중치 파일이 있는지 확인한 후, 프로젝트 루트 디렉토리에서 다음을 실행하세요:
docker build -t linzeyi/hivision_idphotos .방법 3: Docker compose로 빌드하기:
hivision/creator/weights 디렉토리에 최소한 하나의 마스킹 모델 가중치 파일이 있는지 확인한 후, 프로젝트 루트 디렉토리에서 다음을 실행하세요:
docker compose build2. 서비스 실행
Gradio 데모 서비스를 시작합니다
다음 명령어를 실행하여 로컬에서 http://127.0.0.1:7860에 접근하면 사용 가능합니다.
docker run -d -p 7860:7860 linzeyi/hivision_idphotosAPI 백엔드 서비스를 시작합니다
docker run -d -p 8080:8080 linzeyi/hivision_idphotos python3 deploy_api.py두 개의 서비스를 동시에 시작합니다
docker compose up -d환경 변수
본 프로젝트는 몇 가지 추가 설정 항목을 제공하며, 환경 변수를 사용하여 설정합니다:
| 환경 변수 | 유형 | 설명 | 예 |
|---|---|---|---|
| FACE_PLUS_API_KEY | 선택 사항 | 이는 Face++ 콘솔에서 신청한 API 키입니다. | 7-fZStDJ···· |
| FACE_PLUS_API_SECRET | 선택 사항 | Face++ API 키에 대응하는 Secret | VTee824E···· |
docker에서 환경 변수 사용 예:
docker run -d -p 7860:7860 \
-e FACE_PLUS_API_KEY=7-fZStDJ···· \
-e FACE_PLUS_API_SECRET=VTee824E···· \
linzeyi/hivision_idphotos📖 프로젝트 인용
- MTCNN:
@software{ipazc_mtcnn_2021,
author = {ipazc},
title = {{MTCNN}},
url = {https://github.com/ipazc/mtcnn},
year = {2021},
publisher = {GitHub}
}- ModNet:
@software{zhkkke_modnet_2021,
author = {ZHKKKe},
title = {{ModNet}},
url = {https://github.com/ZHKKKe/MODNet},
year = {2021},
publisher = {GitHub}
}자주 묻는 질문 (FAQ)
1. 기본 크기와 색상을 어떻게 수정하나요?
- 크기: size_list_EN.csv 파일을 수정한 후
app.py를 다시 실행하면 됩니다. 첫 번째 열은 크기 이름, 두 번째 열은 높이, 세 번째 열은 너비입니다. - 색상: color_list_EN.csv 파일을 수정한 후
app.py를 다시 실행하면 됩니다. 첫 번째 열은 색상 이름, 두 번째 열은 Hex 값입니다.
2. 워터마크 글꼴을 어떻게 수정하나요?
- 글꼴 파일을
hivision/plugin/font폴더에 넣습니다. hivision/plugin/watermark.py파일에서font_file매개변수 값을 글꼴 파일 이름으로 수정합니다.
3. 소셜 미디어 템플릿 사진을 어떻게 추가하나요?
- 템플릿 이미지를
hivision/plugin/template/assets폴더에 넣습니다. 템플릿 이미지는 4채널 투명 PNG입니다. hivision/plugin/template/assets/template_config.json파일에 최신 템플릿 정보를 추가합니다. 여기서width는 템플릿 이미지의 너비(px),height는 템플릿 이미지의 높이(px),anchor_points는 템플릿의 투명 영역 네 모서리의 좌표(px)입니다.rotation은 투명 영역의 수직 방향에 대한 회전 각도로, >0은 반시계 방향, <0은 시계 방향입니다.demo/processor.py의_generate_image_template함수 내의TEMPLATE_NAME_LIST변수에 최신 템플릿 이름을 추가합니다.
4. Gradio Demo의 상단 내비게이션 바를 어떻게 수정하나요?
demo/assets/title.md파일을 수정합니다.
📧 문의하기
궁금한 점이 있으시면 [email protected]로 이메일을 보내 주세요.
기여자
Zeyi-Lin、SAKURA-CAT、Feudalman、swpfY、Kaikaikaifang、ShaohonChen、KashiwaByte
Thanks for support
Lincese
This repository is licensed under the Apache-2.0 License.