|
|
import cv2
|
|
|
import numpy as np
|
|
|
from django.http import JsonResponse
|
|
|
import base64
|
|
|
import tensorflow
|
|
|
from django.views.decorators.http import require_POST
|
|
|
|
|
|
def base64tocv(imagecode):
|
|
|
strList = str(imagecode).split(',')
|
|
|
b64_img = ''
|
|
|
for i in strList[1:]:
|
|
|
b64_img += i
|
|
|
imgString = base64.b64decode(b64_img)
|
|
|
nparr = np.fromstring(imgString, np.uint8)
|
|
|
image = cv2.imdecode(nparr, cv2.COLOR_RGB2BGR)
|
|
|
# image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
|
|
|
return image
|
|
|
|
|
|
#ndarray 转 base64
|
|
|
def getbase64byndarray(pic_img):
|
|
|
retval, buffer = cv2.imencode('.jpg', pic_img)
|
|
|
pic_str = base64.b64encode(buffer)
|
|
|
return pic_str.decode()
|
|
|
|
|
|
|
|
|
@require_POST
|
|
|
def style_transfer(request):
|
|
|
'''
|
|
|
pathIn: 原始图片的路径
|
|
|
pathOut: 风格化图片的保存路径
|
|
|
model: 预训练模型的路径
|
|
|
width: 设置风格化图片的宽度,默认为None, 即原始图片尺寸
|
|
|
jpg_quality: 0-100,设置输出图片的质量,默认80,越大图片质量越好
|
|
|
'''
|
|
|
|
|
|
## 读入原始图片,调整图片至所需尺寸,然后获取图片的宽度和高度
|
|
|
image = request.POST.get('files')
|
|
|
img = base64tocv(image)
|
|
|
(h, w) = img.shape[:2]
|
|
|
|
|
|
## 从本地加载预训练模型
|
|
|
net = get_model_from_style(request.POST.get('style'))
|
|
|
|
|
|
## 将图片构建成一个blob:设置图片尺寸,将各通道像素值减去平均值(比如ImageNet所有训练样本各通道统计平均值)
|
|
|
## 然后执行一次前馈网络计算,并输出计算所需的时间
|
|
|
blob = cv2.dnn.blobFromImage(img, 1.0, (w, h), (103.939, 116.779, 123.680), swapRB=False, crop=False)
|
|
|
net.setInput(blob)
|
|
|
output = net.forward()
|
|
|
|
|
|
## reshape输出结果, 将减去的平均值加回来,并交换各颜色通道
|
|
|
output = output.reshape((3, output.shape[2], output.shape[3]))
|
|
|
output[0] += 103.939
|
|
|
output[1] += 116.779
|
|
|
output[2] += 123.680
|
|
|
output = output.transpose(1, 2, 0)
|
|
|
output=getbase64byndarray(output)
|
|
|
|
|
|
return JsonResponse(data={"image": output, "height": h, "width": w},
|
|
|
json_dumps_params={'ensure_ascii': False})
|
|
|
|
|
|
# model_base_dir = "/root/imageProcess/styleTransfer/models/"
|
|
|
model_base_dir = "F:\imageprocess\imageProcess\styleTransfer\models\\"
|
|
|
d_model_map = {
|
|
|
0: "candy",
|
|
|
1: "udnie",
|
|
|
2: "la_muse",
|
|
|
3: "the_scream",
|
|
|
4: "mosaic",
|
|
|
5: "feathers",
|
|
|
6: "starry_night"
|
|
|
}
|
|
|
|
|
|
def get_model_from_style(style):
|
|
|
"""
|
|
|
加载指定风格的模型
|
|
|
:param style: 模型编码
|
|
|
:return: model
|
|
|
"""
|
|
|
style=int(style)
|
|
|
model_name = d_model_map[style]
|
|
|
model_path = model_base_dir + model_name + ".t7"
|
|
|
model = cv2.dnn.readNetFromTorch(model_path)
|
|
|
return model
|
|
|
|