Skip to content

图像生成

模型基本信息

本模型封装自小视科技 photo2cartoon 项目的 paddlepaddle 版本

参考:https://github.com/PaddlePaddle/PaddleHub/blob/release/v2.2/modules/image/Image_gan/style_transfer/Photo2Cartoon

示例

图片来源 (https://www.pexels.com)

人脸

人脸

现在就来试试吧

先决条件

1、环境依赖

请访问 依赖项

2、mobilenet_v2_animals 依赖

  • paddlepaddle >= 2.0.0

  • paddlehub >= 2.0.0

3、下载模型

hub install Photo2Cartoon

服务模型

安装 Pinferencia

首先,让我们安装 Pinferencia

pip install "pinferencia[streamlit]"

创建 app.py

让我们将我们的预测函数保存到一个文件 app.py 中并添加一些行来注册它。

app.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import base64
from io import BytesIO

import paddlehub as hub
from PIL import Image

from pinferencia import Server, task
from pinferencia.tools import base64_str_to_cv2

image_generation = hub.Module(name="Photo2Cartoon")


def predict(base64_img_str: str) -> str:
    result = image_generation.Cartoon_GEN(
        images=[base64_str_to_cv2(base64_img_str)], visualization=True, output_dir="./"
    )
    pil_img = Image.fromarray(result[0])
    buff = BytesIO()
    pil_img.save(buff, format="JPEG")
    return base64.b64encode(buff.getvalue()).decode("utf-8")


service = Server()
service.register(
    model_name="image_generation",
    model=predict,
    metadata={"task": task.IMAGE_TO_IMAGE},
)

运行服务,等待它加载模型并启动服务器:

$ uvicorn app:service --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [xxxxx] using statreload
INFO:     Started server process [xxxxx]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
$ pinfer app:service --reload

Pinferencia: Frontend component streamlit is starting...
Pinferencia: Backend component uvicorn is starting...

测试服务

打开http://127.0.0.1:8501,模板 Url Image To Image 会自动选中。

png

请求

curl --location --request POST \
    'http://127.0.0.1:8000/v1/models/image_generation/predict' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "data": "base64 image string"
    }'

响应

{
    "model_name": "image_generation",
    "model_version": "default",
    "data": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0a..."
}

创建test.py

test.py
1
2
3
4
5
6
7
8
9
import requests


response = requests.post(
    url="http://localhost:8000/v1/models/image_generation/predict",
    headers = {"Content-type": "application/json"},
    json={"data": "base64 image string"}
)
print(response.json())
运行脚本并检查结果。

$ python test.py
{
    "model_name": "image_generation",
    "model_version": "default",
    "data": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0a..."
}

更酷的是,访问 http://127.0.0.1:8000,您将拥有一个完整的 API 文档。

您甚至也可以在那里发送预测请求!