提交 be32aadd 编写于 作者: W wuzewu

Merge branch 'release/v2.1' into develop

......@@ -123,6 +123,7 @@ please add WeChat above and send "Hub" to the robot, the robot will invite you t
<a name="QuickStart"></a>
## QuickStart
### The installation of required components.
```python
# install paddlepaddle with gpu
# !pip install --upgrade paddlepaddle-gpu
......@@ -132,8 +133,11 @@ please add WeChat above and send "Hub" to the robot, the robot will invite you t
# install paddlehub
!pip install --upgrade paddlehub
```
### The simplest cases of Chinese word segmentation.
```python
import paddlehub as hub
lac = hub.Module(name="lac")
......@@ -143,6 +147,15 @@ results = lac.cut(text=test_text, use_gpu=False, batch_size=1, return_tag=True)
print(results)
#{'word': ['今天', '是', '个', '好天气', '。'], 'tag': ['TIME', 'v', 'q', 'n', 'w']}
```
### The simplest command of deploying lac service.
</div>
```python
!hub serving start -m lac
```
More model description, please refer [Models List](https://www.paddlepaddle.org.cn/hublist)
More API for transfer learning, please refer [Tutorial](https://paddlehub.readthedocs.io/en/release-v2.1/transfer_learning_index.html)
<a name="License"></a>
......@@ -158,20 +171,23 @@ The release of this project is certified by the <a href="./LICENSE">Apache 2.0 l
<a href="https://github.com/ZeyuChen"><img src="https://avatars.githubusercontent.com/u/1371212?v=4" width=75 height=75></a>
<a href="https://github.com/ShenYuhan"><img src="https://avatars.githubusercontent.com/u/28444161?v=4" width=75 height=75></a>
<a href="https://github.com/kinghuin"><img src="https://avatars.githubusercontent.com/u/11913168?v=4" width=75 height=75></a>
<a href="https://github.com/haoyuying"><img src="https://avatars.githubusercontent.com/u/35907364?v=4" width=75 height=75></a>
<a href="https://github.com/grasswolfs"><img src="https://avatars.githubusercontent.com/u/23690325?v=4" width=75 height=75></a>
<a href="https://github.com/haoyuying"><img src="https://avatars.githubusercontent.com/u/35907364?v=4" width=75 height=75></a>
<a href="https://github.com/sjtubinlong"><img src="https://avatars.githubusercontent.com/u/2063170?v=4" width=75 height=75></a>
<a href="https://github.com/KPatr1ck"><img src="https://avatars.githubusercontent.com/u/22954146?v=4" width=75 height=75></a>
<a href="https://github.com/jm12138"><img src="https://avatars.githubusercontent.com/u/15712990?v=4" width=75 height=75></a>
<a href="https://github.com/DesmonDay"><img src="https://avatars.githubusercontent.com/u/20554008?v=4" width=75 height=75></a>
<a href="https://github.com/adaxiadaxi"><img src="https://avatars.githubusercontent.com/u/58928121?v=4" width=75 height=75></a>
<a href="https://github.com/chunzhang-hub"><img src="https://avatars.githubusercontent.com/u/63036966?v=4" width=75 height=75></a>
<a href="https://github.com/adaxiadaxi"><img src="https://avatars.githubusercontent.com/u/58928121?v=4" width=75 height=75></a>
<a href="https://github.com/linshuliang"><img src="https://avatars.githubusercontent.com/u/15993091?v=4" width=75 height=75></a>
<a href="https://github.com/eepgxxy"><img src="https://avatars.githubusercontent.com/u/15946195?v=4" width=75 height=75></a>
<a href="https://github.com/houj04"><img src="https://avatars.githubusercontent.com/u/35131887?v=4" width=75 height=75></a>
<a href="https://github.com/linjieccc"><img src="https://avatars.githubusercontent.com/u/40840292?v=4" width=75 height=75></a>
<a href="https://github.com/paopjian"><img src="https://avatars.githubusercontent.com/u/20377352?v=4" width=75 height=75></a>
<a href="https://github.com/zbp-xxxp"><img src="https://avatars.githubusercontent.com/u/58476312?v=4" width=75 height=75></a>
<a href="https://github.com/houj04"><img src="https://avatars.githubusercontent.com/u/35131887?v=4" width=75 height=75></a>
<a href="https://github.com/apps/dependabot"><img src="https://avatars.githubusercontent.com/in/29110?v=4" width=75 height=75></a>
<a href="https://github.com/dxxxp"><img src="https://avatars.githubusercontent.com/u/15886898?v=4" width=75 height=75></a>
<a href="https://github.com/jianganbai"><img src="https://avatars.githubusercontent.com/u/50263321?v=4" width=75 height=75></a>
<a href="https://github.com/1084667371"><img src="https://avatars.githubusercontent.com/u/50902619?v=4" width=75 height=75></a>
<a href="https://github.com/Channingss"><img src="https://avatars.githubusercontent.com/u/12471701?v=4" width=75 height=75></a>
<a href="https://github.com/Austendeng"><img src="https://avatars.githubusercontent.com/u/16330293?v=4" width=75 height=75></a>
......@@ -181,12 +197,16 @@ The release of this project is certified by the <a href="./LICENSE">Apache 2.0 l
<a href="https://github.com/Haijunlv"><img src="https://avatars.githubusercontent.com/u/28926237?v=4" width=75 height=75></a>
<a href="https://github.com/holyseven"><img src="https://avatars.githubusercontent.com/u/13829174?v=4" width=75 height=75></a>
<a href="https://github.com/MRXLT"><img src="https://avatars.githubusercontent.com/u/16594411?v=4" width=75 height=75></a>
<a href="https://github.com/Wgm-Inspur"><img src="https://avatars.githubusercontent.com/u/89008682?v=4" width=75 height=75></a>
<a href="https://github.com/cclauss"><img src="https://avatars.githubusercontent.com/u/3709715?v=4" width=75 height=75></a>
<a href="https://github.com/rainyfly"><img src="https://avatars.githubusercontent.com/u/22424850?v=4" width=75 height=75></a>
<a href="https://github.com/hu-qi"><img src="https://avatars.githubusercontent.com/u/17986122?v=4" width=75 height=75></a>
<a href="https://github.com/jayhenry"><img src="https://avatars.githubusercontent.com/u/4285375?v=4" width=75 height=75></a>
<a href="https://github.com/hlmu"><img src="https://avatars.githubusercontent.com/u/30133236?v=4" width=75 height=75></a>
<a href="https://github.com/yma-admin"><img src="https://avatars.githubusercontent.com/u/40477813?v=4" width=75 height=75></a>
<a href="https://github.com/zl1271"><img src="https://avatars.githubusercontent.com/u/22902089?v=4" width=75 height=75></a>
<a href="https://github.com/brooklet"><img src="https://avatars.githubusercontent.com/u/1585799?v=4" width=75 height=75></a>
<a href="https://github.com/wj-Mcat"><img src="https://avatars.githubusercontent.com/u/10242208?v=4" width=75 height=75></a>
</p>
We welcome you to contribute code to PaddleHub, and thank you for your feedback.
......@@ -203,3 +223,5 @@ We welcome you to contribute code to PaddleHub, and thank you for your feedback.
* Many thanks to [huqi](https://github.com/hu-qi) for fixing readme typo
* Many thanks to [parano](https://github.com/parano) [cqvu](https://github.com/cqvu) [deehrlic](https://github.com/deehrlic) for contributing this feature in PaddleHub
* Many thanks to [paopjian](https://github.com/paopjian) for correcting the wrong website address [#1424](https://github.com/PaddlePaddle/PaddleHub/issues/1424)
* Many thanks to [Wgm-Inspur](https://github.com/Wgm-Inspur) for correcting the demo errors in readme
* Many thanks to [zl1271](https://github.com/zl1271) for fixing serving docs typo
......@@ -128,14 +128,29 @@
<div id="QuickStart">
## 快速开始
[【零基础windows安装并实现图像风格迁移】](./docs/docs_ch/get_start/windows_quickstart.md)
[【零基础mac安装并实现图像风格迁移】](./docs/docs_ch/get_start/mac_quickstart.md)
[【零基础linux安装并实现图像风格迁移】](./docs/docs_ch/get_start/linux_quickstart.md)
### 快速安装相关组件
</div>
```python
!pip install --upgrade paddlepaddle -i https://mirror.baidu.com/pypi/simple
!pip install --upgrade paddlehub -i https://mirror.baidu.com/pypi/simple
```
### 极简中文分词案例
</div>
```python
import paddlehub as hub
lac = hub.Module(name="lac")
......@@ -144,11 +159,17 @@ test_text = ["今天是个好天气。"]
results = lac.cut(text=test_text, use_gpu=False, batch_size=1, return_tag=True)
print(results)
#{'word': ['今天', '是', '个', '好天气', '。'], 'tag': ['TIME', 'v', 'q', 'n', 'w']}
```
# 一行代码启动serving 服务,更多模型搜索可参考 https://www.paddlepaddle.org.cn/hublist
hub serving start -m lac
### 一行代码部署lac(词法分析)模型
</div>
```python
!hub serving start -m lac
```
欢迎用户通过[模型搜索](https://www.paddlepaddle.org.cn/hublist)发现更多实用的预训练模型!
更多迁移学习能力可以参考[教程文档](https://paddlehub.readthedocs.io/zh_CN/release-v2.1/transfer_learning_index.html)
......@@ -167,20 +188,23 @@ print(results)
<a href="https://github.com/ZeyuChen"><img src="https://avatars.githubusercontent.com/u/1371212?v=4" width=75 height=75></a>
<a href="https://github.com/ShenYuhan"><img src="https://avatars.githubusercontent.com/u/28444161?v=4" width=75 height=75></a>
<a href="https://github.com/kinghuin"><img src="https://avatars.githubusercontent.com/u/11913168?v=4" width=75 height=75></a>
<a href="https://github.com/haoyuying"><img src="https://avatars.githubusercontent.com/u/35907364?v=4" width=75 height=75></a>
<a href="https://github.com/grasswolfs"><img src="https://avatars.githubusercontent.com/u/23690325?v=4" width=75 height=75></a>
<a href="https://github.com/haoyuying"><img src="https://avatars.githubusercontent.com/u/35907364?v=4" width=75 height=75></a>
<a href="https://github.com/sjtubinlong"><img src="https://avatars.githubusercontent.com/u/2063170?v=4" width=75 height=75></a>
<a href="https://github.com/KPatr1ck"><img src="https://avatars.githubusercontent.com/u/22954146?v=4" width=75 height=75></a>
<a href="https://github.com/jm12138"><img src="https://avatars.githubusercontent.com/u/15712990?v=4" width=75 height=75></a>
<a href="https://github.com/DesmonDay"><img src="https://avatars.githubusercontent.com/u/20554008?v=4" width=75 height=75></a>
<a href="https://github.com/adaxiadaxi"><img src="https://avatars.githubusercontent.com/u/58928121?v=4" width=75 height=75></a>
<a href="https://github.com/chunzhang-hub"><img src="https://avatars.githubusercontent.com/u/63036966?v=4" width=75 height=75></a>
<a href="https://github.com/adaxiadaxi"><img src="https://avatars.githubusercontent.com/u/58928121?v=4" width=75 height=75></a>
<a href="https://github.com/linshuliang"><img src="https://avatars.githubusercontent.com/u/15993091?v=4" width=75 height=75></a>
<a href="https://github.com/eepgxxy"><img src="https://avatars.githubusercontent.com/u/15946195?v=4" width=75 height=75></a>
<a href="https://github.com/houj04"><img src="https://avatars.githubusercontent.com/u/35131887?v=4" width=75 height=75></a>
<a href="https://github.com/linjieccc"><img src="https://avatars.githubusercontent.com/u/40840292?v=4" width=75 height=75></a>
<a href="https://github.com/paopjian"><img src="https://avatars.githubusercontent.com/u/20377352?v=4" width=75 height=75></a>
<a href="https://github.com/zbp-xxxp"><img src="https://avatars.githubusercontent.com/u/58476312?v=4" width=75 height=75></a>
<a href="https://github.com/houj04"><img src="https://avatars.githubusercontent.com/u/35131887?v=4" width=75 height=75></a>
<a href="https://github.com/apps/dependabot"><img src="https://avatars.githubusercontent.com/in/29110?v=4" width=75 height=75></a>
<a href="https://github.com/dxxxp"><img src="https://avatars.githubusercontent.com/u/15886898?v=4" width=75 height=75></a>
<a href="https://github.com/jianganbai"><img src="https://avatars.githubusercontent.com/u/50263321?v=4" width=75 height=75></a>
<a href="https://github.com/1084667371"><img src="https://avatars.githubusercontent.com/u/50902619?v=4" width=75 height=75></a>
<a href="https://github.com/Channingss"><img src="https://avatars.githubusercontent.com/u/12471701?v=4" width=75 height=75></a>
<a href="https://github.com/Austendeng"><img src="https://avatars.githubusercontent.com/u/16330293?v=4" width=75 height=75></a>
......@@ -190,12 +214,16 @@ print(results)
<a href="https://github.com/Haijunlv"><img src="https://avatars.githubusercontent.com/u/28926237?v=4" width=75 height=75></a>
<a href="https://github.com/holyseven"><img src="https://avatars.githubusercontent.com/u/13829174?v=4" width=75 height=75></a>
<a href="https://github.com/MRXLT"><img src="https://avatars.githubusercontent.com/u/16594411?v=4" width=75 height=75></a>
<a href="https://github.com/Wgm-Inspur"><img src="https://avatars.githubusercontent.com/u/89008682?v=4" width=75 height=75></a>
<a href="https://github.com/cclauss"><img src="https://avatars.githubusercontent.com/u/3709715?v=4" width=75 height=75></a>
<a href="https://github.com/rainyfly"><img src="https://avatars.githubusercontent.com/u/22424850?v=4" width=75 height=75></a>
<a href="https://github.com/hu-qi"><img src="https://avatars.githubusercontent.com/u/17986122?v=4" width=75 height=75></a>
<a href="https://github.com/jayhenry"><img src="https://avatars.githubusercontent.com/u/4285375?v=4" width=75 height=75></a>
<a href="https://github.com/hlmu"><img src="https://avatars.githubusercontent.com/u/30133236?v=4" width=75 height=75></a>
<a href="https://github.com/yma-admin"><img src="https://avatars.githubusercontent.com/u/40477813?v=4" width=75 height=75></a>
<a href="https://github.com/zl1271"><img src="https://avatars.githubusercontent.com/u/22902089?v=4" width=75 height=75></a>
<a href="https://github.com/brooklet"><img src="https://avatars.githubusercontent.com/u/1585799?v=4" width=75 height=75></a>
<a href="https://github.com/wj-Mcat"><img src="https://avatars.githubusercontent.com/u/10242208?v=4" width=75 height=75></a>
</p>
我们非常欢迎您为PaddleHub贡献代码,也十分感谢您的反馈。
......@@ -211,3 +239,5 @@ print(results)
* 非常感谢[huqi](https://github.com/hu-qi)修复了readme中的错别字
* 非常感谢[parano](https://github.com/parano)[cqvu](https://github.com/cqvu)[deehrlic](https://github.com/deehrlic)三位的贡献与支持
* 非常感谢[paopjian](https://github.com/paopjian)修改了中文readme模型搜索指向的的网站地址错误[#1424](https://github.com/PaddlePaddle/PaddleHub/issues/1424)
* 非常感谢[Wgm-Inspur](https://github.com/Wgm-Inspur)修复了readme中的代码示例问题
* 非常感谢[zl1271](https://github.com/zl1271)修复了serving文档中的错别字
# 零基础Linux安装并实现图像风格迁移
## 第1步:安装Anaconda
- 说明:使用paddlepaddle需要先安装python环境,这里我们选择python集成环境Anaconda工具包
- Anaconda是1个常用的python包管理程序
- 安装完Anaconda后,可以安装python环境,以及numpy等所需的工具包环境
- **下载Anaconda**
- 下载地址:https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/?C=M&O=D
- <img src="../../imgs/Install_Related/linux/anaconda_download.png" akt="anaconda download" width="800" align="center"/>
- 选择适合您操作系统的版本
- 可在终端输入`uname -m`查询系统所用的指令集
- 下载法1:本地下载,再将安装包传到linux服务器上
- 下载法2:直接使用linux命令行下载
- ```shell
# 首先安装wget
sudo apt-get install wget # Ubuntu
sudo yum install wget # CentOS
```
- ```shell
# 然后使用wget从清华源上下载
# 如要下载Anaconda3-2021.05-Linux-x86_64.sh,则下载命令如下:
wget https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/Anaconda3-2021.05-Linux-x86_64.sh
# 若您要下载其他版本,需要将最后1个/后的文件名改成您希望下载的版本
```
- 安装Anaconda:
- 在命令行输入`sh Anaconda3-2021.05-Linux-x86_64.sh`
- 若您下载的是其它版本,则将该命令的文件名替换为您下载的文件名
- 按照安装提示安装即可
- 查看许可时可输入q来退出
- **将conda加入环境变量**
- 加入环境变量是为了让系统能识别conda命令,若您在安装时已将conda加入环境变量path,则可跳过本步
- 在终端中打开`~/.bashrc`
- ```shell
# 在终端中输入以下命令:
vim ~/.bashrc
```
-`~/.bashrc`中将conda添加为环境变量:
- ```shell
# 先按i进入编辑模式
# 在第一行输入:
export PATH="~/anaconda3/bin:$PATH"
# 若安装时自定义了安装位置,则将~/anaconda3/bin改为自定义的安装目录下的bin文件夹
```
- ```shell
# 修改后的~/.bash_profile文件应如下(其中xxx为用户名):
export PATH="~/opt/anaconda3/bin:$PATH"
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/Users/xxx/opt/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
eval "$__conda_setup"
else
if [ -f "/Users/xxx/opt/anaconda3/etc/profile.d/conda.sh" ]; then
. "/Users/xxx/opt/anaconda3/etc/profile.d/conda.sh"
else
export PATH="/Users/xxx/opt/anaconda3/bin:$PATH"
fi
fi
unset __conda_setup
# <<< conda initialize <<<
```
- 修改完成后,先按`esc`键退出编辑模式,再输入`:wq!`并回车,以保存退出
- 验证是否能识别conda命令:
- 在终端中输入`source ~/.bash_profile`以更新环境变量
- 再在终端输入`conda info --envs`,若能显示当前有base环境,则conda已加入环境变量
## 第2步:创建conda环境
- 创建新的conda环境
- ```shell
# 在命令行输入以下命令,创建名为paddle_env的环境
# 此处为加速下载,使用清华源
conda create --name paddle_env python=3.8 --channel https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
```
- 该命令会创建1个名为paddle_env、python版本为3.8的可执行环境,根据网络状态,需要花费一段时间
- 之后命令行中会输出提示信息,输入y并回车继续安装
- <img src="../../imgs/Install_Related/linux/conda_create.png" alt="conda_create" width="500" align="center"/>
- 激活刚创建的conda环境,在命令行中输入以下命令:
- ```shell
# 激活paddle_env环境
conda activate paddle_env
```
- 以上anaconda环境和python环境安装完毕
## 第3步:安装程序所需要库
- 使用pip命令在刚激活的环境中安装paddle:
- ```shell
# 在命令行中输入以下命令:
# 默认安装CPU版本,安装paddle时建议使用百度源
pip install paddlepaddle -i https://mirror.baidu.com/pypi/simple
```
- 安装完paddle后,继续在paddle_env环境中安装paddlehub:
- ```shell
# 在命令行中输入以下命令:
pip install paddlehub -i https://mirror.baidu.com/pypi/simple
```
- paddlehub的介绍文档:https://github.com/PaddlePaddle/PaddleHub/blob/release/v2.1/README_ch.md
- 安装paddlehub时会自动安装其它依赖库,可能需要花费一段时间
## 第4步:安装paddlehub并下载模型
- 安装完paddlehub后,下载风格迁移模型:
- ```shell
# 在命令行中输入以下命令
hub install stylepro_artistic==1.0.1
```
- 模型的说明文档:[https://www.paddlepaddle.org.cn/hubsearch?filter=en_category&value=%7B%22scenes%22%3A%5B%22GANs%22%5D%7D](https://www.paddlepaddle.org.cn/hubsearch?filter=en_category&value={"scenes"%3A["GANs"]})
- <img src="../../imgs/Install_Related/linux/hub_model_intro.png" alt="hub model intro" width="800" align="center"/>
## 第5步:准备风格迁移数据和代码
### 准备风格迁移数据
- 在用户目录~下,创建工作目录`style_transfer`
- ```shell
# 在终端中输入以下命令:
cd ~ # 进入用户目录
mkdir style_transfer # 创建style_transfer文件夹
cd style_transfer # 进入style_transfer目录
```
- 分别放置待转换图片和风格图片:
- 将待转换图片放置到`~/style_transfer/pic.jpg`
- <img src="../../imgs/Install_Related/linux/pic.jpg" alt="pic.jpg" width="400" align="center"/>
- 将风格图片放置到`~/style_transfer/fangao.jpg`
- <img src="../../imgs/Install_Related/linux/fangao.jpg" alt="fangao.jpg" width="350" align="center"/>
### 代码
- 创建代码文件:
- ```shell
# 以下命令均在命令行执行
$ pwd # 查看当前目录是否为style_transfer,若不是则输入:cd ~/style_transfer
$ touch style_transfer.py # 创建空文件
$ vim style_transfer.py # 使用vim编辑器打开代码文件
# 先输入i进入编辑模式
# 将代码拷贝进vim编辑器中
# 按esc键退出编辑模式,再输入":wq"并回车,以保存并退出
```
- ```python
# 代码
import paddlehub as hub
import cv2
# 待转换图片的相对地址
picture = './pic.jpg'
# 风格图片的相对地址
style_image = './fangao.jpg'
# 创建风格转移网络并加载参数
stylepro_artistic = hub.Module(name="stylepro_artistic")
# 读入图片并开始风格转换
result = stylepro_artistic.style_transfer(
images=[{'content': cv2.imread(picture),
'styles': [cv2.imread(style_image)]}],
visualization=True
)
```
- 运行代码:
- 在命令行中,输入`python style_transfer.py`
- 程序执行时,会创建新文件夹`transfer_result`,并将转换后的文件保存到该目录下
- 输出的图片如下:
- <img src="../../imgs/Install_Related/linux/output_img.png" alt="output image" width="600" align="center"/>
## 第6步:飞桨预训练模型探索之旅
- 恭喜你,到这里PaddleHub在windows环境下的安装和入门案例就全部完成了,快快开启你更多的深度学习模型探索之旅吧。[【更多模型探索,跳转飞桨官网】](https://www.paddlepaddle.org.cn/hublist)
# 零基础mac安装并实现图像风格迁移
## 第1步:安装Anaconda
- 说明:使用paddlepaddle需要先安装python环境,这里我们选择python集成环境Anaconda工具包
- Anaconda是1个常用的python包管理程序
- 安装完Anaconda后,可以安装python环境,以及numpy等所需的工具包环境
- Anaconda下载:
- 地址:https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/?C=M&O=D
- <img src="../../imgs/Install_Related/mac/anaconda_start.png" alt="anaconda download" width="800" align="center"/>
- 选择最下方的`Anaconda3-2021.05-MacOSX-x86_64.pkg`下载
- 下载完成后,双击.pkg文件进入图形界面
- 按默认设置即可,安装需要花费一段时间
- 建议安装vscode或pycharm等代码编辑器
## 第2步:打开终端并创建conda环境
- 打开终端
- 同时按下command键和空格键,在聚焦搜索中输入"终端",双击进入终端
- **将conda加入环境变量**
- 加入环境变量是为了让系统能识别conda命令
- 输入以下命令,在终端中打开`~/.bash_profile`
- ```shell
vim ~/.bash_profile
```
-`~/.bash_profile`中将conda添加为环境变量:
- ```shell
# 先按i进入编辑模式
# 在第一行输入:
export PATH="~/opt/anaconda3/bin:$PATH"
# 若安装时自定义了安装位置,则将~/opt/anaconda3/bin改为自定义的安装目录下的bin文件夹
```
- ```shell
# 修改后的~/.bash_profile文件应如下(其中xxx为用户名):
export PATH="~/opt/anaconda3/bin:$PATH"
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/Users/xxx/opt/anaconda3/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
eval "$__conda_setup"
else
if [ -f "/Users/xxx/opt/anaconda3/etc/profile.d/conda.sh" ]; then
. "/Users/xxx/opt/anaconda3/etc/profile.d/conda.sh"
else
export PATH="/Users/xxx/opt/anaconda3/bin:$PATH"
fi
fi
unset __conda_setup
# <<< conda initialize <<<
```
- 修改完成后,先按`esc`键退出编辑模式,再输入`:wq!`并回车,以保存退出
- 验证是否能识别conda命令:
- 在终端中输入`source ~/.bash_profile`以更新环境变量
- 再在终端输入`conda info --envs`,若能显示当前有base环境,则conda已加入环境变量
- 创建新的conda环境
- ```shell
# 在命令行输入以下命令,创建名为paddle_env的环境
# 此处为加速下载,使用清华源
conda create --name paddle_env python=3.8 --channel https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
```
- 该命令会创建1个名为paddle_env、python版本为3.8的可执行环境,根据网络状态,需要花费一段时间
- 之后命令行中会输出提示信息,输入y并回车继续安装
- <img src="../../imgs/Install_Related/mac/conda_create.png" alt="conda_create" width="600" align="center"/>
- 激活刚创建的conda环境,在命令行中输入以下命令:
- ```shell
# 激活paddle_env环境
conda activate paddle_env
# 查看当前python的位置
where python
```
- <img src="../../imgs/Install_Related/mac/conda_activate.png" alt="conda_actviate" width="600" align="center"/>
- 以上anaconda环境和python环境安装完毕
## 第3步:安装程序所需要库
- 使用pip命令在刚激活的环境中安装paddle:
- ```shell
# 在命令行中输入以下命令
# 确认当前所用的pip是否是paddle_env环境下的pip
where pip
# 默认安装CPU版本,安装paddle时建议使用百度源
pip install paddlepaddle -i https://mirror.baidu.com/pypi/simple
```
- 安装完paddle后,继续在paddle_env环境中安装paddlehub:
- ```shell
# 在命令行中输入以下命令
pip install paddlehub -i https://mirror.baidu.com/pypi/simple
```
- paddlehub的介绍文档:https://github.com/PaddlePaddle/PaddleHub/blob/release/v2.1/README_ch.md
- 安装paddlehub时会自动安装其它依赖库,可能需要花费一段时间
## 第4步:安装paddlehub并下载模型
- 安装完paddlehub后,下载风格迁移模型:
- ```shell
# 在命令行中输入以下命令
hub install stylepro_artistic==1.0.1
```
- 模型的说明文档:[https://www.paddlepaddle.org.cn/hubsearch?filter=en_category&value=%7B%22scenes%22%3A%5B%22GANs%22%5D%7D](https://www.paddlepaddle.org.cn/hubsearch?filter=en_category&value={"scenes"%3A["GANs"]})
- <img src="../../imgs/Install_Related/mac/hub_model_intro.png" alt="hub model intro" width="800" align="center"/>
## 第5步:准备风格迁移数据和代码
### 准备风格迁移数据
- 在桌面创建工作目录`style_transfer`
- ```shell
# 在终端中输入以下命令:
cd ~/Desktop # 进入桌面
mkdir style_transfer # 创建style_transfer文件夹
cd style_transfer # 进入style_transfer目录
```
- 分别放置待转换图片和风格图片:
- 将待转换图片放置到桌面的`style_transfer/pic.jpg`
- <img src="../../imgs/Install_Related/mac/pic.jpg" alt="pic.jpg" width="400" align="center"/>
- 将风格图片放置到桌面的`style_transfer/fangao.jpg`
- <img src="../../imgs/Install_Related/mac/fangao.jpg" alt="fangao.jpg" width="350" align="center"/>
### 代码
-`style_transfer`目录下创建代码文件`style_transfer.py`
-`style_transfer.py`中复制进如下代码:
- ```python
import paddlehub as hub
import cv2
# 待转换图片的相对地址
picture = './pic.jpg'
# 风格图片的相对地址
style_image = './fangao.jpg'
# 创建风格转移网络并加载参数
stylepro_artistic = hub.Module(name="stylepro_artistic")
# 读入图片并开始风格转换
result = stylepro_artistic.style_transfer(
images=[{'content': cv2.imread(picture),
'styles': [cv2.imread(style_image)]}],
visualization=True
)
```
- 若没有vscode等代码编辑器,则可通过命令行方法:
- ```shell
pwd # 查看当前目录是否为style_transfer,若不是则输入:cd ~/Desktop/style_transfer
touch style_transfer.py # 创建空文件
vim style_transfer.py # 使用vim编辑器打开代码文件
# 先输入i进入编辑模式
# 将上面的代码拷贝进vim编辑器中
# 按esc键退出编辑模式,再输入":wq"并回车,以保存并退出
```
- 运行代码:
- 在命令行中,输入`python style_transfer.py`
- 程序执行时,会创建新文件夹`transfer_result`,并将转换后的文件保存到该目录下
- 输出的图片如下:
- <img src="../../imgs/Install_Related/mac/output_img.png" alt="output image" width="600" align="center"/>
## 第6步:飞桨预训练模型探索之旅
- 恭喜你,到这里PaddleHub在windows环境下的安装和入门案例就全部完成了,快快开启你更多的深度学习模型探索之旅吧。[【更多模型探索,跳转飞桨官网】](https://www.paddlepaddle.org.cn/hublist)
# 零基础windows安装并实现图像风格迁移
## 第1步:安装Anaconda
- 说明:使用paddlepaddle需要先安装python环境,这里我们选择python集成环境Anaconda工具包
- Anaconda是1个常用的python包管理程序
- 安装完Anaconda后,可以安装python环境,以及numpy等所需的工具包环境。
- Anaconda下载:
- 地址:https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/?C=M&O=D
- 大部分win10电脑均为64位操作系统,选择x86_64版本;若电脑为32位操作系统,则选择x86.exe
- <img src="../../imgs/Install_Related/windows/Anaconda_download.png" alt="anaconda download" width="800" align="center"/>
- 下载完成后,双击安装程序进入图形界面
- 默认安装位置为C盘,建议将安装位置更改到D盘:
- <img src="../../imgs/Install_Related/windows/anaconda_install_folder.png" alt="install config" width="500" align="center"/>
- 勾选conda加入环境变量,忽略警告:
- <img src="../../imgs/Install_Related/windows/anaconda_install_env.png" alt="add conda to path" width="500" align="center"/>
## 第2步:打开终端并创建conda环境
- 打开Anaconda Prompt终端
- 左下角Windows Start Menu -> Anaconda3 -> Anaconda Prompt启动控制台
- <img src="../../imgs/Install_Related/windows/anaconda_prompt.png" alt="anaconda download" width="300" align="center"/>
- 创建新的conda环境
- ```shell
# 在命令行输入以下命令,创建名为paddle_env的环境
# 此处为加速下载,使用清华源
conda create --name paddle_env python=3.8 --channel https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ # 这是一行命令
```
- 该命令会创建1个名为paddle_env、python版本为3.8的可执行环境,根据网络状态,需要花费一段时间
- 之后命令行中会输出提示信息,输入y并回车继续安装
- <img src="../../imgs/Install_Related/windows/conda_new_env.png" alt="conda create" width="700" align="center"/>
- 激活刚创建的conda环境,在命令行中输入以下命令:
- ```shell
# 激活paddle_env环境
conda activate paddle_env
# 查看当前python的位置
where python
```
- <img src="../../imgs/Install_Related/windows/conda_list_env.png" alt="create environment" width="600" align="center"/>
- 以上anaconda环境和python环境安装完毕
## 第3步:安装程序运行所需库
- 使用pip命令在刚激活的环境中安装paddle,
- ```shell
# 在命令行中输入以下命令
# 确认当前所用的pip是否是paddle_env环境下的pip
where pip
# 默认安装CPU版本,安装paddle时建议使用百度源
pip install paddlepaddle -i https://mirror.baidu.com/pypi/simple
```
- 若需要安装GPU版本,则请打开[paddle官网](https://www.paddlepaddle.org.cn/)选择适合的版本
- paddle官网:https://www.paddlepaddle.org.cn/
- 由于安装GPU版本需要先配置好CUDA和cudnn,建议有一定基础后再安装GPU版本
- 安装完paddle后,继续在paddle_env环境中安装paddlehub:
- ```shell
# 在命令行中输入以下命令
pip install paddlehub -i https://mirror.baidu.com/pypi/simple
```
- paddlehub的介绍文档:https://github.com/PaddlePaddle/PaddleHub/blob/release/v2.1/README_ch.md
## 第4步:安装paddlehub并下载模型
- 安装完paddlehub后,下载风格迁移模型:
- ```shell
# 在命令行中输入以下命令
hub install stylepro_artistic==1.0.1
```
- 模型的说明文档:[https://www.paddlepaddle.org.cn/hubsearch?filter=en_category&value=%7B%22scenes%22%3A%5B%22GANs%22%5D%7D](https://www.paddlepaddle.org.cn/hubsearch?filter=en_category&value={"scenes"%3A["GANs"]})
- <img src="../../imgs/Install_Related/windows/paddlehub_modulelist.png" alt="model introduction" width="700" align="center"/>
## 第5步:准备风格迁移数据和代码
### 准备风格迁移数据
- 切换工作目录到`D:\style_transfer`,在命令行中输入以下命令
- ```shell
# 在命令行中输入以下命令
#把当前工作目录切换到D盘根目录
D:
#创建style_transfer目录
mkdir style_transfer
#切换当前目录到style_transfer目录
cd style_transfer
```
- 分别放置待转换图片和风格图片
- 将待转换图片放置到`D:\style_transfer\pic.jpg`
- <img src="../../imgs/Install_Related/windows/pic.jpg" alt="pic.jpg" width="400" align="center"/>
- 将风格图片放置到`D:\style_transfer\fangao.jpg`
- <img src="../../imgs/Install_Related/windows/fangao.jpg" alt="fangao.jpg" width="350" align="center"/>
### 代码
-`D:\style_transfer`目录下创建代码文件`style_transfer.py`
- 若没有vscode等编辑器,可使用记事本先创建1个txt文件,再将文件名改成`style_transfer.py`
-`style_transfer.py`中复制进如下代码:
- ```python
import paddlehub as hub
import cv2
# 待转换图片的绝对地址
picture = 'D:\\style_transfer\\pic.jpg' # 注意代码中此处为双反斜杠
# 风格图片的绝对地址
style_image = 'D:\\style_transfer\\fangao.jpg'
# 创建风格转移网络并加载参数
stylepro_artistic = hub.Module(name="stylepro_artistic")
# 读入图片并开始风格转换
result = stylepro_artistic.style_transfer(
images=[{'content': cv2.imread(picture),
'styles': [cv2.imread(style_image)]}],
visualization=True
)
```
- 运行代码:
- 在命令行中,输入`python style_transfer.py`
- 程序执行时,会创建新文件夹`transfer_result`,并将转换后的文件保存到该目录下
- 输出图片如下:
- <img src="../../imgs/Install_Related/windows/after_transfer.png" alt="transferred image" width="600" align="center"/>
## 第六步:飞桨预训练模型探索之旅
- 恭喜你,到这里PaddleHub在windows环境下的安装和入门案例就全部完成了,快快开启你更多的深度学习模型探索之旅吧。[【更多模型探索,跳转飞桨官网】](https://www.paddlepaddle.org.cn/hublist)
......@@ -167,7 +167,7 @@ if __name__ == "__main__":
text = ["今天是个好日子", "天气预报说今天要下雨"]
# 以key的方式指定text传入预测方法的时的参数,此例中为"data"
# 对应本地部署,则为lac.analysis_lexical(data=text, batch_size=1)
data = {"texts": text, "batch_size": 1}
data = {"text": text, "batch_size": 1}
# 指定预测方法为lac并发送post请求,content-type类型应指定json方式
url = "http://127.0.0.1:8866/predict/lac"
# 指定post请求的headers为application/json方式
......
<p align="center">
<img src="https://paddlehub.bj.bcebos.com/resources/style.png" hspace='10'/> <br />
</p>
更多详情请参考StyleProNet论文[https://arxiv.org/abs/2003.07694](https://arxiv.org/abs/2003.07694)
## 命令行预测
```
hub run stylepro_artistic --选项 选项值
```
**选项说明:**
* content (str): 待转换风格的图片的存放路径;
* styles (str): 作为底色的风格图片的存放路径,不同图片用英文逗号 `,` 间隔;
* weights (float, optional) : styles 的权重,用英文逗号 `,` 间隔;
* alpha (float, optioal):转换的强度,\[0, 1\] 之间,默认值为1;
* use\_gpu (bool, optional): 是否使用 gpu,默认为 False;
* output\_dir (str, optional): 输出目录,默认为 transfer\_result;
* visualization (bool, optioanl): 是否将结果保存为图片,默认为 True。
## API
```python
def style_transfer(images=None,
paths=None,
alpha=1,
use_gpu=False,
visualization=False,
output_dir='transfer_result'):
```
对图片进行风格转换。
**参数**
* images (list\[dict\]): ndarray 格式的图片数据。每一个元素都为一个 dict,有关键字 content, styles, weights(可选),相应取值为:
* content (numpy.ndarray): 待转换的图片,shape 为 \[H, W, C\],BGR格式;
* styles (list\[numpy.ndarray\]) : 作为底色的风格图片组成的列表,各个图片数组的shape 都是 \[H, W, C\],BGR格式;
* weights (list\[float\], optioal) : 各个 style 对应的权重。当不设置 weights 时,默认各个 style 有着相同的权重;
* paths (list\[str\]): 图片的路径。每一个元素都为一个 dict,有关键字 content, styles, weights(可选),相应取值为:
* content (str): 待转换的图片的路径;
* styles (list\[str\]) : 作为底色的风格图片的路径;
* weights (list\[float\], optioal) : 各个 style 对应的权重。当不设置 weights 时,各个 style 的权重相同;
* alpha (float) : 转换的强度,\[0, 1\] 之间,默认值为1;
* use\_gpu (bool): 是否使用 GPU;
* visualization (bool): 是否将结果保存为图片,默认为 False;
* output\_dir (str): 图片的保存路径,默认设为 transfer\_result 。
**返回**
* res (list\[dict\]): 识别结果的列表,列表中每一个元素为 OrderedDict,关键字有 date, save\_path,相应取值为:
* save\_path (str): 保存图片的路径;
* data (numpy.ndarray): 风格转换的图片数据。
```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
将模型保存到指定路径。
**参数**
* dirname: 存在模型的目录名称
* model\_filename: 模型文件名称,默认为\_\_model\_\_
* params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效)
* combined: 是否将参数保存到统一的一个文件中
## 代码示例
```python
import paddlehub as hub
import cv2
stylepro_artistic = hub.Module(name="stylepro_artistic")
result = stylepro_artistic.style_transfer(
# stylepro_artistic
|模型名称|stylepro_artistic|
| :--- | :---: |
|类别|图像 - 图像生成|
|网络|StyleProNet|
|数据集|MS-COCO + WikiArt|
|是否支持Fine-tuning|否|
|模型大小|28MB|
|最新更新日期|2021-02-26|
|数据指标|-|
## 一、模型基本信息
- ### 应用效果展示
- 样例结果示例:
<p align="center">
<img src="https://paddlehub.bj.bcebos.com/resources/style.png" width='80%' hspace='10'/> <br />
</p>
- ### 模型介绍
- 艺术风格迁移模型可以将给定的图像转换为任意的艺术风格。本模型StyleProNet整体采用全卷积神经网络架构(FCNs),通过encoder-decoder重建艺术风格图片。StyleProNet的核心是无参数化的内容-风格融合算法Style Projection,模型规模小,响应速度快。模型训练的损失函数包含style loss、content perceptual loss以及content KL loss,确保模型高保真还原内容图片的语义细节信息与风格图片的风格信息。预训练数据集采用MS-COCO数据集作为内容端图像,WikiArt数据集作为风格端图像。更多详情请参考StyleProNet论文[https://arxiv.org/abs/2003.07694](https://arxiv.org/abs/2003.07694)
## 二、安装
- ### 1、环境依赖
- paddlepaddle >= 1.6.2
- paddlehub >= 1.6.0 | [如何安装paddlehub](../../../../docs/docs_ch/get_start/installation.rst)
- ### 2、安装
- ```shell
$ hub install stylepro_artistic
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
## 三、模型API预测
- ### 1、命令行预测
- ```shell
$ hub run stylepro_artistic --input_path "/PATH/TO/IMAGE"
```
- 通过命令行方式实现风格转换模型的调用,更多请见 [PaddleHub命令行指令](../../../../docs/docs_ch/tutorial/cmd_usage.rst)
- ### 2、代码示例
- ```python
import paddlehub as hub
import cv2
stylepro_artistic = hub.Module(name="stylepro_artistic")
result = stylepro_artistic.style_transfer(
images=[{
'content': cv2.imread('/PATH/TO/CONTENT_IMAGE'),
'styles': [cv2.imread('/PATH/TO/STYLE_IMAGE')]
}])
# or
# result = stylepro_artistic.style_transfer(
# paths=[{
# 'content': '/PATH/TO/CONTENT_IMAGE',
# 'styles': ['/PATH/TO/STYLE_IMAGE']
# }])
```
# or
# result = stylepro_artistic.style_transfer(
# paths=[{
# 'content': '/PATH/TO/CONTENT_IMAGE',
# 'styles': ['/PATH/TO/STYLE_IMAGE']
# }])
```
- ### 3、API
- ```python
def style_transfer(images=None,
paths=None,
alpha=1,
use_gpu=False,
visualization=False,
output_dir='transfer_result')
```
- 对图片进行风格转换。
- **参数**
- images (list\[dict\]): ndarray 格式的图片数据。每一个元素都为一个 dict,有关键字 content, styles, weights(可选),相应取值为:
- content (numpy.ndarray): 待转换的图片,shape 为 \[H, W, C\],BGR格式;<br/>
- styles (list\[numpy.ndarray\]) : 作为底色的风格图片组成的列表,各个图片数组的shape 都是 \[H, W, C\],BGR格式;<br/>
- weights (list\[float\], optioal) : 各个 style 对应的权重。当不设置 weights 时,默认各个 style 有着相同的权重;<br/>
- paths (list\[str\]): 图片的路径。每一个元素都为一个 dict,有关键字 content, styles, weights(可选),相应取值为:
- content (str): 待转换的图片的路径;<br/>
- styles (list\[str\]) : 作为底色的风格图片的路径;<br/>
- weights (list\[float\], optioal) : 各个 style 对应的权重。当不设置 weights 时,各个 style 的权重相同;<br/>
- alpha (float) : 转换的强度,\[0, 1\] 之间,默认值为1;<br/>
- use\_gpu (bool): 是否使用 GPU;<br/>
- visualization (bool): 是否将结果保存为图片,默认为 False; <br/>
- output\_dir (str): 图片的保存路径,默认设为 transfer\_result。
**NOTE:** paths和images两个参数选择其一进行提供数据
## 服务部署
- **返回**
PaddleHub Serving可以部署一个在线风格转换服务。
- res (list\[dict\]): 识别结果的列表,列表中每一个元素为 OrderedDict,关键字有 date, save\_path,相应取值为:
- save\_path (str): 保存图片的路径
- data (numpy.ndarray): 风格转换的图片数据
## 第一步:启动PaddleHub Serving
运行启动命令:
```shell
$ hub serving start -m stylepro_artistic
```
- ```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- 将模型保存到指定路径。
这样就完成了一个风格转换服务化API的部署,默认端口号为8866。
- **参数**
**NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置环境变量 CUDA\_VISIBLE\_DEVICES ,否则不用设置。
- dirname: 存在模型的目录名称; <br/>
- model\_filename: 模型文件名称,默认为\_\_model\_\_; <br/>
- params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效);<br/>
- combined: 是否将参数保存到统一的一个文件中。
## 第二步:发送预测请求
配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
## 四、服务部署
```python
import requests
import json
import cv2
import base64
import numpy as np
- PaddleHub Serving可以部署一个在线风格转换服务。
- ### 第一步:启动PaddleHub Serving
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
- 运行启动命令:
- ```shell
$ hub serving start -m stylepro_artistic
```
- 这样就完成了一个风格转换服务化API的部署,默认端口号为8866。
def base64_to_cv2(b64str):
data = base64.b64decode(b64str.encode('utf8'))
data = np.fromstring(data, np.uint8)
data = cv2.imdecode(data, cv2.IMREAD_COLOR)
return data
- **NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- ### 第二步:发送预测请求
data = {'images':[
- 配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- ```python
import requests
import json
import cv2
import base64
import numpy as np
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
def base64_to_cv2(b64str):
data = base64.b64decode(b64str.encode('utf8'))
data = np.fromstring(data, np.uint8)
data = cv2.imdecode(data, cv2.IMREAD_COLOR)
return data
# 发送HTTP请求
data = {'images':[
{
'content':cv2_to_base64(cv2.imread('/PATH/TO/CONTENT_IMAGE')),
'styles':[cv2_to_base64(cv2.imread('/PATH/TO/STYLE_IMAGE'))]
}
]}
]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/stylepro_artistic"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
# 打印预测结果
print(base64_to_cv2(r.json()["results"][0]['data']))
```
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/stylepro_artistic"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
## 五、更新历史
print(base64_to_cv2(r.json()["results"][0]['data']))
```
* 1.0.0
### 依赖
初始发布
paddlepaddle >= 1.6.2
* 1.0.1
paddlehub >= 1.6.0
- ```shell
$ hub install stylepro_artistic==1.0.1
```
......@@ -67,10 +67,19 @@ def _handle_single(im_path=None, im_arr=None):
Returns:
im (numpy.ndarray): preprocessed data, with shape (1, 3, 512, 512).
"""
im = None
if im_path is not None:
im = cv2.imread(im_path)[:, :, ::-1].astype(np.float32)
im = cv2.imread(im_path)
if im is None:
raise FileNotFoundError('Error: The file path "{}" may not exist or is not a valid image file, please provide a valid path.'.format(im_path))
else:
assert(len(im.shape) == 3, 'The input image shape should be [H, W, 3], but got {}'.format(im.shape))
assert(im.shape[2] == 3, 'The input image should have 3 channels, but got {}'.format(im.shape[2]))
im = im[:, :, ::-1].astype(np.float32) ### Image should have 3-channels, and BGR format is arranged by cv2, we should change it to RGB.
if im_arr is not None:
im = im_arr[:, :, ::-1].astype(np.float32)
if im is None:
raise ValueError('No image data is provided. Please check the input "images" and "paths".')
w, h = im.shape[1], im.shape[0]
im = cv2.resize(im, (512, 512), interpolation=cv2.INTER_LINEAR)
im = im.transpose((2, 0, 1))
......
......@@ -22,7 +22,7 @@ from stylepro_artistic.data_feed import reader
@moduleinfo(
name="stylepro_artistic",
version="1.0.1",
version="1.0.2",
type="cv/style_transfer",
summary="StylePro Artistic is an algorithm for Arbitrary image style, which is parameter-free, fast yet effective.",
author="baidu-bdl",
......
......@@ -40,7 +40,11 @@ def postprocess(im, output_dir, save_im_name, visualization, size):
os.makedirs(output_dir)
# save image
save_path = os.path.join(output_dir, save_im_name)
cv2.imwrite(save_path, im)
try:
cv2.imwrite(save_path, im)
print('Notice: an image has been proccessed and saved in path "{}".'.format(os.path.abspath(save_path)))
except Exception as e:
print('Exception {}: Fail to save output image in path "{}".'.format(e, os.path.abspath(save_path)))
result['save_path'] = save_path
return result
......
```shell
$ hub install pyramidbox_face_detection==1.1.0
```
# pyramidbox_face_detection
<p align="center">
<img src="https://bj.bcebos.com/paddlehub/paddlehub-img/pyramidbox_face_detection_network.png" hspace='10'/> <br />
Pyramidbox模型框架图
</p>
|模型名称|pyramidbox_face_detection|
| :--- | :---: |
|类别|图像 - 人脸检测|
|网络|PyramidBox|
|数据集|WIDER FACE数据集|
|是否支持Fine-tuning|否|
|模型大小|220MB|
|最新更新日期|2021-02-26|
|数据指标|-|
模型详情请参考[论文](https://arxiv.org/pdf/1803.07737.pdf)
## 一、模型基本信息
## 命令行预测
- ### 应用效果展示
- 样例结果示例:
<p align="center">
<img src="https://user-images.githubusercontent.com/22424850/131602468-351eb3fb-81e3-4294-ac8e-b49a3a0232cb.jpg" width='50%' hspace='10'/>
<br />
</p>
```
hub run pyramidbox_face_detection --input_path "/PATH/TO/IMAGE"
```
## API
- ### 模型介绍
```python
def face_detection(images=None,
paths=None,
use_gpu=False,
output_dir='detection_result',
visualization=False,
score_thresh=0.15):
```
- PyramidBox是一种基于SSD的单阶段人脸检测器,它利用上下文信息解决困难人脸的检测问题。PyramidBox在六个尺度的特征图上进行不同层级的预测。该工作主要包括以下模块:LFPN、PyramidAnchors、CPM、Data-anchor-sampling。该PaddleHub Module的预训练数据集为WIDER FACE数据集,可支持预测。
预测API,检测输入图片中的所有人脸位置。
**参数**
## 二、安装
* images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;
* paths (list\[str\]): 图片的路径;
* use\_gpu (bool): 是否使用 GPU;
* output\_dir (str): 图片的保存路径,当为 None 时,默认设为 detection\_result;
* visualization (bool): 是否将识别结果保存为图片文件;
* score\_thresh (float): 检测置信度的阈值。
- ### 1、环境依赖
**返回**
- paddlepaddle >= 1.6.2
* res (list\[dict\]): 识别结果的列表,列表中每一个元素为 dict,关键字包括'path', 'data', 相应的取值为:
* path (str): 原输入图片的路径;
* data (list): 检测结果,list的每一个元素为 dict,各字段为:
* confidence (float): 识别的置信度;
* left (int): 边界框的左上角x坐标;
* top (int): 边界框的左上角y坐标;
* right (int): 边界框的右下角x坐标;
* bottom (int): 边界框的右下角y坐标。
- paddlehub >= 1.6.0 | [如何安装paddlehub](../../../../docs/docs_ch/get_start/installation.rst)
```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- ### 2、安装
将模型保存到指定路径。
- ```shell
$ hub install pyramidbox_face_detection
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
**参数**
## 三、模型API预测
* dirname: 存在模型的目录名称
* model\_filename: 模型文件名称,默认为\_\_model\_\_
* params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效)
* combined: 是否将参数保存到统一的一个文件中
- ### 1、命令行预测
## 代码示例
- ```shell
$ hub run pyramidbox_face_detection --input_path "/PATH/TO/IMAGE"
```
- 通过命令行方式实现人脸检测模型的调用,更多请见 [PaddleHub命令行指令](../../../../docs/docs_ch/tutorial/cmd_usage.rst)
```python
import paddlehub as hub
import cv2
- ### 2、代码示例
face_detector = hub.Module(name="pyramidbox_face_detection")
result = face_detector.face_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = face_detector.face_detection((paths=['/PATH/TO/IMAGE'])
```
- ```python
import paddlehub as hub
import cv2
## 服务部署
face_detector = hub.Module(name="pyramidbox_face_detection")
result = face_detector.face_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = face_detector.face_detection(paths=['/PATH/TO/IMAGE'])
```
PaddleHub Serving可以部署一个在线人脸检测服务。
- ### 3、API
## 第一步:启动PaddleHub Serving
- ```python
def face_detection(images=None,
paths=None,
use_gpu=False,
output_dir='detection_result',
visualization=False,
score_thresh=0.15)
```
运行启动命令:
```shell
$ hub serving start -m pyramidbox_face_detection
```
- 检测输入图片中的所有人脸位置。
这样就完成了一个人脸检测服务化API的部署,默认端口号为8866。
- **参数**
**NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;<br/>
- paths (list\[str\]): 图片的路径;<br/>
- use\_gpu (bool): 是否使用 GPU;<br/>
- output\_dir (str): 图片的保存路径,默认设为 detection\_result;<br/>
- visualization (bool): 是否将识别结果保存为图片文件;<br/>
- score_thresh (float): 置信度的阈值。
## 第二步:发送预测请求
**NOTE:** paths和images两个参数选择其一进行提供数据
配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- **返回**
```python
import requests
import json
import cv2
import base64
- res (list\[dict\]): 识别结果的列表,列表中每一个元素为 dict,各字段为:
- path (str): 原输入图片的路径
- data (list): 检测结果,list的每一个元素为 dict,各字段为:
- confidence (float): 识别的置信度
- left (int): 边界框的左上角x坐标
- top (int): 边界框的左上角y坐标
- right (int): 边界框的右下角x坐标
- bottom (int): 边界框的右下角y坐标
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
- ```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- 将模型保存到指定路径。
- **参数**
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/pyramidbox_face_detection"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
- dirname: 存在模型的目录名称; <br/>
- model\_filename: 模型文件名称,默认为\_\_model\_\_; <br/>
- params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效);<br/>
- combined: 是否将参数保存到统一的一个文件中。
# 打印预测结果
print(r.json()["results"])
```
## 查看代码
## 四、服务部署
https://github.com/PaddlePaddle/models/tree/develop/PaddleCV/face_detection
- PaddleHub Serving可以部署一个在线人脸检测服务。
### 依赖
- ### 第一步:启动PaddleHub Serving
paddlepaddle >= 1.6.2
- 运行启动命令:
- ```shell
$ hub serving start -m pyramidbox_face_detection
```
paddlehub >= 1.6.0
- 这样就完成了一个人脸检测服务化API的部署,默认端口号为8866。
- **NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- ### 第二步:发送预测请求
- 配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- ```python
import requests
import json
import cv2
import base64
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/pyramidbox_face_detection"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
# 打印预测结果
print(r.json()["results"])
```
## 五、更新历史
* 1.0.0
初始发布
* 1.1.0
修复numpy数据读取问题
- ```shell
$ hub install pyramidbox_face_detection==1.1.0
```
```shell
$ hub install pyramidbox_lite_mobile==1.2.0
```
# pyramidbox_lite_mobile
## 命令行预测
|模型名称|pyramidbox_lite_mobile|
| :--- | :---: |
|类别|图像 - 人脸检测|
|网络|PyramidBox|
|数据集|WIDER FACE数据集 + 百度自采人脸数据集|
|是否支持Fine-tuning|否|
|模型大小|7.3MB|
|最新更新日期|2021-02-26|
|数据指标|-|
```
hub run pyramidbox_lite_mobile --input_path "/PATH/TO/IMAGE"
```
## API
## 一、模型基本信息
```python
def face_detection(images=None,
paths=None,
data=None,
use_gpu=False,
output_dir='detection_result',
visualization=False,
shrink=0.5,
confs_threshold=0.6)
```
- ### 应用效果展示
- 样例结果示例:
<p align="center">
<img src="https://user-images.githubusercontent.com/22424850/131602468-351eb3fb-81e3-4294-ac8e-b49a3a0232cb.jpg" width='50%' hspace='10'/>
<br />
</p>
检测输入图片中的所有人脸位置
- ### 模型介绍
**参数**
- PyramidBox-Lite是基于2018年百度发表于计算机视觉顶级会议ECCV 2018的论文PyramidBox而研发的轻量级模型,模型基于主干网络FaceBoxes,对于光照、口罩遮挡、表情变化、尺度变化等常见问题具有很强的鲁棒性。该PaddleHub Module是针对于移动端优化过的模型,适合部署于移动端或者边缘检测等算力受限的设备上,并基于WIDER FACE数据集和百度自采人脸数据集进行训练,支持预测,可用于人脸检测。
* images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;
* paths (list\[str\]): 图片的路径;
* batch\_size (int): batch 的大小;
* use\_gpu (bool): 是否使用 GPU;
* visualization (bool): 是否将识别结果保存为图片文件;
* output\_dir (str): 图片的保存路径,默认设为 detection\_result;
* shrink (float): 用于设置图片的缩放比例,该值越大,则对于输入图片中的小尺寸人脸有更好的检测效果(模型计算成本越高),反之则对于大尺寸人脸有更好的检测效果。
* confs\_threshold (float): 置信度的阈值。
**返回**
## 二、安装
* res (list\[dict\]): 识别结果的列表,列表中每一个元素为 dict,各字段为:
* path (str): 原输入图片的路径;
* data (list): 检测结果,list的每一个元素为 dict,各字段为:
* confidence (float): 识别的置信度;
* left (int): 边界框的左上角x坐标;
* top (int): 边界框的左上角y坐标;
* right (int): 边界框的右下角x坐标;
* bottom (int): 边界框的右下角y坐标。
- ### 1、环境依赖
```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- paddlepaddle >= 1.6.2
将模型保存到指定路径。
- paddlehub >= 1.6.0 | [如何安装paddlehub](../../../../docs/docs_ch/get_start/installation.rst)
**参数**
- ### 2、安装
* dirname: 存在模型的目录名称
* model\_filename: 模型文件名称,默认为\_\_model\_\_
* params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效)
* combined: 是否将参数保存到统一的一个文件中
- ```shell
$ hub install pyramidbox_lite_mobile
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
## 代码示例
## 三、模型API预测
```python
import paddlehub as hub
import cv2
- ### 1、命令行预测
face_detector = hub.Module(name="pyramidbox_lite_mobile")
result = face_detector.face_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = face_detector.face_detection((paths=['/PATH/TO/IMAGE'])
```
- ```shell
$ hub run pyramidbox_lite_mobile --input_path "/PATH/TO/IMAGE"
```
- 通过命令行方式实现人脸检测模型的调用,更多请见 [PaddleHub命令行指令](../../../../docs/docs_ch/tutorial/cmd_usage.rst)
## 服务部署
- ### 2、代码示例
PaddleHub Serving可以部署一个在线人脸检测服务。
- ```python
import paddlehub as hub
import cv2
## 第一步:启动PaddleHub Serving
face_detector = hub.Module(name="pyramidbox_lite_mobile")
result = face_detector.face_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = face_detector.face_detection(paths=['/PATH/TO/IMAGE'])
```
运行启动命令:
```shell
$ hub serving start -m pyramidbox_lite_mobile
```
- ### 3、API
这样就完成了一个人脸检测服务化API的部署,默认端口号为8866。
- ```python
def face_detection(images=None,
paths=None,
use_gpu=False,
output_dir='detection_result',
visualization=False,
shrink=0.5,
confs_threshold=0.6)
```
**NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- 检测输入图片中的所有人脸位置。
## 第二步:发送预测请求
- **参数**
配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;<br/>
- paths (list\[str\]): 图片的路径;<br/>
- use\_gpu (bool): 是否使用 GPU;<br/>
- output\_dir (str): 图片的保存路径,默认设为 detection\_result;<br/>
- visualization (bool): 是否将识别结果保存为图片文件;<br/>
- shrink (float): 用于设置图片的缩放比例,该值越大,则对于输入图片中的小尺寸人脸有更好的检测效果(模型计算成本越高),反之则对于大尺寸人脸有更好的检测效果;<br/>
- confs\_threshold (float): 置信度的阈值。
```python
import requests
import json
import cv2
import base64
**NOTE:** paths和images两个参数选择其一进行提供数据
- **返回**
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
- res (list\[dict\]): 识别结果的列表,列表中每一个元素为 dict,各字段为:
- path (str): 原输入图片的路径
- data (list): 检测结果,list的每一个元素为 dict,各字段为:
- confidence (float): 识别的置信度
- left (int): 边界框的左上角x坐标
- top (int): 边界框的左上角y坐标
- right (int): 边界框的右下角x坐标
- bottom (int): 边界框的右下角y坐标
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/pyramidbox_lite_mobile"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
- ```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- 将模型保存到指定路径。
# 打印预测结果
print(r.json()["results"])
```
- **参数**
### 依赖
- dirname: 存在模型的目录名称; <br/>
- model\_filename: 模型文件名称,默认为\_\_model\_\_; <br/>
- params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效);<br/>
- combined: 是否将参数保存到统一的一个文件中。
paddlepaddle >= 1.6.2
paddlehub >= 1.6.0
## 四、服务部署
- PaddleHub Serving可以部署一个在线人脸检测服务。
- ### 第一步:启动PaddleHub Serving
- 运行启动命令:
- ```shell
$ hub serving start -m pyramidbox_lite_mobile
```
- 这样就完成了一个人脸检测服务化API的部署,默认端口号为8866。
- **NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- ### 第二步:发送预测请求
- 配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- ```python
import requests
import json
import cv2
import base64
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/pyramidbox_lite_mobile"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
# 打印预测结果
print(r.json()["results"])
```
## 五、更新历史
* 1.0.0
初始发布
* 1.2.0
- ```shell
$ hub install pyramidbox_lite_mobile==1.2.0
```
```shell
$ hub install pyramidbox_lite_mobile_mask==1.3.0
```
# pyramidbox_lite_mobile_mask
## 命令行预测
|模型名称|pyramidbox_lite_mobile_mask|
| :--- | :---: |
|类别|图像 - 人脸检测|
|网络|PyramidBox|
|数据集|WIDER FACE数据集 + 百度自采人脸数据集|
|是否支持Fine-tuning|否|
|模型大小|1.2MB|
|最新更新日期|2021-02-26|
|数据指标|-|
```
hub run pyramidbox_lite_mobile_mask --input_path "/PATH/TO/IMAGE"
```
## API
## 一、模型基本信息
```python
def __init__(face_detector_module=None)
```
- ### 应用效果展示
- 样例结果示例:
<p align="center">
<img src="https://user-images.githubusercontent.com/22424850/131603304-690a2e3b-9f24-42f6-9297-a12ada884191.jpg" width='50%' hspace='10'/>
<br />
</p>
**参数**
- ### 模型介绍
* face\_detector\_module (class): 人脸检测模型,默认为 pyramidbox\_lite\_mobile.
- PyramidBox-Lite是基于2018年百度发表于计算机视觉顶级会议ECCV 2018的论文PyramidBox而研发的轻量级模型,模型基于主干网络FaceBoxes,对于光照、口罩遮挡、表情变化、尺度变化等常见问题具有很强的鲁棒性。该PaddleHub Module是针对于移动端优化过的模型,适合部署于移动端或者边缘检测等算力受限的设备上,并基于WIDER FACE数据集和百度自采人脸数据集进行训练,支持预测,可用于检测人脸是否佩戴口罩。
```python
def face_detection(images=None,
paths=None,
batch_size=1,
use_gpu=False,
visualization=False,
output_dir='detection_result',
use_multi_scale=False,
shrink=0.5,
confs_threshold=0.6):
```
## 二、安装
识别输入图片中的所有的人脸,并判断有无戴口罩。
- ### 1、环境依赖
**参数**
- paddlepaddle >= 1.6.2
* images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;
* paths (list\[str\]): 图片的路径;
* batch\_size (int): batch 的大小;
* use\_gpu (bool): 是否使用 GPU;
* visualization (bool): 是否将识别结果保存为图片文件;
* output\_dir (str): 图片的保存路径,默认设为 detection\_result。
* use\_multi\_scale (bool) : 用于设置是否开启多尺度的人脸检测,开启多尺度人脸检测能够更好的检测到输入图像中不同尺寸的人脸,但是会增加模型计算量,降低预测速度;
* shrink (float): 用于设置图片的缩放比例,该值越大,则对于输入图片中的小尺寸人脸有更好的检测效果(模型计算成本越高),反之则对于大尺寸人脸有更好的检测效果;
* confs\_threshold (float): 人脸检测的置信度的阈值。
- paddlehub >= 1.6.0 | [如何安装paddlehub](../../../../docs/docs_ch/get_start/installation.rst)
**返回**
- ### 2、安装
* res (list\[dict\]): 识别结果的列表,列表元素为 dict, 有以下两个字段:
* path (str): 原图的路径。
* data (list\[dict\]): 识别的边界框列表,有以下字段:
* label (str): 识别标签,为 'NO MASK' 或者 'MASK';
* confidence (float): 识别的置信度;
* left (int): 边界框的左上角x坐标;
* top (int): 边界框的左上角y坐标;
* right (int): 边界框的右下角x坐标;
* bottom (int): 边界框的右下角y坐标;
- ```shell
$ hub install pyramidbox_lite_mobile_mask
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
```python
def set_face_detector_module(face_detector_module)
```
## 三、模型API预测
设置口罩检测模型中进行人脸检测的底座模型。
- ### 1、命令行预测
**参数**
- ```shell
$ hub run pyramidbox_lite_mobile_mask --input_path "/PATH/TO/IMAGE"
```
- 通过命令行方式实现人脸检测模型的调用,更多请见 [PaddleHub命令行指令](../../../../docs/docs_ch/tutorial/cmd_usage.rst)
* face\_detector\_module (class): 人脸检测模型
- ### 2、代码示例
```python
def get_face_detector_module()
```
- ```python
import paddlehub as hub
import cv2
获取口罩检测模型中进行人脸检测的底座模型。
mask_detector = hub.Module(name="pyramidbox_lite_mobile_mask")
result = mask_detector.face_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = mask_detector.face_detection(paths=['/PATH/TO/IMAGE'])
```
**返回**
- ### 3、API
* 当前模型使用的人脸检测模型。
- ```python
def __init__(face_detector_module=None)
```
```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- **参数**
将模型保存到指定路径
- face\_detector\_module (class): 人脸检测模型,默认为 pyramidbox\_lite\_mobile
**参数**
- ```python
def face_detection(images=None,
paths=None,
batch_size=1,
use_gpu=False,
visualization=False,
output_dir='detection_result',
use_multi_scale=False,
shrink=0.5,
confs_threshold=0.6)
```
* dirname: 存在模型的目录名称
* model\_filename: 模型文件名称,默认为\_\_model\_\_
* params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效)
* combined: 是否将参数保存到统一的一个文件中
- 识别输入图片中的所有的人脸,并判断有无戴口罩。
## 代码示例
- **参数**
```python
import paddlehub as hub
import cv2
- images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;<br/>
- paths (list\[str\]): 图片的路径;<br/>
- batch\_size (int): batch 的大小;<br/>
- use\_gpu (bool): 是否使用 GPU;<br/>
- visualization (bool): 是否将识别结果保存为图片文件;<br/>
- output\_dir (str): 图片的保存路径,默认设为 detection\_result;<br/>
- use\_multi\_scale (bool) : 用于设置是否开启多尺度的人脸检测,开启多尺度人脸检测能够更好的检测到输入图像中不同尺寸的人脸,但是会增加模型计算量,降低预测速度;<br/>
- shrink (float): 用于设置图片的缩放比例,该值越大,则对于输入图片中的小尺寸人脸有更好的检测效果(模型计算成本越高),反之则对于大尺寸人脸有更好的检测效果;<br/>
- confs\_threshold (float): 置信度的阈值。
mask_detector = hub.Module(name="pyramidbox_lite_mobile_mask")
**NOTE:** paths和images两个参数选择其一进行提供数据
result = mask_detector.face_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = mask_detector.face_detection(paths=['/PATH/TO/IMAGE'])
```
- **返回**
## 服务部署
- res (list\[dict\]): 识别结果的列表,列表中每一个元素为 dict,各字段为:
- path (str): 原输入图片的路径
- data (list): 检测结果,list的每一个元素为 dict,各字段为:
- label (str): 识别标签,为 'NO MASK' 或者 'MASK';
- confidence (float): 识别的置信度
- left (int): 边界框的左上角x坐标
- top (int): 边界框的左上角y坐标
- right (int): 边界框的右下角x坐标
- bottom (int): 边界框的右下角y坐标
PaddleHub Serving可以部署一个在线人脸关键点检测服务。
- ```python
def set_face_detector_module(face_detector_module)
```
- 设置口罩检测模型中进行人脸检测的底座模型。
- **参数**
## 第一步:启动PaddleHub Serving
- face\_detector\_module (class): 人脸检测模型。
运行启动命令:
```shell
$ hub serving start -m pyramidbox_lite_mobile_mask
```
- ```python
def get_face_detector_module()
```
- 获取口罩检测模型中进行人脸检测的底座模型。
- **返回**
这样就完成了一个人脸关键点服务化API的部署,默认端口号为8866。
- 当前模型使用的人脸检测模型
**NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
## 第二步:发送预测请求
配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- ```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- 将模型保存到指定路径。
```python
import requests
import json
import cv2
import base64
- **参数**
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
- dirname: 存在模型的目录名称; <br/>
- model\_filename: 模型文件名称,默认为\_\_model\_\_; <br/>
- params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效);<br/>
- combined: 是否将参数保存到统一的一个文件中。
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/pyramidbox_lite_mobile_mask"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
# 打印预测结果
print(r.json()["results"])
```
## 四、服务部署
## Paddle Lite部署
- PaddleHub Serving可以部署一个在线口罩检测服务。
1. 通过python执行以下代码,保存模型
- ### 第一步:启动PaddleHub Serving
```python
import paddlehub as hub
pyramidbox_lite_mobile_mask = hub.Module(name="pyramidbox_lite_mobile_mask")
- 运行启动命令:
- ```shell
$ hub serving start -m pyramidbox_lite_mobile_mask
```
# 将模型保存在test_program文件夹之中
pyramidbox_lite_mobile_mask.save_inference_model(dirname="test_program")
```
- 这样就完成了一个口罩检测服务化API的部署,默认端口号为8866。
通过以上命令,可以获得人脸检测和口罩佩戴判断模型,分别存储在pyramidbox\_lite和mask\_detector之中。文件夹中的\_\_model\_\_是模型结构文件,\_\_params\_\_文件是权重文件
- **NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置
2. 进行模型转换
- ### 第二步:发送预测请求
从paddlehub下载的是预测模型,可以使用PaddleLite提供的模型优化工具OPT对预测模型进行转换,转换之后进而可以实现在手机等端侧硬件上的部署,具体请请参考[OPT工具](https://paddle-lite.readthedocs.io/zh/latest/user_guides/model_optimize_tool.html)
- 配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
3. 模型通过Paddle Lite进行部署
- ```python
import requests
import json
import cv2
import base64
参考[Paddle-Lite口罩检测模型部署教程](https://github.com/PaddlePaddle/Paddle-Lite/tree/develop/lite/demo/cxx)
### 依赖
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
paddlepaddle >= 1.6.2
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/pyramidbox_lite_mobile_mask"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
paddlehub >= 1.6.0
# 打印预测结果
print(r.json()["results"])
```
## 五、Paddle Lite部署
- ### 通过python执行以下代码,保存模型
- ```python
import paddlehub as hub
pyramidbox_lite_mobile_mask = hub.Module(name="pyramidbox_lite_mobile_mask")
# 将模型保存在test_program文件夹之中
pyramidbox_lite_mobile_mask.save_inference_model(dirname="test_program")
```
通过以上命令,可以获得人脸检测和口罩佩戴判断模型,分别存储在pyramidbox\_lite和mask\_detector之中。文件夹中的\_\_model\_\_是模型结构文件,\_\_params\_\_文件是权重文件。
- ### 进行模型转换
- 从paddlehub下载的是预测模型,可以使用PaddleLite提供的模型优化工具OPT对预测模型进行转换,转换之后进而可以实现在手机等端侧硬件上的部署,具体请请参考[OPT工具](https://paddle-lite.readthedocs.io/zh/latest/user_guides/model_optimize_tool.html)
- ### 模型通过Paddle Lite进行部署
- 参考[Paddle-Lite口罩检测模型部署教程](https://github.com/PaddlePaddle/Paddle-Lite/tree/develop/lite/demo/cxx)
## 五、更新历史
* 1.0.0
初始发布
* 1.3.0
- ```shell
$ hub install pyramidbox_lite_mobile_mask==1.3.0
```
```shell
$ hub install pyramidbox_lite_server==1.2.0
```
# pyramidbox_lite_server
## 命令行预测
|模型名称|pyramidbox_lite_server|
| :--- | :---: |
|类别|图像 - 人脸检测|
|网络|PyramidBox|
|数据集|WIDER FACE数据集 + 百度自采人脸数据集|
|是否支持Fine-tuning|否|
|模型大小|8MB|
|最新更新日期|2021-02-26|
|数据指标|-|
```
hub run pyramidbox_lite_server --input_path "/PATH/TO/IMAGE"
```
## API
## 一、模型基本信息
```python
def face_detection(images=None,
paths=None,
data=None,
use_gpu=False,
output_dir='detection_result',
visualization=False,
shrink=0.5,
confs_threshold=0.6)
```
- ### 应用效果展示
- 样例结果示例:
<p align="center">
<img src="https://user-images.githubusercontent.com/22424850/131602468-351eb3fb-81e3-4294-ac8e-b49a3a0232cb.jpg" width='50%' hspace='10'/>
<br />
</p>
检测输入图片中的所有人脸位置
- ### 模型介绍
**参数**
- PyramidBox-Lite是基于2018年百度发表于计算机视觉顶级会议ECCV 2018的论文PyramidBox而研发的轻量级模型,模型基于主干网络FaceBoxes,对于光照、口罩遮挡、表情变化、尺度变化等常见问题具有很强的鲁棒性。该PaddleHub Module基于WIDER FACE数据集和百度自采人脸数据集进行训练,支持预测,可用于人脸检测。
* images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;
* paths (list\[str\]): 图片的路径;
* batch\_size (int): batch 的大小;
* use\_gpu (bool): 是否使用 GPU;
* visualization (bool): 是否将识别结果保存为图片文件;
* output\_dir (str): 图片的保存路径,默认设为 detection\_result;
* shrink (float): 用于设置图片的缩放比例,该值越大,则对于输入图片中的小尺寸人脸有更好的检测效果(模型计算成本越高),反之则对于大尺寸人脸有更好的检测效果。
* confs\_threshold (float): 置信度的阈值。
**返回**
## 二、安装
* res (list\[dict\]): 识别结果的列表,列表中每一个元素为 dict,各字段为:
* path (str): 原输入图片的路径;
* data (list): 检测结果,list 的每一个元素为 dict,各字段为:
* confidence (float): 识别的置信度;
* left (int): 边界框的左上角x坐标;
* top (int): 边界框的左上角y坐标;
* right (int): 边界框的右下角x坐标;
* bottom (int): 边界框的右下角y坐标。
- ### 1、环境依赖
```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- paddlepaddle >= 1.6.2
将模型保存到指定路径。
- paddlehub >= 1.6.0 | [如何安装paddlehub](../../../../docs/docs_ch/get_start/installation.rst)
**参数**
- ### 2、安装
* dirname: 存在模型的目录名称
* model\_filename: 模型文件名称,默认为\_\_model\_\_
* params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效)
* combined: 是否将参数保存到统一的一个文件中
- ```shell
$ hub install pyramidbox_lite_server
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
## 代码示例
## 三、模型API预测
```python
import paddlehub as hub
import cv2
- ### 1、命令行预测
face_detector = hub.Module(name="pyramidbox_lite_server")
result = face_detector.face_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = face_detector.face_detection((paths=['/PATH/TO/IMAGE'])
```
- ```shell
$ hub run pyramidbox_lite_server --input_path "/PATH/TO/IMAGE"
```
- 通过命令行方式实现人脸检测模型的调用,更多请见 [PaddleHub命令行指令](../../../../docs/docs_ch/tutorial/cmd_usage.rst)
## 服务部署
- ### 2、代码示例
PaddleHub Serving可以部署一个在线人脸检测服务。
- ```python
import paddlehub as hub
import cv2
## 第一步:启动PaddleHub Serving
face_detector = hub.Module(name="pyramidbox_lite_server")
result = face_detector.face_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = face_detector.face_detection(paths=['/PATH/TO/IMAGE'])
```
运行启动命令:
```shell
$ hub serving start -m pyramidbox_lite_server
```
- ### 3、API
这样就完成了一个人脸检测服务化API的部署,默认端口号为8866。
- ```python
def face_detection(images=None,
paths=None,
use_gpu=False,
output_dir='detection_result',
visualization=False,
shrink=0.5,
confs_threshold=0.6)
```
**NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- 检测输入图片中的所有人脸位置。
## 第二步:发送预测请求
- **参数**
配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;<br/>
- paths (list\[str\]): 图片的路径;<br/>
- use\_gpu (bool): 是否使用 GPU;<br/>
- output\_dir (str): 图片的保存路径,默认设为 detection\_result;<br/>
- visualization (bool): 是否将识别结果保存为图片文件;<br/>
- shrink (float): 用于设置图片的缩放比例,该值越大,则对于输入图片中的小尺寸人脸有更好的检测效果(模型计算成本越高),反之则对于大尺寸人脸有更好的检测效果;<br/>
- confs\_threshold (float): 置信度的阈值。
```python
import requests
import json
import cv2
import base64
**NOTE:** paths和images两个参数选择其一进行提供数据
- **返回**
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
- res (list\[dict\]): 识别结果的列表,列表中每一个元素为 dict,各字段为:
- path (str): 原输入图片的路径
- data (list): 检测结果,list的每一个元素为 dict,各字段为:
- confidence (float): 识别的置信度
- left (int): 边界框的左上角x坐标
- top (int): 边界框的左上角y坐标
- right (int): 边界框的右下角x坐标
- bottom (int): 边界框的右下角y坐标
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/pyramidbox_lite_server"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
- ```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- 将模型保存到指定路径。
# 打印预测结果
print(r.json()["results"])
```
- **参数**
### 依赖
- dirname: 存在模型的目录名称; <br/>
- model\_filename: 模型文件名称,默认为\_\_model\_\_; <br/>
- params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效);<br/>
- combined: 是否将参数保存到统一的一个文件中。
paddlepaddle >= 1.6.2
paddlehub >= 1.6.0
## 四、服务部署
- PaddleHub Serving可以部署一个在线人脸检测服务。
- ### 第一步:启动PaddleHub Serving
- 运行启动命令:
- ```shell
$ hub serving start -m pyramidbox_lite_server
```
- 这样就完成了一个人脸检测服务化API的部署,默认端口号为8866。
- **NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- ### 第二步:发送预测请求
- 配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- ```python
import requests
import json
import cv2
import base64
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/pyramidbox_lite_server"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
# 打印预测结果
print(r.json()["results"])
```
## 五、更新历史
* 1.0.0
初始发布
* 1.2.0
修复numpy数据读取问题
- ```shell
$ hub install pyramidbox_lite_server==1.2.0
```
```shell
$ hub install pyramidbox_lite_server_mask==1.3.0
```
# pyramidbox_lite_server_mask
## 命令行预测
|模型名称|pyramidbox_lite_server_mask|
| :--- | :---: |
|类别|图像 - 人脸检测|
|网络|PyramidBox|
|数据集|WIDER FACE数据集 + 百度自采人脸数据集|
|是否支持Fine-tuning|否|
|模型大小|1.2MB|
|最新更新日期|2021-02-26|
|数据指标|-|
```
hub run pyramidbox_lite_server_mask --input_path "/PATH/TO/IMAGE"
```
## API
## 一、模型基本信息
```python
def __init__(face_detector_module=None)
```
- ### 应用效果展示
- 样例结果示例:
<p align="center">
<img src="https://user-images.githubusercontent.com/22424850/131603304-690a2e3b-9f24-42f6-9297-a12ada884191.jpg" width='50%' hspace='10'/>
<br />
</p>
**参数**
- ### 模型介绍
* face\_detector\_module (class): 人脸检测模型,默认为 pyramidbox\_lite\_server.
- PyramidBox-Lite是基于2018年百度发表于计算机视觉顶级会议ECCV 2018的论文PyramidBox而研发的轻量级模型,模型基于主干网络FaceBoxes,对于光照、口罩遮挡、表情变化、尺度变化等常见问题具有很强的鲁棒性。该PaddleHub Module基于WIDER FACE数据集和百度自采人脸数据集进行训练,支持预测,可用于检测人脸是否佩戴口罩。
```python
def face_detection(images=None,
paths=None,
batch_size=1,
use_gpu=False,
visualization=False,
output_dir='detection_result',
use_multi_scale=False,
shrink=0.5,
confs_threshold=0.6):
```
## 二、安装
识别输入图片中的所有的人脸,并判断有无戴口罩。
- ### 1、环境依赖
**参数**
- paddlepaddle >= 1.6.2
* images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;
* paths (list\[str\]): 图片的路径;
* batch\_size (int): batch 的大小;
* use\_gpu (bool): 是否使用 GPU;
* visualization (bool): 是否将识别结果保存为图片文件;
* output\_dir (str): 图片的保存路径,默认设为 detection\_result。
* use\_multi\_scale (bool) : 用于设置是否开启多尺度的人脸检测,开启多尺度人脸检测能够更好的检测到输入图像中不同尺寸的人脸,但是会增加模型计算量,降低预测速度;
* shrink (float): 用于设置图片的缩放比例,该值越大,则对于输入图片中的小尺寸人脸有更好的检测效果(模型计算成本越高),反之则对于大尺寸人脸有更好的检测效果;
* confs\_threshold (float): 人脸检测的置信度的阈值。
- paddlehub >= 1.6.0 | [如何安装paddlehub](../../../../docs/docs_ch/get_start/installation.rst)
**返回**
- ### 2、安装
* res (list\[dict\]): 识别结果的列表,列表元素为 dict, 有以下两个字段:
* path (str): 原图的路径。
* data (list\[dict\]): 识别的边界框列表,有以下字段:
* label (str): 识别标签,为 'NO MASK' 或者 'MASK';
* confidence (float): 识别的置信度;
* left (int): 边界框的左上角x坐标;
* top (int): 边界框的左上角y坐标;
* right (int): 边界框的右下角x坐标;
* bottom (int): 边界框的右下角y坐标;
- ```shell
$ hub install pyramidbox_lite_server_mask
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
```python
def set_face_detector_module(face_detector_module)
```
## 三、模型API预测
设置口罩检测模型中进行人脸检测的底座模型。
- ### 1、命令行预测
**参数**
- ```shell
$ hub run pyramidbox_lite_server_mask --input_path "/PATH/TO/IMAGE"
```
- 通过命令行方式实现人脸检测模型的调用,更多请见 [PaddleHub命令行指令](../../../../docs/docs_ch/tutorial/cmd_usage.rst)
* face\_detector\_module (class): 人脸检测模型
- ### 2、代码示例
```python
def get_face_detector_module()
```
- ```python
import paddlehub as hub
import cv2
获取口罩检测模型中进行人脸检测的底座模型。
mask_detector = hub.Module(name="pyramidbox_lite_server_mask")
result = mask_detector.face_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = mask_detector.face_detection(paths=['/PATH/TO/IMAGE'])
```
**返回**
- ### 3、API
* 当前模型使用的人脸检测模型。
- ```python
def __init__(face_detector_module=None)
```
```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- **参数**
将模型保存到指定路径
- face\_detector\_module (class): 人脸检测模型,默认为 pyramidbox\_lite\_server
**参数**
- ```python
def face_detection(images=None,
paths=None,
batch_size=1,
use_gpu=False,
visualization=False,
output_dir='detection_result',
use_multi_scale=False,
shrink=0.5,
confs_threshold=0.6)
```
* dirname: 存在模型的目录名称
* model\_filename: 模型文件名称,默认为\_\_model\_\_
* params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效)
* combined: 是否将参数保存到统一的一个文件中
- 识别输入图片中的所有的人脸,并判断有无戴口罩。
## 代码示例
- **参数**
```python
import paddlehub as hub
import cv2
- images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;<br/>
- paths (list\[str\]): 图片的路径;<br/>
- batch\_size (int): batch 的大小;<br/>
- use\_gpu (bool): 是否使用 GPU;<br/>
- visualization (bool): 是否将识别结果保存为图片文件;<br/>
- output\_dir (str): 图片的保存路径,默认设为 detection\_result;<br/>
- use\_multi\_scale (bool) : 用于设置是否开启多尺度的人脸检测,开启多尺度人脸检测能够更好的检测到输入图像中不同尺寸的人脸,但是会增加模型计算量,降低预测速度;<br/>
- shrink (float): 用于设置图片的缩放比例,该值越大,则对于输入图片中的小尺寸人脸有更好的检测效果(模型计算成本越高),反之则对于大尺寸人脸有更好的检测效果;<br/>
- confs\_threshold (float): 置信度的阈值。
mask_detector = hub.Module(name="pyramidbox_lite_server_mask")
**NOTE:** paths和images两个参数选择其一进行提供数据
result = mask_detector.face_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = mask_detector.face_detection(paths=['/PATH/TO/IMAGE'])
```
- **返回**
## 服务部署
- res (list\[dict\]): 识别结果的列表,列表中每一个元素为 dict,各字段为:
- path (str): 原输入图片的路径
- data (list): 检测结果,list的每一个元素为 dict,各字段为:
- label (str): 识别标签,为 'NO MASK' 或者 'MASK';
- confidence (float): 识别的置信度
- left (int): 边界框的左上角x坐标
- top (int): 边界框的左上角y坐标
- right (int): 边界框的右下角x坐标
- bottom (int): 边界框的右下角y坐标
PaddleHub Serving可以部署一个在线人脸关键点检测服务。
- ```python
def set_face_detector_module(face_detector_module)
```
- 设置口罩检测模型中进行人脸检测的底座模型。
- **参数**
## 第一步:启动PaddleHub Serving
- face\_detector\_module (class): 人脸检测模型。
运行启动命令:
```shell
$ hub serving start -m pyramidbox_lite_server_mask
```
- ```python
def get_face_detector_module()
```
- 获取口罩检测模型中进行人脸检测的底座模型。
- **返回**
这样就完成了一个人脸关键点服务化API的部署,默认端口号为8866。
- 当前模型使用的人脸检测模型
**NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
## 第二步:发送预测请求
配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- ```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- 将模型保存到指定路径。
```python
import requests
import json
import cv2
import base64
- **参数**
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
- dirname: 存在模型的目录名称; <br/>
- model\_filename: 模型文件名称,默认为\_\_model\_\_; <br/>
- params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效);<br/>
- combined: 是否将参数保存到统一的一个文件中。
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/pyramidbox_lite_server_mask"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
# 打印预测结果
print(r.json()["results"])
```
## 四、服务部署
## Paddle Lite部署
- PaddleHub Serving可以部署一个在线口罩检测服务。
1. 通过python执行以下代码,保存模型
- ### 第一步:启动PaddleHub Serving
```python
import paddlehub as hub
pyramidbox_lite_server_mask = hub.Module(name="pyramidbox_lite_server_mask")
- 运行启动命令:
- ```shell
$ hub serving start -m pyramidbox_lite_server_mask
```
# 将模型保存在test_program文件夹之中
pyramidbox_lite_server_mask.save_inference_model(dirname="test_program")
```
- 这样就完成了一个口罩检测服务化API的部署,默认端口号为8866。
通过以上命令,可以获得人脸检测和口罩佩戴判断模型,分别存储在pyramidbox\_lite和mask\_detector之中。文件夹中的\_\_model\_\_是模型结构文件,\_\_params\_\_文件是权重文件
- **NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置
2. 进行模型转换
- ### 第二步:发送预测请求
从paddlehub下载的是预测模型,可以使用PaddleLite提供的模型优化工具OPT对预测模型进行转换,转换之后进而可以实现在手机等端侧硬件上的部署,具体请请参考[OPT工具](https://paddle-lite.readthedocs.io/zh/latest/user_guides/model_optimize_tool.html)
- 配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
3. 模型通过Paddle Lite进行部署
- ```python
import requests
import json
import cv2
import base64
参考[Paddle-Lite口罩检测模型部署教程](https://github.com/PaddlePaddle/Paddle-Lite/tree/develop/lite/demo/cxx)
### 依赖
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
paddlepaddle >= 1.6.2
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/pyramidbox_lite_server_mask"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
paddlehub >= 1.6.0
# 打印预测结果
print(r.json()["results"])
```
## 五、Paddle Lite部署
- ### 通过python执行以下代码,保存模型
- ```python
import paddlehub as hub
pyramidbox_lite_server_mask = hub.Module(name="pyramidbox_lite_server_mask")
# 将模型保存在test_program文件夹之中
pyramidbox_lite_server_mask.save_inference_model(dirname="test_program")
```
通过以上命令,可以获得人脸检测和口罩佩戴判断模型,分别存储在pyramidbox\_lite和mask\_detector之中。文件夹中的\_\_model\_\_是模型结构文件,\_\_params\_\_文件是权重文件。
- ### 进行模型转换
- 从paddlehub下载的是预测模型,可以使用PaddleLite提供的模型优化工具OPT对预测模型进行转换,转换之后进而可以实现在手机等端侧硬件上的部署,具体请请参考[OPT工具](https://paddle-lite.readthedocs.io/zh/latest/user_guides/model_optimize_tool.html)
- ### 模型通过Paddle Lite进行部署
- 参考[Paddle-Lite口罩检测模型部署教程](https://github.com/PaddlePaddle/Paddle-Lite/tree/develop/lite/demo/cxx)
## 五、更新历史
* 1.0.0
初始发布
* 1.3.1
- ```shell
$ hub install pyramidbox_lite_server_mask==1.3.1
```
......@@ -43,7 +43,8 @@ def bbox_vote(det):
det_accu[:, 0:4] = det_accu[:, 0:4] * np.tile(det_accu[:, -1:], (1, 4))
max_score = np.max(det_accu[:, 4])
det_accu_sum = np.zeros((1, 5))
det_accu_sum[:, 0:4] = np.sum(det_accu[:, 0:4], axis=0) / np.sum(det_accu[:, -1:])
det_accu_sum[:, 0:4] = np.sum(
det_accu[:, 0:4], axis=0) / np.sum(det_accu[:, -1:])
det_accu_sum[:, 4] = max_score
try:
dets = np.row_stack((dets, det_accu_sum))
......@@ -53,26 +54,38 @@ def bbox_vote(det):
return dets
def crop(image, pts, shift=0, scale=1.5, rotate=0, res_width=128, res_height=128):
def crop(image,
pts,
shift=0,
scale=1.5,
rotate=0,
res_width=128,
res_height=128):
res = (res_width, res_height)
idx1 = 0
idx2 = 1
# angle
alpha = 0
if pts[idx2, 0] != -1 and pts[idx2, 1] != -1 and pts[idx1, 0] != -1 and pts[idx1, 1] != -1:
alpha = math.atan2(pts[idx2, 1] - pts[idx1, 1], pts[idx2, 0] - pts[idx1, 0]) * 180 / math.pi
if pts[idx2, 0] != -1 and pts[idx2, 1] != -1 and pts[idx1, 0] != -1 and pts[
idx1, 1] != -1:
alpha = math.atan2(pts[idx2, 1] - pts[idx1, 1],
pts[idx2, 0] - pts[idx1, 0]) * 180 / math.pi
pts[pts == -1] = np.inf
coord_min = np.min(pts, 0)
pts[pts == np.inf] = -1
coord_max = np.max(pts, 0)
# coordinates of center point
c = np.array([coord_max[0] - (coord_max[0] - coord_min[0]) / 2,
coord_max[1] - (coord_max[1] - coord_min[1]) / 2]) # center
max_wh = max((coord_max[0] - coord_min[0]) / 2, (coord_max[1] - coord_min[1]) / 2)
c = np.array([
coord_max[0] - (coord_max[0] - coord_min[0]) / 2,
coord_max[1] - (coord_max[1] - coord_min[1]) / 2
]) # center
max_wh = max((coord_max[0] - coord_min[0]) / 2,
(coord_max[1] - coord_min[1]) / 2)
# Shift the center point, rot add eyes angle
c = c + shift * max_wh
rotate = rotate + alpha
M = cv2.getRotationMatrix2D((c[0], c[1]), rotate, res[0] / (2 * max_wh * scale))
M = cv2.getRotationMatrix2D((c[0], c[1]), rotate,
res[0] / (2 * max_wh * scale))
M[0, 2] = M[0, 2] - (c[0] - res[0] / 2.0)
M[1, 2] = M[1, 2] - (c[1] - res[0] / 2.0)
image_out = cv2.warpAffine(image, M, res)
......@@ -84,24 +97,27 @@ def color_normalize(image, mean, std=None):
image = np.repeat(image, axis=2)
h, w, c = image.shape
image = np.transpose(image, (2, 0, 1))
image = np.subtract(image.reshape(c, -1), mean[:, np.newaxis]).reshape(-1, h, w)
image = np.subtract(image.reshape(c, -1), mean[:, np.newaxis]).reshape(
-1, h, w)
image = np.transpose(image, (1, 2, 0))
return image
def process_image(org_im, face):
pts = np.array([
face['left'], face['top'], face['right'], face['top'], face['left'], face['bottom'], face['right'],
face['bottom']
face['left'], face['top'], face['right'], face['top'], face['left'],
face['bottom'], face['right'], face['bottom']
]).reshape(4, 2).astype(np.float32)
image_in, M = crop(org_im, pts)
image_in = image_in / 256.0
image_in = color_normalize(image_in, mean=np.array([0.5, 0.5, 0.5]))
image_in = image_in.astype(np.float32).transpose([2, 0, 1]).reshape(-1, 3, 128, 128)
image_in = image_in.astype(np.float32).transpose([2, 0, 1]).reshape(
-1, 3, 128, 128)
return image_in
def reader(face_detector, shrink, confs_threshold, images, paths, use_gpu, use_multi_scale):
def reader(face_detector, shrink, confs_threshold, images, paths, use_gpu,
use_multi_scale):
"""
Preprocess to yield image.
......@@ -126,7 +142,8 @@ def reader(face_detector, shrink, confs_threshold, images, paths, use_gpu, use_m
assert type(paths) is list, "paths should be a list."
for im_path in paths:
each = OrderedDict()
assert os.path.isfile(im_path), "The {} isn't a valid file path.".format(im_path)
assert os.path.isfile(
im_path), "The {} isn't a valid file path.".format(im_path)
im = cv2.imread(im_path)
each['org_im'] = im
each['org_im_path'] = im_path
......@@ -136,7 +153,8 @@ def reader(face_detector, shrink, confs_threshold, images, paths, use_gpu, use_m
for im in images:
each = OrderedDict()
each['org_im'] = im
each['org_im_path'] = 'ndarray_time={}'.format(round(time.time(), 6) * 1e6)
each['org_im_path'] = 'ndarray_time={}'.format(
round(time.time(), 6) * 1e6)
component.append(each)
for element in component:
......@@ -153,19 +171,30 @@ def reader(face_detector, shrink, confs_threshold, images, paths, use_gpu, use_m
_s = list()
for _face in _detect_res[0]['data']:
_face_list = [_face['left'], _face['top'], _face['right'], _face['bottom'], _face['confidence']]
_face_list = [
_face['left'], _face['top'], _face['right'],
_face['bottom'], _face['confidence']
]
_s.append(_face_list)
if _s:
scale_res.append(np.array(_s))
scale_res = np.row_stack(scale_res)
scale_res = bbox_vote(scale_res)
keep_index = np.where(scale_res[:, 4] >= confs_threshold)[0]
scale_res = scale_res[keep_index, :]
for data in scale_res:
face = {'left': data[0], 'top': data[1], 'right': data[2], 'bottom': data[3], 'confidence': data[4]}
detect_faces.append(face)
if scale_res:
scale_res = np.row_stack(scale_res)
scale_res = bbox_vote(scale_res)
keep_index = np.where(scale_res[:, 4] >= confs_threshold)[0]
scale_res = scale_res[keep_index, :]
for data in scale_res:
face = {
'left': data[0],
'top': data[1],
'right': data[2],
'bottom': data[3],
'confidence': data[4]
}
detect_faces.append(face)
else:
detect_faces = []
else:
_detect_res = face_detector.face_detection(
images=[element['org_im']],
......
......@@ -23,14 +23,15 @@ from pyramidbox_lite_server_mask.processor import postprocess, base64_to_cv2
author_email="",
summary=
"PyramidBox-Lite-Server-Mask is a high-performance face detection model used to detect whether people wear masks.",
version="1.3.0")
version="1.3.1")
class PyramidBoxLiteServerMask(hub.Module):
def _initialize(self, face_detector_module=None):
"""
Args:
face_detector_module (class): module to detect face.
"""
self.default_pretrained_model_path = os.path.join(self.directory, "pyramidbox_lite_server_mask_model")
self.default_pretrained_model_path = os.path.join(
self.directory, "pyramidbox_lite_server_mask_model")
if face_detector_module is None:
self.face_detector = hub.Module(name='pyramidbox_lite_server')
else:
......@@ -56,7 +57,8 @@ class PyramidBoxLiteServerMask(hub.Module):
if use_gpu:
gpu_config = AnalysisConfig(self.default_pretrained_model_path)
gpu_config.disable_glog_info()
gpu_config.enable_use_gpu(memory_pool_init_size_mb=1000, device_id=0)
gpu_config.enable_use_gpu(
memory_pool_init_size_mb=1000, device_id=0)
self.gpu_predictor = create_paddle_predictor(gpu_config)
def set_face_detector_module(self, face_detector_module):
......@@ -105,7 +107,7 @@ class PyramidBoxLiteServerMask(hub.Module):
int(_places[0])
except:
raise RuntimeError(
"Environment Variable CUDA_VISIBLE_DEVICES is not set correctly. If you wanna use gpu, please set CUDA_VISIBLE_DEVICES as cuda_device_id."
"Attempt to use GPU for prediction, but environment variable CUDA_VISIBLE_DEVICES was not set correctly."
)
# compatibility with older versions
......@@ -121,13 +123,16 @@ class PyramidBoxLiteServerMask(hub.Module):
# get all data
all_element = list()
for yield_data in reader(self.face_detector, shrink, confs_threshold, images, paths, use_gpu, use_multi_scale):
for yield_data in reader(self.face_detector, shrink, confs_threshold,
images, paths, use_gpu, use_multi_scale):
all_element.append(yield_data)
image_list = list()
element_image_num = list()
for i in range(len(all_element)):
element_image = [handled['image'] for handled in all_element[i]['preprocessed']]
element_image = [
handled['image'] for handled in all_element[i]['preprocessed']
]
element_image_num.append(len(element_image))
image_list.extend(element_image)
......@@ -146,7 +151,9 @@ class PyramidBoxLiteServerMask(hub.Module):
image_arr = np.squeeze(np.array(batch_data), axis=1)
image_tensor = PaddleTensor(image_arr.copy())
data_out = self.gpu_predictor.run([image_tensor]) if use_gpu else self.cpu_predictor.run([image_tensor])
data_out = self.gpu_predictor.run([
image_tensor
]) if use_gpu else self.cpu_predictor.run([image_tensor])
# len(data_out) == 1
# data_out[0].as_ndarray().shape == (-1, 2)
data_out = data_out[0].as_ndarray()
......@@ -156,7 +163,9 @@ class PyramidBoxLiteServerMask(hub.Module):
# postprocess one by one
res = list()
for i in range(len(all_element)):
detect_faces_list = [handled['face'] for handled in all_element[i]['preprocessed']]
detect_faces_list = [
handled['face'] for handled in all_element[i]['preprocessed']
]
interval_left = sum(element_image_num[0:i])
interval_right = interval_left + element_image_num[i]
out = postprocess(
......@@ -169,16 +178,31 @@ class PyramidBoxLiteServerMask(hub.Module):
res.append(out)
return res
def save_inference_model(self, dirname, model_filename=None, params_filename=None, combined=True):
def save_inference_model(self,
dirname,
model_filename=None,
params_filename=None,
combined=True):
classifier_dir = os.path.join(dirname, 'mask_detector')
detector_dir = os.path.join(dirname, 'pyramidbox_lite')
self._save_classifier_model(classifier_dir, model_filename, params_filename, combined)
self._save_detector_model(detector_dir, model_filename, params_filename, combined)
self._save_classifier_model(classifier_dir, model_filename,
params_filename, combined)
self._save_detector_model(detector_dir, model_filename, params_filename,
combined)
def _save_detector_model(self, dirname, model_filename=None, params_filename=None, combined=True):
self.face_detector.save_inference_model(dirname, model_filename, params_filename, combined)
def _save_detector_model(self,
dirname,
model_filename=None,
params_filename=None,
combined=True):
self.face_detector.save_inference_model(dirname, model_filename,
params_filename, combined)
def _save_classifier_model(self, dirname, model_filename=None, params_filename=None, combined=True):
def _save_classifier_model(self,
dirname,
model_filename=None,
params_filename=None,
combined=True):
if combined:
model_filename = "__model__" if not model_filename else model_filename
params_filename = "__params__" if not params_filename else params_filename
......@@ -216,9 +240,12 @@ class PyramidBoxLiteServerMask(hub.Module):
prog='hub run {}'.format(self.name),
usage='%(prog)s',
add_help=True)
self.arg_input_group = self.parser.add_argument_group(title="Input options", description="Input data. Required")
self.arg_input_group = self.parser.add_argument_group(
title="Input options", description="Input data. Required")
self.arg_config_group = self.parser.add_argument_group(
title="Config options", description="Run configuration for controlling module behavior, not required.")
title="Config options",
description=
"Run configuration for controlling module behavior, not required.")
self.add_module_config_arg()
self.add_module_input_arg()
args = self.parser.parse_args(argvs)
......@@ -236,21 +263,36 @@ class PyramidBoxLiteServerMask(hub.Module):
Add the command config options.
"""
self.arg_config_group.add_argument(
'--use_gpu', type=ast.literal_eval, default=False, help="whether use GPU or not")
'--use_gpu',
type=ast.literal_eval,
default=False,
help="whether use GPU or not")
self.arg_config_group.add_argument(
'--output_dir', type=str, default='detection_result', help="The directory to save output images.")
'--output_dir',
type=str,
default='detection_result',
help="The directory to save output images.")
self.arg_config_group.add_argument(
'--visualization', type=ast.literal_eval, default=False, help="whether to save output as images.")
'--visualization',
type=ast.literal_eval,
default=False,
help="whether to save output as images.")
def add_module_input_arg(self):
"""
Add the command input options.
"""
self.arg_input_group.add_argument('--input_path', type=str, help="path to image.")
self.arg_input_group.add_argument(
'--input_path', type=str, help="path to image.")
self.arg_input_group.add_argument(
'--shrink',
type=ast.literal_eval,
default=0.5,
help="resize the image to `shrink * original_shape` before feeding into network.")
help=
"resize the image to `shrink * original_shape` before feeding into network."
)
self.arg_input_group.add_argument(
'--confs_threshold', type=ast.literal_eval, default=0.6, help="confidence threshold.")
'--confs_threshold',
type=ast.literal_eval,
default=0.6,
help="confidence threshold.")
......@@ -57,7 +57,8 @@ def get_save_image_name(org_im, org_im_path, output_dir):
# save image path
save_im_path = os.path.join(output_dir, im_prefix + ext)
if os.path.exists(save_im_path):
save_im_path = os.path.join(output_dir, im_prefix + 'time={}'.format(int(time.time())) + ext)
save_im_path = os.path.join(
output_dir, im_prefix + 'time={}'.format(int(time.time())) + ext)
return save_im_path
......@@ -68,13 +69,19 @@ def draw_bounding_box_on_image(save_im_path, output_data):
for bbox in output_data:
# draw bouding box
if bbox['label'] == "MASK":
draw.line([(bbox['left'], bbox['top']), (bbox['left'], bbox['bottom']), (bbox['right'], bbox['bottom']),
(bbox['right'], bbox['top']), (bbox['left'], bbox['top'])],
draw.line([(bbox['left'], bbox['top']),
(bbox['left'], bbox['bottom']),
(bbox['right'], bbox['bottom']),
(bbox['right'], bbox['top']),
(bbox['left'], bbox['top'])],
width=2,
fill='green')
else:
draw.line([(bbox['left'], bbox['top']), (bbox['left'], bbox['bottom']), (bbox['right'], bbox['bottom']),
(bbox['right'], bbox['top']), (bbox['left'], bbox['top'])],
draw.line([(bbox['left'], bbox['top']),
(bbox['left'], bbox['bottom']),
(bbox['right'], bbox['bottom']),
(bbox['right'], bbox['top']),
(bbox['left'], bbox['top'])],
width=2,
fill='red')
# draw label
......@@ -88,13 +95,16 @@ def draw_bounding_box_on_image(save_im_path, output_data):
text_fill = (0)
draw.rectangle(
xy=(bbox['left'], bbox['top'] - (textsize_height + 5), bbox['left'] + textsize_width + 10, bbox['top'] - 3),
xy=(bbox['left'], bbox['top'] - (textsize_height + 5),
bbox['left'] + textsize_width + 10, bbox['top'] - 3),
fill=box_fill)
draw.text(xy=(bbox['left'], bbox['top'] - 15), text=text, fill=text_fill)
draw.text(
xy=(bbox['left'], bbox['top'] - 15), text=text, fill=text_fill)
image.save(save_im_path)
def postprocess(confidence_out, org_im, org_im_path, detected_faces, output_dir, visualization):
def postprocess(confidence_out, org_im, org_im_path, detected_faces, output_dir,
visualization):
"""
Postprocess output of network. one element at a time.
......
## 命令行预测
# ultra_light_fast_generic_face_detector_1mb_320
```
hub run ultra_light_fast_generic_face_detector_1mb_320 --input_path "/PATH/TO/IMAGE"
```
|模型名称|ultra_light_fast_generic_face_detector_1mb_320|
| :--- | :---: |
|类别|图像 - 人脸检测|
|网络|Ultra-Light-Fast-Generic-Face-Detector-1MB|
|数据集|WIDER FACE数据集|
|是否支持Fine-tuning|否|
|模型大小|2.6MB|
|最新更新日期|2021-02-26|
|数据指标|-|
## API
```python
def face_detection(images=None,
paths=None,
batch_size=1,
use_gpu=False,
visualization=False,
output_dir=None,
confs_threshold=0.5):
```
## 一、模型基本信息
检测输入图片中的所有人脸位置
- ### 应用效果展示
- 样例结果示例:
<p align="center">
<img src="https://user-images.githubusercontent.com/22424850/131604811-bce29c3f-66f7-45cb-a388-d739368bfeb9.jpg" width='50%' hspace='10'/>
<br />
</p>
**参数**
- ### 模型介绍
* images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;
* paths (list\[str\]): 图片的路径;
* batch\_size (int): batch 的大小;
* use\_gpu (bool): 是否使用 GPU;
* visualization (bool): 是否将识别结果保存为图片文件;
* output\_dir (str): 图片的保存路径,当为 None 时,默认设为face\_detector\_320\_predict\_output;
* confs\_threshold (float): 置信度的阈值。
- Ultra-Light-Fast-Generic-Face-Detector-1MB是针对边缘计算设备或低算力设备(如用ARM推理)设计的实时超轻量级通用人脸检测模型,可以在低算力设备中如用ARM进行实时的通用场景的人脸检测推理。该PaddleHub Module的预训练数据集为WIDER FACE数据集,可支持预测,在预测时会将图片输入缩放为320 * 240。
**返回**
* res (list\[dict\]): 识别结果的列表,列表中每一个元素为 dict,关键字有 path, save\_path, data,其中:
* path 字段为原输入图片的路径(仅当使用paths输入时存在);
* save\_path 字段为可视化图片的保存路径(仅当visualization=True时存在);
* data 字段为检测结果,类型为list,list的每一个元素为dict,其中'left', 'right', 'top', 'bottom' 为人脸识别框,'confidence' 为此识别框置信度。
## 二、安装
```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- ### 1、环境依赖
将模型保存到指定路径。
- paddlepaddle >= 1.6.2
**参数**
- paddlehub >= 1.6.0 | [如何安装paddlehub](../../../../docs/docs_ch/get_start/installation.rst)
* dirname: 存在模型的目录名称
* model_filename: 模型文件名称,默认为\_\_model\_\_
* params_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效)
* combined: 是否将参数保存到统一的一个文件中
- ### 2、安装
## 代码示例
- ```shell
$ hub install ultra_light_fast_generic_face_detector_1mb_320
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
```python
import paddlehub as hub
import cv2
## 三、模型API预测
face_detector = hub.Module(name="ultra_light_fast_generic_face_detector_1mb_320")
result = face_detector.face_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = face_detector.face_detection((paths=['/PATH/TO/IMAGE'])
```
- ### 1、命令行预测
## 服务部署
- ```shell
$ hub run ultra_light_fast_generic_face_detector_1mb_320 --input_path "/PATH/TO/IMAGE"
```
- 通过命令行方式实现人脸检测模型的调用,更多请见 [PaddleHub命令行指令](../../../../docs/docs_ch/tutorial/cmd_usage.rst)
PaddleHub Serving可以部署一个在线人脸检测服务。
- ### 2、代码示例
## 第一步:启动PaddleHub Serving
- ```python
import paddlehub as hub
import cv2
运行启动命令:
```shell
$ hub serving start -m ultra_light_fast_generic_face_detector_1mb_320
```
face_detector = hub.Module(name="ultra_light_fast_generic_face_detector_1mb_320")
result = face_detector.face_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = face_detector.face_detection(paths=['/PATH/TO/IMAGE'])
```
这样就完成了一个人脸检测服务化API的部署,默认端口号为8866。
- ### 3、API
**NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- ```python
def face_detection(images=None,
paths=None,
batch\_size=1,
use_gpu=False,
output_dir='face_detector_640_predict_output',
visualization=False,
confs_threshold=0.5)
```
## 第二步:发送预测请求
- 检测输入图片中的所有人脸位置。
配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- **参数**
```python
import requests
import json
import cv2
import base64
import paddlehub as hub
- images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;<br/>
- paths (list\[str\]): 图片的路径;<br/>
- batch\_size (int): batch 的大小;<br/>
- use\_gpu (bool): 是否使用 GPU;<br/>
- output\_dir (str): 图片的保存路径,默认设为 face\_detector\_640\_predict\_output;<br/>
- visualization (bool): 是否将识别结果保存为图片文件;<br/>
- confs\_threshold (float): 置信度的阈值。
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
**NOTE:** paths和images两个参数选择其一进行提供数据
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/ultra_light_fast_generic_face_detector_1mb_320"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
- **返回**
# 打印预测结果
print(r.json()["results"])
```
- res (list\[dict\]): 识别结果的列表,列表中每一个元素为 dict,各字段为:
- path (str): 原输入图片的路径
- data (list): 检测结果,list的每一个元素为 dict,各字段为:
- confidence (float): 识别的置信度
- left (int): 边界框的左上角x坐标
- top (int): 边界框的左上角y坐标
- right (int): 边界框的右下角x坐标
- bottom (int): 边界框的右下角y坐标
- save\_path 字段为可视化图片的保存路径(仅当visualization=True时存在)
### 查看代码
https://github.com/Linzaer/Ultra-Light-Fast-Generic-Face-Detector-1MB
- ```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- 将模型保存到指定路径。
### 贡献者
- **参数**
[Jason](https://github.com/jiangjiajun)[Channingss](https://github.com/Channingss)
- dirname: 存在模型的目录名称; <br/>
- model\_filename: 模型文件名称,默认为\_\_model\_\_; <br/>
- params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效);<br/>
- combined: 是否将参数保存到统一的一个文件中。
### 依赖
paddlepaddle >= 1.6.2
## 四、服务部署
paddlehub >= 1.6.0
- PaddleHub Serving可以部署一个在线人脸检测服务。
- ### 第一步:启动PaddleHub Serving
- 运行启动命令:
- ```shell
$ hub serving start -m ultra_light_fast_generic_face_detector_1mb_320
```
- 这样就完成了一个人脸检测服务化API的部署,默认端口号为8866。
- **NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- ### 第二步:发送预测请求
- 配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- ```python
import requests
import json
import cv2
import base64
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/ultra_light_fast_generic_face_detector_1mb_320"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
# 打印预测结果
print(r.json()["results"])
```
## 五、更新历史
* 1.0.0
初始发布
* 1.1.2
- ```shell
$ hub install ultra_light_fast_generic_face_detector_1mb_320==1.1.2
```
## 命令行预测
# ultra_light_fast_generic_face_detector_1mb_640
```
hub run ultra_light_fast_generic_face_detector_1mb_640 --input_path "/PATH/TO/IMAGE"
```
|模型名称|ultra_light_fast_generic_face_detector_1mb_640|
| :--- | :---: |
|类别|图像 - 人脸检测|
|网络|Ultra-Light-Fast-Generic-Face-Detector-1MB|
|数据集|WIDER FACE数据集|
|是否支持Fine-tuning|否|
|模型大小|2.9MB|
|最新更新日期|2021-02-26|
|数据指标|-|
## API
```python
def face_detection(images=None,
paths=None,
batch_size=1,
use_gpu=False,
visualization=False,
output_dir=None,
confs_threshold=0.5):
```
## 一、模型基本信息
检测输入图片中的所有人脸位置
- ### 应用效果展示
- 样例结果示例:
<p align="center">
<img src="https://user-images.githubusercontent.com/22424850/131604811-bce29c3f-66f7-45cb-a388-d739368bfeb9.jpg" width='50%' hspace='10'/>
<br />
</p>
**参数**
- ### 模型介绍
* images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;
* paths (list\[str\]): 图片的路径;
* batch\_size (int): batch 的大小;
* use\_gpu (bool): 是否使用 GPU;
* visualization (bool): 是否将识别结果保存为图片文件;
* output\_dir (str): 图片的保存路径,当为 None 时,默认设为face\_detector\_640\_predict\_output;
* confs\_threshold (float): 置信度的阈值。
- Ultra-Light-Fast-Generic-Face-Detector-1MB是针对边缘计算设备或低算力设备(如用ARM推理)设计的实时超轻量级通用人脸检测模型,可以在低算力设备中如用ARM进行实时的通用场景的人脸检测推理。该PaddleHub Module的预训练数据集为WIDER FACE数据集,可支持预测,在预测时会将图片输入缩放为640 * 480。
**返回**
* res (list\[dict\]): 识别结果的列表,列表中每一个元素为 dict,关键字有 path, save\_path, data,其中:
* path 字段为原输入图片的路径(仅当使用paths输入时存在);
* save\_path 字段为可视化图片的保存路径(仅当visualization=True时存在);
* data 字段为检测结果,类型为list,list的每一个元素为dict,其中'left', 'right', 'top', 'bottom' 为人脸识别框,'confidence' 为此识别框置信度。
## 二、安装
```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- ### 1、环境依赖
将模型保存到指定路径。
- paddlepaddle >= 1.6.2
**参数**
- paddlehub >= 1.6.0 | [如何安装paddlehub](../../../../docs/docs_ch/get_start/installation.rst)
* dirname: 存在模型的目录名称
* model_filename: 模型文件名称,默认为\_\_model\_\_
* params_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效)
* combined: 是否将参数保存到统一的一个文件中
- ### 2、安装
## 预测代码示例
- ```shell
$ hub install ultra_light_fast_generic_face_detector_1mb_640
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
```python
import paddlehub as hub
import cv2
## 三、模型API预测
face_detector = hub.Module(name="ultra_light_fast_generic_face_detector_1mb_640")
result = face_detector.face_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = face_detector.face_detection((paths=['/PATH/TO/IMAGE'])
```
- ### 1、命令行预测
## 服务部署
- ```shell
$ hub run ultra_light_fast_generic_face_detector_1mb_640 --input_path "/PATH/TO/IMAGE"
```
- 通过命令行方式实现人脸检测模型的调用,更多请见 [PaddleHub命令行指令](../../../../docs/docs_ch/tutorial/cmd_usage.rst)
PaddleHub Serving可以部署一个在线人脸检测服务。
- ### 2、代码示例
## 第一步:启动PaddleHub Serving
- ```python
import paddlehub as hub
import cv2
运行启动命令:
```shell
$ hub serving start -m ultra_light_fast_generic_face_detector_1mb_640
```
face_detector = hub.Module(name="ultra_light_fast_generic_face_detector_1mb_640")
result = face_detector.face_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = face_detector.face_detection(paths=['/PATH/TO/IMAGE'])
```
这样就完成了一个人脸检测服务化API的部署,默认端口号为8866。
- ### 3、API
**NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- ```python
def face_detection(images=None,
paths=None,
batch\_size=1,
use_gpu=False,
output_dir='face_detector_640_predict_output',
visualization=False,
confs_threshold=0.5)
```
## 第二步:发送预测请求
- 检测输入图片中的所有人脸位置。
配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- **参数**
```python
import requests
import json
import cv2
import base64
import paddlehub as hub
- images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;<br/>
- paths (list\[str\]): 图片的路径;<br/>
- batch\_size (int): batch 的大小;<br/>
- use\_gpu (bool): 是否使用 GPU;<br/>
- output\_dir (str): 图片的保存路径,默认设为 face\_detector\_640\_predict\_output;<br/>
- visualization (bool): 是否将识别结果保存为图片文件;<br/>
- confs\_threshold (float): 置信度的阈值。
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
**NOTE:** paths和images两个参数选择其一进行提供数据
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/ultra_light_fast_generic_face_detector_1mb_640"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
- **返回**
# 打印预测结果
print(r.json()["results"])
```
- res (list\[dict\]): 识别结果的列表,列表中每一个元素为 dict,各字段为:
- path (str): 原输入图片的路径
- data (list): 检测结果,list的每一个元素为 dict,各字段为:
- confidence (float): 识别的置信度
- left (int): 边界框的左上角x坐标
- top (int): 边界框的左上角y坐标
- right (int): 边界框的右下角x坐标
- bottom (int): 边界框的右下角y坐标
- save\_path 字段为可视化图片的保存路径(仅当visualization=True时存在)
### 查看代码
https://github.com/Linzaer/Ultra-Light-Fast-Generic-Face-Detector-1MB
- ```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
- 将模型保存到指定路径。
### 贡献者
- **参数**
[Jason](https://github.com/jiangjiajun)[Channingss](https://github.com/Channingss)
- dirname: 存在模型的目录名称; <br/>
- model\_filename: 模型文件名称,默认为\_\_model\_\_; <br/>
- params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效);<br/>
- combined: 是否将参数保存到统一的一个文件中。
### 依赖
paddlepaddle >= 1.6.2
## 四、服务部署
paddlehub >= 1.6.0
- PaddleHub Serving可以部署一个在线人脸检测服务。
- ### 第一步:启动PaddleHub Serving
- 运行启动命令:
- ```shell
$ hub serving start -m ultra_light_fast_generic_face_detector_1mb_640
```
- 这样就完成了一个人脸检测服务化API的部署,默认端口号为8866。
- **NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- ### 第二步:发送预测请求
- 配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- ```python
import requests
import json
import cv2
import base64
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/ultra_light_fast_generic_face_detector_1mb_640"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
# 打印预测结果
print(r.json()["results"])
```
## 五、更新历史
* 1.0.0
初始发布
* 1.1.2
- ```shell
$ hub install ultra_light_fast_generic_face_detector_1mb_640==1.1.2
```
## 模型概述
# solov2
solov2是基于'SOLOv2: Dynamic, Faster and Stronger'实现的快速实例分割的模型。该模型基于SOLOV1, 并且针对mask的检测效果和运行效率进行改进,在实例分割任务中表现优秀。相对语义分割,实例分割需要标注出图上同一物体的不同个体。solov2实例分割效果如下:
| 模型名称 | solov2 |
| :------------------ | :-----------: |
| 类别 | 图像-实例分割 |
| 网络 | - |
| 数据集 | COCO2014 |
| 是否支持Fine-tuning | 否 |
| 模型大小 | 165M |
| 最新更新日期 | 2021-02-26 |
| 数据指标 | - |
<div align="center">
<img src="example.png" width = "642" height = "400" />
</div>
## API
```python
def predict(self,
image: Union[str, np.ndarray],
threshold: float = 0.5,
visualization: bool = False,
save_dir: str = 'solov2_result'):
```
预测API,实例分割。
**参数**
* image (Union\[str, np.ndarray\]): 图片路径或者图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;
* threshold (float): 检测模型输出结果中,预测得分低于该阈值的框将被滤除,默认值为0.5;
* visualization (bool): 是否将可视化图片保存;
* save_dir (str): 保存图片到路径, 默认为"solov2_result"。
**返回**
* res (dict): 识别结果,关键字有 'segm', 'label', 'score'对应的取值为:
* segm (np.ndarray): 实例分割结果,取值为0或1。0表示背景,1为实例;
* label (list): 实例分割结果类别id;
* score (list):实例分割结果类别得分;
## 代码示例
```python
import cv2
import paddlehub as hub
img = cv2.imread('/PATH/TO/IMAGE')
model = hub.Module(name='solov2', use_gpu=False)
output = model.predict(image=img,visualization=False)
```
## 服务部署
PaddleHub Serving可以部署一个实例分割的在线服务。
## 第一步:启动PaddleHub Serving
运行启动命令:
```shell
$ hub serving start -m solov2
```
## 一、模型基本信息
默认端口号为8866。
- ### 应用效果展示
**NOTE:** 如使用GPU预测,则需要在启动服务之前,设置CUDA_VISIBLE_DEVICES环境变量,否则不用设置。
## 第二步:发送预测请求
配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
```python
import requests
import json
import cv2
import base64
import numpy as np
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
def base64_to_cv2(b64str):
data = base64.b64decode(b64str.encode('utf8'))
data = np.fromstring(data, np.uint8)
data = cv2.imdecode(data, cv2.IMREAD_COLOR)
return data
# 发送HTTP请求
org_im = cv2.imread('/PATH/TO/IMAGE')
h, w, c = org_im.shape
data = {'images':[cv2_to_base64(org_im)]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/solov2"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
seg = base64.b64decode(r.json()["results"]['segm'].encode('utf8'))
seg = np.fromstring(seg, dtype=np.int32).reshape((-1, h, w))
label = base64.b64decode(r.json()["results"]['label'].encode('utf8'))
label = np.fromstring(label, dtype=np.int64)
score = base64.b64decode(r.json()["results"]['score'].encode('utf8'))
score = np.fromstring(score, dtype=np.float32)
print('seg', seg)
print('label', label)
print('score', score)
```
### 查看代码
https://github.com/PaddlePaddle/PaddleDetection
### 依赖
paddlepaddle >= 2.0.0
<div align="center">
<img src="https://user-images.githubusercontent.com/76040149/133250741-83040204-acfc-4348-af90-acac74f40cd8.png" height = "300" />
</div>
paddlehub >= 2.0.0
- ### 模型介绍
- solov2是基于"SOLOv2: Dynamic, Faster and Stronger"实现的快速实例分割的模型。该模型基于SOLOV1, 并且针对mask的检测效果和运行效率进行改进,在实例分割任务中表现优秀。相对语义分割,实例分割需要标注出图上同一物体的不同个体。
## 二、安装
- ### 1、环境依赖
- paddlepaddle >= 2.0.0
- paddlehub >= 2.0.0 | [如何安装PaddleHub](../../../../docs/docs_ch/get_start/installation.rst)
- ### 2、安装
- ```shell
$ hub install solov2
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
## 三、模型API预测
- ### 1、命令行预测
- ```shell
$ hub run openpose_hands_estimation --input_path "/PATH/TO/IMAGE"
```
- 通过命令行方式实现hub模型的调用,更多请见 [PaddleHub命令行指令](../../../../docs/docs_ch/tutorial/cmd_usage.rst)
- ### 2、预测代码示例
- ```python
import cv2
import paddlehub as hub
img = cv2.imread('/PATH/TO/IMAGE')
model = hub.Module(name='solov2', use_gpu=False)
output = model.predict(image=img, visualization=False)
```
- ### 3、API
- ```python
def predict(image: Union[str, np.ndarray],
threshold: float = 0.5,
visualization: bool = False,
save_dir: str = 'solov2_result'):
```
- 预测API,实例分割。
- **参数**
- image (Union[str, np.ndarray]): 图片路径或者图片数据,ndarray.shape 为 [H, W, C],BGR格式;
- threshold (float): 检测模型输出结果中,预测得分低于该阈值的框将被滤除,默认值为0.5;
- visualization (bool): 是否将可视化图片保存;
- save_dir (str): 保存图片到路径, 默认为"solov2_result"。
- **返回**
- res (dict): 识别结果,关键字有 'segm', 'label', 'score'对应的取值为:
- segm (np.ndarray): 实例分割结果,取值为0或1。0表示背景,1为实例;
- label (list): 实例分割结果类别id;
- score (list):实例分割结果类别得分;s
## 四、服务部署
- PaddleHub Serving可以部署一个实例分割的在线服务。
- ### 第一步:启动PaddleHub Serving
- 运行启动命令:
- ```shell
$ hub serving start -m solov2 -p 8866
```
- 这样就完成了一个实例分割的在线服务API的部署,默认端口号为8866。
- **NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- ### 第二步:发送预测请求
- 配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- ```python
import requests
import json
import cv2
import base64
import numpy as np
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
def base64_to_cv2(b64str):
data = base64.b64decode(b64str.encode('utf8'))
data = np.fromstring(data, np.uint8)
data = cv2.imdecode(data, cv2.IMREAD_COLOR)
return data
# 发送HTTP请求
org_im = cv2.imread('/PATH/TO/IMAGE')
h, w, c = org_im.shape
data = {'images':[cv2_to_base64(org_im)]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/solov2"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
seg = base64.b64decode(r.json()["results"]['segm'].encode('utf8'))
seg = np.fromstring(seg, dtype=np.int32).reshape((-1, h, w))
label = base64.b64decode(r.json()["results"]['label'].encode('utf8'))
label = np.fromstring(label, dtype=np.int64)
score = base64.b64decode(r.json()["results"]['score'].encode('utf8'))
score = np.fromstring(score, dtype=np.float32)
print('seg', seg)
print('label', label)
print('score', score)
```
## 五、更新历史
* 1.0.0
初始发布
* ```shell
$ hub install hand_pose_localization==1.0.0
```
## 命令行预测
# face_landmark_localization
```
hub run face_landmark_localization --input_path "/PATH/TO/IMAGE"
```
| 模型名称 | face_landmark_localization |
| :------------------ | :------------------------: |
| 类别 | 图像-关键点检测 |
| 网络 | Face_Landmark |
| 数据集 | AFW/AFLW |
| 是否支持Fine-tuning | 否 |
| 模型大小 | 3M |
| 最新更新日期 | 2021-02-26 |
| 数据指标 | - |
## API
## 一、模型基本信息
```python
def __init__(face_detector_module=None)
```
- ### 应用效果展示
- 人脸关键点(左)、模型检测效果(右)
**参数**
<p align="center">
<img src="https://user-images.githubusercontent.com/76040149/133222449-a1c2d444-a839-4c0e-9203-30d67eeb2246.jpeg" hspace="5" width="300"/> <img src="https://user-images.githubusercontent.com/76040149/133229934-e7357767-28e0-4253-bf71-f948de9966f1.jpg" hspace="5" height="300"/>
</p>
* face\_detector\_module (class): 人脸检测模型,默认为 ultra\_light\_fast\_generic\_face\_detector\_1mb\_640.
- ### 模型介绍
- 人脸关键点检测是人脸识别和分析领域中的关键一步,它是诸如自动人脸识别、表情分析、三维人脸重建及三维动画等其它人脸相关问题的前提和突破口。该 PaddleHub Module 的模型转换自 https://github.com/lsy17096535/face-landmark ,支持同一张图中的多个人脸检测。
```python
def keypoint_detection(images=None,
paths=None,
batch_size=1,
use_gpu=False,
output_dir='face_landmark_output',
visualization=False)
```
识别输入图片中的所有人脸关键点,每张人脸检测出68个关键点(人脸轮廓17个点,左右眉毛各5个点,左右眼睛各6个点,鼻子9个点,嘴巴20个点)
## 二、安装
<p align="center">
<img src="https://paddlehub.bj.bcebos.com/resources/face_landmark.jpg" hspace='5' width=500/> <br />
</p>
- ### 1、环境依赖
**参数**
- paddlepaddle >= 1.6.2
* images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\],BGR格式;
* paths (list\[str\]): 图片的路径;
* batch\_size (int): batch 的大小;
* use\_gpu (bool): 是否使用 GPU;
* visualization (bool): 是否将识别结果保存为图片文件;
* output\_dir (str): 图片的保存路径,当为 None 时,默认设为face\_landmark\_output。
- paddlehub >= 1.6.0 | [如何安装PaddleHub](../../../../docs/docs_ch/get_start/installation.rst)
**返回**
- ### 2、安装
* res (list\[dict\]): 识别结果的列表,列表元素为 dict, 有以下两个字段:
* save\_path : 可视化图片的保存路径(仅当visualization=True时存在);
* data: 图片中每张人脸的关键点坐标
- ```shell
$ hub install face_landmark_localization
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
```python
def set_face_detector_module(face_detector_module)
```
## 三、模型API预测
设置为人脸关键点检测模型进行人脸检测的底座模型
- ### 1、命令行预测
**参数**
- ```shell
$ hub run face_landmark_localization --input_path "/PATH/TO/IMAGE"
```
- 通过命令行方式实现hub模型的调用,更多请见 [PaddleHub命令行指令](../../../../docs/docs_ch/tutorial/cmd_usage.rst)
* face\_detector\_module (class): 人脸检测模型
- ### 2、预测代码示例
- ```python
import paddlehub as hub
import cv2
face_landmark = hub.Module(name="face_landmark_localization")
# Replace face detection module to speed up predictions but reduce performance
# face_landmark.set_face_detector_module(hub.Module(name="ultra_light_fast_generic_face_detector_1mb_320"))
result = face_landmark.keypoint_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = face_landmark.keypoint_detection(paths=['/PATH/TO/IMAGE'])
```
- ### 3、API
```python
def get_face_detector_module()
```
- ```python
def __init__(face_detector_module=None):
```
获取为人脸关键点检测模型进行人脸检测的底座模型
- **参数**
- face_detector_module (class): 人脸检测模型,默认为 ultra_light_fast_generic_face_detector_1mb_640.
**返回**
- ```python
def keypoint_detection(images=None,
paths=None,
batch_size=1,
use_gpu=False,
output_dir='face_landmark_output',
visualization=False):
```
* 当前模型使用的人脸检测模型。
- 识别输入图片中的所有人脸关键点,每张人脸检测出68个关键点(人脸轮廓17个点,左右眉毛各5个点,左右眼睛各6个点,鼻子9个点,嘴巴20个点)
```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
将模型保存到指定路径,由于人脸关键点检测模型由人脸检测+关键点检测两个模型组成,因此保存后会存在两个子目录,其中`face_landmark`为人脸关键点模型,`detector`为人脸检测模型。
- **参数**
**参数**
- images (list[numpy.ndarray]): 图片数据,ndarray.shape 为 [H, W, C],BGR格式;
- paths (list[str]): 图片的路径;
- batch_size (int): batch 的大小;
- use_gpu (bool): 是否使用 GPU;
- visualization (bool): 是否将识别结果保存为图片文件;
- output_dir (str): 图片的保存路径,当为 None 时,默认设为face_landmark_output。
* dirname: 存在模型的目录名称
* model_filename: 模型文件名称,默认为\_\_model\_\_
* params_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效)
* combined: 是否将参数保存到统一的一个文件中
- **返回**
- res (list[dict]): 识别结果的列表,列表元素为 dict, 有以下两个字段:
- save_path : 可视化图片的保存路径(仅当visualization=True时存在);
- data: 图片中每张人脸的关键点坐标
## 代码示例
- ```python
def set_face_detector_module(face_detector_module):
```
```python
import paddlehub as hub
import cv2
- 设置为人脸关键点检测模型进行人脸检测的底座模型
- **参数**
- face_detector_module (class): 人脸检测模型
face_landmark = hub.Module(name="face_landmark_localization")
- ```python
def get_face_detector_module():
```
# Replace face detection module to speed up predictions but reduce performance
# face_landmark.set_face_detector_module(hub.Module(name="ultra_light_fast_generic_face_detector_1mb_320"))
- 获取为人脸关键点检测模型进行人脸检测的底座模型
- **返回**
- 当前模型使用的人脸检测模型。
result = face_landmark.keypoint_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = face_landmark.keypoint_detection(paths=['/PATH/TO/IMAGE'])
```
- ```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=False):
```
- 将模型保存到指定路径,由于人脸关键点检测模型由人脸检测+关键点检测两个模型组成,因此保存后会存在两个子目录,其中`face_landmark`为人脸关键点模型,`detector`为人脸检测模型。
- **参数**
- dirname: 存在模型的目录名称
- model_filename: 模型文件名称,默认为\__model__
- params_filename: 参数文件名称,默认为\__params__(仅当combined为True时生效)
- combined: 是否将参数保存到统一的一个文件中
## 四、服务部署
- PaddleHub Serving可以部署一个在线人脸关键点检测服务。
- ### 第一步:启动PaddleHub Serving
- 运行启动命令:
- ```shell
$ hub serving start -m face_landmark_localization -p 8866
```
- 这样就完成了一个人脸关键点服务化API的部署,默认端口号为8866。
- **NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- ### 第二步:发送预测请求
- 配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- ```python
import requests
import json
import cv2
import base64
import paddlehub as hub
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/face_landmark_localization"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
# 打印预测结果
print(r.json()["results"])
```
## 服务部署
## 五、更新历史
* 1.0.0
初始发布
* 1.0.1
PaddleHub Serving可以部署一个在线人脸关键点检测服务。
* 1.0.2
## 第一步:启动PaddleHub Serving
* ```shell
$ hub install face_landmark_localization==1.0.2
```
运行启动命令:
```shell
$ hub serving start -m face_landmark_localization
```
这样就完成了一个人脸关键点服务化API的部署,默认端口号为8866。
**NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA_VISIBLE_DEVICES环境变量,否则不用设置。
## 第二步:发送预测请求
配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
```python
import requests
import json
import cv2
import base64
import paddlehub as hub
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/face_landmark_localization"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
# 打印预测结果
print(r.json()["results"])
```
### 查看代码
https://github.com/lsy17096535/face-landmark
## Module贡献者
[Jason](https://github.com/jiangjiajun)
### 依赖
paddlepaddle >= 1.6.2
paddlehub >= 1.6.0
# hand_pose_localization
| 模型名称 | hand_pose_localization |
| :------------------ | :--------------------: |
| 类别 | 图像-关键点检测 |
| 网络 | |
| 数据集 | MPII, NZSL |
| 是否支持Fine-tuning | 否 |
| 模型大小 | 130M |
| 最新更新日期 | 2021-06-02 |
| 数据指标 | |
## 一、模型基本信息
- ### 应用效果展示
<p align="center">
<img src="https://user-images.githubusercontent.com/76040149/133246893-f47cfdce-b9c1-490b-b1de-f837b61caf18.png" align="center" width="500">
</p>
- ### 模型介绍
- openpose 手部关键点检测模型。更多详情请参考:[openpose开源项目](https://github.com/CMU-Perceptual-Computing-Lab/openpose)
## 二、安装
- ### 1、环境依赖
- paddlepaddle >= 2.0.0
- paddlehub >= 2.0.0 | [如何安装PaddleHub](../../../../docs/docs_ch/get_start/installation.rst)
- ### 2、安装
- ```shell
$ hub install hand_pose_localization
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
## 三、模型API预测
- 本模型不支持命令行预测
- ### 1、预测代码示例
- ```python
import cv2
import paddlehub as hub
# use_gpu:是否使用GPU进行预测
model = hub.Module(name='hand_pose_localization', use_gpu=False)
# 调用关键点检测API
result = model.keypoint_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = model.keypoint_detection(paths=['/PATH/TO/IMAGE'])
# 打印预测结果
print(result)
```
- ### 2、API
- ```python
def keypoint_detection(images=None,
paths=None,
batch_size=1,
output_dir='output',
visualization=False):
```
- 预测API,识别出人体手部关键点。
- **参数**
- images (list[numpy.ndarray]): 图片数据,ndarray.shape 为 [H, W, C], 默认设为 None;
- paths (list[str]): 图片的路径, 默认设为 None;
- batch_size (int): batch 的大小,默认设为 1;
- visualization (bool): 是否将识别结果保存为图片文件,默认设为 False;
- output_dir (str): 图片的保存路径,默认设为 output。
- **返回**
- res (list[list[list[int](https://www.paddlepaddle.org.cn/hubdetail?name=hand_pose_localization&en_category=KeyPointDetection)]]): 每张图片识别到的21个手部关键点组成的列表,每个关键点的格式为[x, y](https://www.paddlepaddle.org.cn/hubdetail?name=hand_pose_localization&en_category=KeyPointDetection),若有关键点未识别到则为None
## 四、服务部署
- PaddleHub Serving可以部署一个在线人体手部关键点检测服务。
- ### 第一步:启动PaddleHub Serving
- 运行启动命令:
- ```shell
$ hub serving start -m hand_pose_localization -p 8866
```
- 这样就完成了一个人体手部关键点检测的在线服务API的部署,默认端口号为8866。
- **NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- ### 第二步:发送预测请求
- 配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- ```python
import requests
import json
import cv2
import base64
# 图片Base64编码函数
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/hand_pose_localization"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
# 打印预测结果
print(r.json()["results"])
```
## 五、更新历史
* 1.0.0
初始发布
* 1.0.1
适配paddlehub 2.0
* ```shell
$ hub install hand_pose_localization==1.0.1
```
## 命令行预测
```
hub run human_pose_estimation_resnet50_mpii --input_path "/PATH/TO/IMAGE"
```
## API 说明
```python
def keypoint_detection(self,
images=None,
paths=None,
batch_size=1,
use_gpu=False,
output_dir='output_pose',
visualization=False)
```
预测API,识别出人体骨骼关键点。
**参数**
* images (list\[numpy.ndarray\]): 图片数据,ndarray.shape 为 \[H, W, C\]
* paths (list\[str\]): 图片的路径;
* batch\_size (int): batch 的大小;
* use\_gpu (bool): 是否使用 GPU;
* visualization (bool): 是否将识别结果保存为图片文件;
* output\_dir (str): 图片的保存路径,默认设为 output\_pose。
**返回**
* res (list[dict]): 识别元素的列表,列表元素为 dict,关键字为 'path', 'data',相应的取值为:
* path (str): 原图的路径;
* data (OrderedDict): 人体骨骼关键点的坐标。
```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True)
```
将模型保存到指定路径。
**参数**
* dirname: 存在模型的目录名称
* model\_filename: 模型文件名称,默认为\_\_model\_\_
* params\_filename: 参数文件名称,默认为\_\_params\_\_(仅当`combined`为True时生效)
* combined: 是否将参数保存到统一的一个文件中
## 预测代码示例
```python
import cv2
import paddlehub as hub
pose_estimation = hub.Module(name="human_pose_estimation_resnet50_mpii")
result = pose_estimation.keypoint_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = pose_estimation.keypoint_detection(paths=['/PATH/TO/IMAGE'])
```
## 服务部署
PaddleHub Serving可以部署一个在线人脸关键点检测服务。
## 第一步:启动PaddleHub Serving
运行启动命令:
```shell
$ hub serving start -m human_pose_estimation_resnet50_mpii
```
这样就完成了一个人体骨骼关键点识别的在线服务API的部署,默认端口号为8866。
**NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
## 第二步:发送预测请求
配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
```python
import requests
import json
import cv2
import base64
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/human_pose_estimation_resnet50_mpii"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
# 打印预测结果
print(r.json()["results"])
```
## 模型相关信息
### 模型代码
https://github.com/PaddlePaddle/models/tree/develop/PaddleCV/human_pose_estimation
### 依赖
paddlepaddle >= 1.6.2
paddlehub >= 1.6.0
# human_pose_estimation_resnet50_mpii
| 模型名称 | human_pose_estimation_resnet50_mpii |
| :------------------ | :---------------------------------: |
| 类别 | 图像-关键点检测 |
| 网络 | Pose_Resnet50 |
| 数据集 | MPII |
| 是否支持Fine-tuning | 否 |
| 模型大小 | 121M |
| 最新更新日期 | 2021-02-26 |
| 数据指标 | |
## 一、模型基本信息
- ### 应用效果展示
<p align="center">
<img src="https://user-images.githubusercontent.com/76040149/133231581-1dffc391-652d-417f-b8ad-a3c22b8092e8.jpg" width="300">
</p>
- ### 模型介绍
- 人体骨骼关键点检测(Pose Estimation) 是计算机视觉的基础算法之一,在很多cv任务中起到了基础性的作用,如行为识别、人物跟踪、步态识别等领域。
## 二、安装
- ### 1、环境依赖
- paddlepaddle >= 1.6.2
- paddlehub >= 1.6.0 | [如何安装PaddleHub](../../../../docs/docs_ch/get_start/installation.rst)
- ### 2、安装
- ```shell
$ hub install human_pose_estimation_resnet50_mpii
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
## 三、模型API预测
- ### 1、命令行预测
- ```shell
$ hub run human_pose_estimation_resnet50_mpii --input_path "/PATH/TO/IMAGE"
```
- 通过命令行方式实现hub模型的调用,更多请见 [PaddleHub命令行指令](../../../../docs/docs_ch/tutorial/cmd_usage.rst)
- ### 2、预测代码示例
- ```python
import cv2
import paddlehub as hub
pose_estimation = hub.Module(name="human_pose_estimation_resnet50_mpii")
result = pose_estimation.keypoint_detection(images=[cv2.imread('/PATH/TO/IMAGE')])
# or
# result = pose_estimation.keypoint_detection(paths=['/PATH/TO/IMAGE'])
# PaddleHub示例图片下载方法:
# wget https://paddlehub.bj.bcebos.com/resources/test_image.jpg
```
- ### 3、API
- ```python
def keypoint_detection(images=None,
paths=None,
batch_size=1,
use_gpu=False,
output_dir='output_pose',
visualization=False):
```
- 预测API,识别出人体骨骼关键点。
- **参数**
- images (list[numpy.ndarray]): 图片数据,ndarray.shape 为 [H, W, C];
- paths (list[str]): 图片的路径;
- batch_size (int): batch 的大小;
- use_gpu (bool): 是否使用 GPU;
- visualization (bool): 是否将识别结果保存为图片文件;
- output_dir (str): 图片的保存路径,默认设为 output_pose。
- **返回**
- res (list): 识别元素的列表,列表元素为 dict,关键字为 'path', 'data',相应的取值为:
- path (str): 原图的路径;
- data (OrderedDict): 人体骨骼关键点的坐标。
- ```python
def save_inference_model(dirname,
model_filename=None,
params_filename=None,
combined=True):
```
- 将模型保存到指定路径。
- **参数**
- dirname: 存在模型的目录名称
- model_filename: 模型文件名称,默认为__model__
- params_filename: 参数文件名称,默认为__params__(仅当combined为True时生效)
- combined: 是否将参数保存到统一的一个文件中
## 四、服务部署
- PaddleHub Serving可以部署一个在线人体骨骼关键点识别服务。
- ### 第一步:启动PaddleHub Serving
- 运行启动命令:
- ```shell
$ hub serving start -m human_pose_estimation_resnet50_mpii -p 8866
```
- 这样就完成了一个人体骨骼关键点识别的在线服务API的部署,默认端口号为8866。
- **NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- ### 第二步:发送预测请求
- 配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- ```python
import requests
import json
import cv2
import base64
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
# 发送HTTP请求
data = {'images':[cv2_to_base64(cv2.imread("/PATH/TO/IMAGE"))]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/human_pose_estimation_resnet50_mpii"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
# 打印预测结果
print(r.json()["results"])
# r.json()['results']即为keypoint_detection函数返回的结果
```
## 五、更新历史
* 1.0.0
* 1.1.0
* 1.1.1
* ```shell
$ hub install human_pose_estimation_resnet50_mpii==1.1.1
```
# openpose_body_estimation
| 模型名称 | openpose_body_estimation |
| :------------------ | :------------------------: |
| 类别 | 图像-关键点检测 |
| 网络 | two-branch multi-stage CNN |
| 数据集 | MPII, COCO 2016 |
| 是否支持Fine-tuning | 否 |
| 模型大小 | 185M |
| 最新更新日期 | 2021-06-28 |
| 数据指标 | - |
## 一、模型基本信息
- ### 应用效果展示
- 人体关键点(左)、模型预测效果(右)
<p align="center">
<img src="https://user-images.githubusercontent.com/76040149/133232647-011528a1-32f3-416f-a618-17ffbeba6bab.png" height = "300" hspace='10'/> <img src="https://user-images.githubusercontent.com/76040149/133232724-30979d86-8688-483e-abc3-a9159695a56c.png" height = "300" hspace='10'/>
</p>
- ### 模型介绍
- openpose_body_estimation是基于'Realtime Multi-Person 2D Pose Estimation using Part Affinity Fields'构建的用于肢体关键点检测的模型,该模型可以与openpose_hands_estimation模型联合使用检测肢体和手部关键点。
## 二、安装
- ### 1、环境依赖
- paddlepaddle >= 2.0.0
- paddlehub >= 2.0.0 | [如何安装PaddleHub](../../../../docs/docs_ch/get_start/installation.rst)
- ### 2、安装
- ```shell
$ hub install openpose_body_estimation
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
## 三、模型API预测
- ### 1、命令行预测
- ```shell
$ hub run openpose_body_estimation --input_path "/PATH/TO/IMAGE"
```
- 通过命令行方式实现hub模型的调用,更多请见 [PaddleHub命令行指令](../../../../docs/docs_ch/tutorial/cmd_usage.rst)
- ### 2、预测代码示例
- ```python
import paddlehub as hub
model = hub.Module(name='openpose_body_estimation')
result = model.predict('/PATH/TO/IMAGE')
model.save_inference_model('/PATH/TO/SAVE/MODEL')
# PaddleHub示例图片下载方法:
# wget https://paddlehub.bj.bcebos.com/resources/test_image.jpg
```
- ### 3、API
- ```python
def __init__(self, load_checkpoint: str = None):
```
- 模型初始化函数
- **参数**
- load_checkpoint(str): 肢体检测模型,用户可以指定自己的模型地址。 默认为None时,会使用PaddleHub提供的默认模型。
- ```python
def predict(self,
img,
save_path='openpose_body',
visualization=True):
```
- 识别输入图片中的所有人肢体关键点。
- **参数**
- img (numpy.ndarray|str): 图片数据,使用图片路径或者输入numpy.ndarray,BGR格式;
- save_path (str): 图片保存路径, 默认为'openpose_body';
- visualization (bool): 是否将识别结果保存为图片文件;
- **返回**
- res (dict): 识别结果的列表,列表元素为 dict, 有以下两个字段:
- data : 可视化图片内容(numpy.ndarray,BGR格式);
- candidate: 图片中所有肢体关键点坐标;
- subset: 不同的人不同关键点对应的关键点坐标的索引。
- ```python
def save_inference_model(save_dir):
```
- 将模型保存到指定路径。
- **参数**
- save_dir(str): 存在模型的目录名称。
## 四、服务部署
- PaddleHub Serving可以部署一个在线肢体关键点检测服务。
- ### 第一步:启动PaddleHub Serving
- 运行启动命令:
- ```shell
$ hub serving start -m openpose_body_estimation -p 8866
```
- 这样就完成了一个肢体关键点服务化API的部署,默认端口号为8866。
- **NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- ### 第二步:发送预测请求
- 配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- ```python
import requests
import json
import cv2
import base64
import numpy as np
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
def base64_to_cv2(b64str):
data = base64.b64decode(b64str.encode('utf8'))
data = np.fromstring(data, np.uint8)
data = cv2.imdecode(data, cv2.IMREAD_COLOR)
return data
# 发送HTTP请求
org_im = cv2.imread('/PATH/TO/IMAGE')
data = {'images':[cv2_to_base64(org_im)]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/openpose_body_estimation"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
canvas = base64_to_cv2(r.json()["results"]['data'])
cv2.imwrite('keypoint_body.png', canvas)
```
## 五、更新历史
* 1.0.0
初始发布
* ```shell
$ hub install openpose_body_estimation==1.0.0
```
# openpose_hands_estimation
| 模型名称 | hand_pose_localization |
| :------------------ | :--------------------: |
| 类别 | 图像-关键点检测 |
| 网络 | - |
| 数据集 | MPII, NZSL |
| 是否支持Fine-tuning | 否 |
| 模型大小 | 130M |
| 最新更新日期 | 2021-06-02 |
| 数据指标 | - |
## 一、模型基本信息
- ### 应用效果展示
- 手部关键点展示(左)、预测效果(右)
<p align="center">
<img src="https://user-images.githubusercontent.com/76040149/133233743-dc6e3aaf-27fd-4f7d-95be-21c9383a2ea1.png" height="300"><img src="https://user-images.githubusercontent.com/76040149/133234189-f7a47940-2be2-445c-8043-b490b5402e15.png" height="300">
</p>
- ### 模型介绍
- penpose_hands_estimation是基于 'Hand Keypoint Detection in Single Images using Multiview Bootstrapping' 构建的用于手部关键点检测的模型。
## 二、安装
- ### 1、环境依赖
- paddlepaddle >= 2.0.0
- paddlehub >= 2.0.0 | [如何安装PaddleHub](../../../../docs/docs_ch/get_start/installation.rst)
- scikit-image
- scipy
- ```shell
$ pip install scikit-image scipy
```
- ### 2、安装
- ```shell
$ hub install openpose_hands_estimation
```
- 如您安装时遇到问题,可参考:[零基础windows安装](../../../../docs/docs_ch/get_start/windows_quickstart.md)
| [零基础Linux安装](../../../../docs/docs_ch/get_start/linux_quickstart.md) | [零基础MacOS安装](../../../../docs/docs_ch/get_start/mac_quickstart.md)
## 三、模型API预测
- ### 1、命令行预测
- ```shell
$ hub run openpose_hands_estimation --input_path "/PATH/TO/IMAGE"
```
- Note:本模型先识别人体关键点以确定2个手的位置,再识别手部关键点;输入图片建议为半身照或全身照,手部没有遮挡;本模型需要用到openpose_body_estimation,若未安装则推理前会自动安装
- 通过命令行方式实现hub模型的调用,更多请见 [PaddleHub命令行指令](../../../../docs/docs_ch/tutorial/cmd_usage.rst)
- ### 2、预测代码示例
- ```python
import paddlehub as hub
model = hub.Module(name='openpose_hands_estimation')
result = model.predict('/PATH/TO/IMAGE')
model.save_inference_model('/PATH/TO/SAVE/MODEL')
```
- ### 3、API
- ```python
def __init__(load_checkpoint: str = None):
```
- **参数**
- load_checkpoint(str): 手部检测模型,用户可以指定自己的模型地址。 默认为None时,会使用PaddleHub提供的默认模型。
- ```python
def predict(img,
save_path='openpose_hand',
scale=[0.5, 1.0, 1.5, 2.0],
visualization=True):
```
- 识别输入图片中的所有人手部关键点。
- **参数**
- img (numpy.ndarray|str): 图片数据,使用图片路径或者输入numpy.ndarray,BGR格式;
- save_path (str): 图片保存路径, 默认为openpose_hand;
- scale (list): 搜索关键点时使用图片的不同尺度;
- visualization (bool): 是否将识别结果保存为图片文件;
- **返回**
- res (dict): 识别结果的列表,列表元素为 dict, 有以下两个字段:
- data : 可视化图片内容(numpy.ndarray,BGR格式);
- all_hand_peaks: 图片中手部关键点坐标
- ```python
def save_inference_model(save_dir):
```
- 将模型保存到指定路径。
- **参数**
- save_dir(str): 存放模型的目录名称
## 四、服务部署
- PaddleHub Serving可以部署一个在线手部关键点检测服务。
- ### 第一步:启动PaddleHub Serving
- 运行启动命令:
- ```shell
$ hub serving start -m openpose_hands_estimation -p 8866
```
- 这样就完成了一个人体手部关键点检测的在线服务API的部署,默认端口号为8866。
- **NOTE:** 如使用GPU预测,则需要在启动服务之前,请设置CUDA\_VISIBLE\_DEVICES环境变量,否则不用设置。
- ### 第二步:发送预测请求
- 配置好服务端,以下数行代码即可实现发送预测请求,获取预测结果
- ```python
import requests
import json
import cv2
import base64
import numpy as np
def cv2_to_base64(image):
data = cv2.imencode('.jpg', image)[1]
return base64.b64encode(data.tostring()).decode('utf8')
def base64_to_cv2(b64str):
data = base64.b64decode(b64str.encode('utf8'))
data = np.fromstring(data, np.uint8)
data = cv2.imdecode(data, cv2.IMREAD_COLOR)
return data
# 发送HTTP请求
org_im = cv2.imread('/PATH/TO/IMAGE')
data = {'images':[cv2_to_base64(org_im)]}
headers = {"Content-type": "application/json"}
url = "http://127.0.0.1:8866/predict/openpose_hands_estimation"
r = requests.post(url=url, headers=headers, data=json.dumps(data))
canvas = base64_to_cv2(r.json()["results"]["data"])
cv2.imwrite('keypoint.png', canvas)
```
## 五、更新历史
* 1.0.0
初始发布
* ```shell
$ hub install hand_pose_localization==1.0.0
```
......@@ -45,11 +45,18 @@ class SmoothL1Loss(object):
def __call__(self, x, y, inside_weight=None, outside_weight=None):
return fluid.layers.smooth_l1(
x, y, inside_weight=inside_weight, outside_weight=outside_weight, sigma=self.sigma)
x,
y,
inside_weight=inside_weight,
outside_weight=outside_weight,
sigma=self.sigma)
class BoxCoder(object):
def __init__(self, prior_box_var=[0.1, 0.1, 0.2, 0.2], code_type='decode_center_size', box_normalized=False,
def __init__(self,
prior_box_var=[0.1, 0.1, 0.2, 0.2],
code_type='decode_center_size',
box_normalized=False,
axis=1):
super(BoxCoder, self).__init__()
self.prior_box_var = prior_box_var
......@@ -78,14 +85,16 @@ class TwoFCHead(object):
act='relu',
name='fc6',
param_attr=ParamAttr(name='fc6_w', initializer=Xavier(fan_out=fan)),
bias_attr=ParamAttr(name='fc6_b', learning_rate=2., regularizer=L2Decay(0.)))
bias_attr=ParamAttr(
name='fc6_b', learning_rate=2., regularizer=L2Decay(0.)))
head_feat = fluid.layers.fc(
input=fc6,
size=self.mlp_dim,
act='relu',
name='fc7',
param_attr=ParamAttr(name='fc7_w', initializer=Xavier()),
bias_attr=ParamAttr(name='fc7_b', learning_rate=2., regularizer=L2Decay(0.)))
bias_attr=ParamAttr(
name='fc7_b', learning_rate=2., regularizer=L2Decay(0.)))
return head_feat
......@@ -103,7 +112,12 @@ class BBoxHead(object):
__inject__ = ['head', 'box_coder', 'nms', 'bbox_loss']
__shared__ = ['num_classes']
def __init__(self, head, box_coder=BoxCoder(), nms=MultiClassNMS(), bbox_loss=SmoothL1Loss(), num_classes=81):
def __init__(self,
head,
box_coder=BoxCoder(),
nms=MultiClassNMS(),
bbox_loss=SmoothL1Loss(),
num_classes=81):
super(BBoxHead, self).__init__()
self.head = head
self.num_classes = num_classes
......@@ -140,24 +154,30 @@ class BBoxHead(object):
head_feat = self.get_head_feat(roi_feat)
# when ResNetC5 output a single feature map
if not isinstance(self.head, TwoFCHead):
head_feat = fluid.layers.pool2d(head_feat, pool_type='avg', global_pooling=True)
head_feat = fluid.layers.pool2d(
head_feat, pool_type='avg', global_pooling=True)
cls_score = fluid.layers.fc(
input=head_feat,
size=self.num_classes,
act=None,
name='cls_score',
param_attr=ParamAttr(name='cls_score_w', initializer=Normal(loc=0.0, scale=0.01)),
bias_attr=ParamAttr(name='cls_score_b', learning_rate=2., regularizer=L2Decay(0.)))
param_attr=ParamAttr(
name='cls_score_w', initializer=Normal(loc=0.0, scale=0.01)),
bias_attr=ParamAttr(
name='cls_score_b', learning_rate=2., regularizer=L2Decay(0.)))
bbox_pred = fluid.layers.fc(
input=head_feat,
size=4 * self.num_classes,
act=None,
name='bbox_pred',
param_attr=ParamAttr(name='bbox_pred_w', initializer=Normal(loc=0.0, scale=0.001)),
bias_attr=ParamAttr(name='bbox_pred_b', learning_rate=2., regularizer=L2Decay(0.)))
param_attr=ParamAttr(
name='bbox_pred_w', initializer=Normal(loc=0.0, scale=0.001)),
bias_attr=ParamAttr(
name='bbox_pred_b', learning_rate=2., regularizer=L2Decay(0.)))
return cls_score, bbox_pred
def get_loss(self, roi_feat, labels_int32, bbox_targets, bbox_inside_weights, bbox_outside_weights):
def get_loss(self, roi_feat, labels_int32, bbox_targets,
bbox_inside_weights, bbox_outside_weights):
"""
Get bbox_head loss.
......@@ -186,11 +206,19 @@ class BBoxHead(object):
logits=cls_score, label=labels_int64, numeric_stable_mode=True)
loss_cls = fluid.layers.reduce_mean(loss_cls)
loss_bbox = self.bbox_loss(
x=bbox_pred, y=bbox_targets, inside_weight=bbox_inside_weights, outside_weight=bbox_outside_weights)
x=bbox_pred,
y=bbox_targets,
inside_weight=bbox_inside_weights,
outside_weight=bbox_outside_weights)
loss_bbox = fluid.layers.reduce_mean(loss_bbox)
return {'loss_cls': loss_cls, 'loss_bbox': loss_bbox}
def get_prediction(self, roi_feat, rois, im_info, im_shape, return_box_score=False):
def get_prediction(self,
roi_feat,
rois,
im_info,
im_shape,
return_box_score=False):
"""
Get prediction bounding box in test stage.
......
......@@ -30,7 +30,8 @@ def test_reader(paths=None, images=None):
img_list = list()
if paths:
for img_path in paths:
assert os.path.isfile(img_path), "The {} isn't a valid file path.".format(img_path)
assert os.path.isfile(
img_path), "The {} isn't a valid file path.".format(img_path)
img = cv2.imread(img_path).astype('float32')
img_list.append(img)
if images is not None:
......@@ -65,7 +66,13 @@ def test_reader(paths=None, images=None):
# im_info holds the resize info of image.
im_info = np.array([resize_h, resize_w, im_scale]).astype('float32')
im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR)
im = cv2.resize(
im,
None,
None,
fx=im_scale,
fy=im_scale,
interpolation=cv2.INTER_LINEAR)
# HWC --> CHW
im = np.swapaxes(im, 1, 2)
......@@ -74,11 +81,14 @@ def test_reader(paths=None, images=None):
def padding_minibatch(batch_data, coarsest_stride=0, use_padded_im_info=True):
max_shape_org = np.array([data['image'].shape for data in batch_data]).max(axis=0)
max_shape_org = np.array(
[data['image'].shape for data in batch_data]).max(axis=0)
if coarsest_stride > 0:
max_shape = np.zeros((3)).astype('int32')
max_shape[1] = int(np.ceil(max_shape_org[1] / coarsest_stride) * coarsest_stride)
max_shape[2] = int(np.ceil(max_shape_org[2] / coarsest_stride) * coarsest_stride)
max_shape[1] = int(
np.ceil(max_shape_org[1] / coarsest_stride) * coarsest_stride)
max_shape[2] = int(
np.ceil(max_shape_org[2] / coarsest_stride) * coarsest_stride)
else:
max_shape = max_shape_org.astype('int32')
......@@ -89,12 +99,15 @@ def padding_minibatch(batch_data, coarsest_stride=0, use_padded_im_info=True):
for data in batch_data:
im_c, im_h, im_w = data['image'].shape
# image
padding_im = np.zeros((im_c, max_shape[1], max_shape[2]), dtype=np.float32)
padding_im = np.zeros((im_c, max_shape[1], max_shape[2]),
dtype=np.float32)
padding_im[:, 0:im_h, 0:im_w] = data['image']
padding_image.append(padding_im)
# im_info
data['im_info'][0] = max_shape[1] if use_padded_im_info else max_shape_org[1]
data['im_info'][1] = max_shape[2] if use_padded_im_info else max_shape_org[2]
data['im_info'][
0] = max_shape[1] if use_padded_im_info else max_shape_org[1]
data['im_info'][
1] = max_shape[2] if use_padded_im_info else max_shape_org[2]
padding_info.append(data['im_info'])
padding_shape.append(data['im_shape'])
......
......@@ -22,7 +22,8 @@ nonlocal_params = {
}
def space_nonlocal(input, dim_in, dim_out, prefix, dim_inner, max_pool_stride=2):
def space_nonlocal(input, dim_in, dim_out, prefix, dim_inner,
max_pool_stride=2):
cur = input
theta = fluid.layers.conv2d(input = cur, num_filters = dim_inner, \
filter_size = [1, 1], stride = [1, 1], \
......@@ -82,7 +83,8 @@ def space_nonlocal(input, dim_in, dim_out, prefix, dim_inner, max_pool_stride=2)
theta_phi_sc = fluid.layers.scale(theta_phi, scale=dim_inner**-.5)
else:
theta_phi_sc = theta_phi
p = fluid.layers.softmax(theta_phi_sc, name=prefix + '_affinity' + '_prob')
p = fluid.layers.softmax(
theta_phi_sc, name=prefix + '_affinity' + '_prob')
else:
# not clear about what is doing in xlw's code
p = None # not implemented
......@@ -96,7 +98,8 @@ def space_nonlocal(input, dim_in, dim_out, prefix, dim_inner, max_pool_stride=2)
# reshape back
# e.g. (8, 1024, 784) => (8, 1024, 4, 14, 14)
t_shape = t.shape
t_re = fluid.layers.reshape(t, shape=list(theta_shape), actual_shape=theta_shape_op)
t_re = fluid.layers.reshape(
t, shape=list(theta_shape), actual_shape=theta_shape_op)
blob_out = t_re
blob_out = fluid.layers.conv2d(input = blob_out, num_filters = dim_out, \
filter_size = [1, 1], stride = [1, 1], padding = [0, 0], \
......
......@@ -31,7 +31,8 @@ def test_reader(paths=None, images=None):
img_list = list()
if paths:
for img_path in paths:
assert os.path.isfile(img_path), "The {} isn't a valid file path.".format(img_path)
assert os.path.isfile(
img_path), "The {} isn't a valid file path.".format(img_path)
img = cv2.imread(img_path).astype('float32')
img_list.append(img)
if images is not None:
......@@ -66,7 +67,13 @@ def test_reader(paths=None, images=None):
# im_info holds the resize info of image.
im_info = np.array([resize_h, resize_w, im_scale]).astype('float32')
im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR)
im = cv2.resize(
im,
None,
None,
fx=im_scale,
fy=im_scale,
interpolation=cv2.INTER_LINEAR)
# HWC --> CHW
im = np.swapaxes(im, 1, 2)
......@@ -75,11 +82,14 @@ def test_reader(paths=None, images=None):
def padding_minibatch(batch_data, coarsest_stride=0, use_padded_im_info=True):
max_shape_org = np.array([data['image'].shape for data in batch_data]).max(axis=0)
max_shape_org = np.array(
[data['image'].shape for data in batch_data]).max(axis=0)
if coarsest_stride > 0:
max_shape = np.zeros((3)).astype('int32')
max_shape[1] = int(np.ceil(max_shape_org[1] / coarsest_stride) * coarsest_stride)
max_shape[2] = int(np.ceil(max_shape_org[2] / coarsest_stride) * coarsest_stride)
max_shape[1] = int(
np.ceil(max_shape_org[1] / coarsest_stride) * coarsest_stride)
max_shape[2] = int(
np.ceil(max_shape_org[2] / coarsest_stride) * coarsest_stride)
else:
max_shape = max_shape_org.astype('int32')
......@@ -90,12 +100,15 @@ def padding_minibatch(batch_data, coarsest_stride=0, use_padded_im_info=True):
for data in batch_data:
im_c, im_h, im_w = data['image'].shape
# image
padding_im = np.zeros((im_c, max_shape[1], max_shape[2]), dtype=np.float32)
padding_im = np.zeros((im_c, max_shape[1], max_shape[2]),
dtype=np.float32)
padding_im[:, 0:im_h, 0:im_w] = data['image']
padding_image.append(padding_im)
# im_info
data['im_info'][0] = max_shape[1] if use_padded_im_info else max_shape_org[1]
data['im_info'][1] = max_shape[2] if use_padded_im_info else max_shape_org[2]
data['im_info'][
0] = max_shape[1] if use_padded_im_info else max_shape_org[1]
data['im_info'][
1] = max_shape[2] if use_padded_im_info else max_shape_org[2]
padding_info.append(data['im_info'])
padding_shape.append(data['im_shape'])
......
......@@ -51,8 +51,8 @@ class FPNRoIAlign(object):
name_list = list(head_inputs.keys())
input_name_list = name_list[-num_roi_lvls:]
spatial_scale = spatial_scale[-num_roi_lvls:]
rois_dist, restore_index = fluid.layers.distribute_fpn_proposals(rois, k_min, k_max, self.canconical_level,
self.canonical_size)
rois_dist, restore_index = fluid.layers.distribute_fpn_proposals(
rois, k_min, k_max, self.canconical_level, self.canonical_size)
# rois_dist is in ascend order
roi_out_list = []
resolution = is_mask and self.mask_resolution or self.box_resolution
......
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册