openfaas 尝试整合flask记录(二)

原创
05/07 13:43
阅读数 177

需要写一些整合tensorflow,opencv之类的demo给新人参考。所以又对flask的模板写了几个变体 。因为要安装tensorflow,所以使用conda做镜像。

代码备份:https://gitee.com/awol2010ex/openfaas-flask-conda-template

主要修改了Dockerfile部分

FROM openfaas/of-watchdog:0.5.3 as watchdog
FROM continuumio/miniconda3:4.8.2
WORKDIR /home/app
RUN apt-get install ca-certificates \
    && addgroup --system app && adduser  --system app && adduser app app \
    && mkdir -p /home/app \
    && chown app /home/app
#复制handler目录,来自用户写handler文件
COPY function ./function
#安装用户需要的依赖,来handler目录的requirements.txt

RUN conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
RUN conda install --yes -c https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ --file ./function/conda_requirements.txt
RUN pip install flask -i http://pypi.douban.com/simple --trusted-host=pypi.douban.com

RUN pip install -r ./function/pip_requirements.txt -i http://pypi.douban.com/simple --trusted-host=pypi.douban.com


#复制fwatchdog程序过来
COPY --from=watchdog /fwatchdog .
#主要python文件和gunicorn配置文件
COPY main.py .
COPY __init__.py .

#fwatchdog运行权限
RUN chmod +x fwatchdog
#使用app用户
RUN chown -R app /home/app

#使用app用户
USER app
RUN export FLASK_APP=main.py

#使用gunicorn运行
ENV fprocess="python main.py"
ENV cgi_headers="true"
#http协议
ENV mode="http"
#反向代理flask服务的5000端口
ENV upstream_url="http://127.0.0.1:5000"


EXPOSE 8080

HEALTHCHECK --interval=3s CMD [ -e /tmp/.lock ] || exit 1

CMD ["./fwatchdog"]

写了一个染发的例子(这里我无耻地抄袭了别人的代码和训练好的模型)

pip依赖

pip_requirements.txt(function部分的导入依赖)

tensorflow==1.15.0
opencv-python==4.2.0.32
keras>=2.2.4
numpy>=1.14.6

handler函数部分 (简单地抄袭别人的代码写了个例子)

from flask import Blueprint,Flask, request,make_response,send_from_directory
import os
import cv2
import keras
import numpy as np

app = Flask(__name__)
UPLOAD_FOLDER = '/home/app'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER  # 上传文件夹


handler_blueprint = Blueprint(
	'handler',
  	__name__,
  	url_prefix='/hair'
)




def predict(model, im):
    h, w, _ = im.shape
    inputs = cv2.resize(im, (480, 480))
    inputs = inputs.astype('float32')
    inputs.shape = (1,) + inputs.shape
    inputs = inputs / 255
    mask = model.predict(inputs)
    # ret, mask = cv2.threshold(mask, 10, 255, cv2.THRESH_BINARY_INV)
    mask.shape = mask.shape[1:]
    mask = cv2.resize(mask, (w, h))
    mask.shape = h, w, 1
    return mask


def change_v(v, mask, target):
    # 染发
    epsilon = 1e-7
    x = v / 255                             # 数学化
    target = target / 255
    target = -np.log(epsilon + 1 - target)
    x_mean = np.sum(-np.log(epsilon + 1 - x)  * mask) / np.sum(mask)
    alpha = target / x_mean
    x = 1 - (1 - x) ** alpha
    v[:] = x * 255                          # 二进制化


def recolor(im, mask, color=(0x40, 0x16, 0x66)):
    # 工程化
    color = np.array(color, dtype='uint8', ndmin=3)
    im_hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
    color_hsv = cv2.cvtColor(color, cv2.COLOR_BGR2HSV)
    # 染发
    im_hsv[..., 0] = color_hsv[..., 0]      # 修改颜色
    change_v(im_hsv[..., 2:], mask, color_hsv[..., 2:])
    im_hsv[..., 1] = color_hsv[..., 1]      # 修改饱和度
    x = cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR)
    im = im * (1 - mask) + x * mask
    return im


@handler_blueprint.route("/",methods = ['POST'])
def hair():
    if request.method == 'POST':
        f = request.files['file']
        #保存文件
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], 'src.jpg'))
        ifn = os.path.join(app.config['UPLOAD_FOLDER'], 'src.jpg')
        src = cv2.imread(ifn)
        model = keras.models.load_model('/home/app/function/weights.005.h5')
        mask = predict(model, src)
        keras.backend.clear_session()  # 清除session(否则keras报错)
        color =[169, 169, 169]#银色
        res = recolor(src, mask, color)
        ofn = os.path.join(app.config['UPLOAD_FOLDER'], 'res.jpg')
        cv2.imwrite(ofn, res)
        return send_from_directory(app.config['UPLOAD_FOLDER'],"res.jpg",as_attachment=True)

配置文件 hair-demo.yml

 

version: 1.0
provider:
  name: openfaas
  gateway: http://127.0.0.1:31112
functions:
  hair-demo:
    lang: openfaas-flask-conda-template
    handler: ./hair-demo
    image: registry.cn-hangzhou.aliyuncs.com/policloud/hair-demo:latest

安装函数(经过漫长的build)

faas up -f hair-demo.yml

测试阶段,上传一个人像图片

使用postman测试函数

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部