基于ModelArts实现人脸自动匹配口红色号的gif动图
【摘要】 基于ModelArts实现人脸自动匹配口红色号的gif动图注意:本案例必须使用GPU运行,请查看《ModelArts JupyterLab 硬件规格使用指南》了解切换硬件规格的方法《ModelArts JupyterLab 硬件规格使用指南》https://developer.huaweicloud.cn/develop/aigallery/article/detail?id=638c55...
基于ModelArts实现人脸自动匹配口红色号的gif动图
注意:本案例必须使用GPU运行,请查看《ModelArts JupyterLab 硬件规格使用指南》了解切换硬件规格的方法
《ModelArts JupyterLab 硬件规格使用指南》
开发案例介绍文档
1.下载代码和模型文件
import os
import moxing as mox
if not os.path.exists('lipstick_lab'):
mox.file.copy_parallel('obs://liufan-lab/lipstick', './lipstick_lab')
cd lipstick_lab
2.安装所需模块
!pip install --upgrade pip
!pip install ipywidgets
!pip install opencv-python==3.4.0.12
!pip install dlib==19.23.0
!pip install matplotlib==3.2.1
3.加载相关模块及模型
import cv2
import numpy as np
import time
import dlib
from PIL import Image
from ipywidgets import widgets
from ipywidgets import interact
from IPython.display import HTML, display
import matplotlib.pyplot as plt
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
def createBox(img,points,scale=5,masked=False,cropped = True):
if masked:
mask = np.zeros_like(img)
mask = cv2.fillPoly(mask, [points], (255, 255, 255))
img = cv2.bitwise_and(img, mask)
# cv2.imshow('Mask', img)
if cropped:
bbox = cv2.boundingRect(points)
x, y, w, h = bbox
imgCrop = img[y:y+h, x:x+w]
imgCrop = cv2.resize(imgCrop, (0, 0), None, scale, scale)
return imgCrop
else:
return mask
加载图片生成嘴唇的检测区域
4.加载图片生成嘴唇的检测区域 上传需要嘴唇上色的照片到lipstick_lab文件夹下并修改下面TODO代码填入照片文件名
img = cv2.imread('example2.png') # TODO 读入图片并进行人脸关键点检测
img = cv2.resize(img, (0, 0), None, 0.5, 0.5)
imgOriginal = img.copy()
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = detector(imgGray)
for face in faces:
x1, y1 = face.left(), face.top()
x2, y2 = face.right(), face.bottom()
# imgOriginal = cv2.rectangle(img, (x1,y1), (x2,y2), (0, 255, 0), 2 )
landmarks = predictor(imgGray, face)
myPoints =[]
for n in range(68):
x = landmarks.part(n).x
y = landmarks.part(n).y
myPoints.append([x, y])
# cv2.circle(imgOriginal, (x, y), 5, (50, 50, 255), cv2.FILLED)
# cv2.putText(imgOriginal, str(n), (x, y-10), cv2.FONT_HERSHEY_COMPLEX_SMALL,0.9, (0, 0, 255), 1)
myPoints = np.array(myPoints)
# imgLeftEye = createBox(img, myPoints[36:42], 8)
# cv2.imshow('LeftEye', imgLeftEye)
# 2 嘴唇区域mask提取
imgLips = createBox(img, myPoints[48:61], 8, masked=True, cropped=False)
imgColorLips = np.zeros_like(imgLips)
5.调节RGB来生成图片
运行程序前需创建Snowflakes文件夹
!注意创建的Snowflakes文件夹必须和所运行代码的ipynb在同一个目录下
class Battery():
def __init__(self,r,g,b,typeface,number):
self.r = r
self.g = g
self.b = b
self.typeface = typeface
self.number = number
def lucky(self):
imgColorLips = np.zeros_like(imgLips)
img_show_imgOriginal = cv2.resize(imgOriginal, None, fx=1, fy=1) # 缩放为原图的0.3倍,方便展示
img_original = Image.fromarray(img_show_imgOriginal[:, :, [2, 1, 0]])
#display(img_original)
imgColorLips[:] = self.b, self.g, self.r
imgColorLips = cv2.bitwise_and(imgLips, imgColorLips)
imgColorLips = cv2.GaussianBlur(imgColorLips, (7, 7), 10)
#color_image
imgColorLips = cv2.addWeighted(imgOriginal, 1, imgColorLips, 0.4, 0) # 调整口红的权重占比
img_show_imgColorLips = cv2.resize(imgColorLips, None, fx=1, fy=1) # 缩放为原图的0.3倍,方便展示
img_colorlips = Image.fromarray(img_show_imgColorLips[:, :, [2, 1, 0]])
plt.figure(figsize=(7,7))
plt.imshow(img_colorlips)
plt.rcParams['font.sans-serif']=['SimHei'] #中文字体识别
plt.rcParams['axes.unicode_minus']=False
plt.xlabel(self.typeface)
plt.savefig('Snowflakes/'+str(self.number)+'.png')
plt.show()
colour = {'枫叶砖红色':[178,48,41],'正红色':[194,3,13],'牛血红':[106,5,0],'番茄橘':[160,33,18],'小羊皮暖柿红':[239,93,71],
'正橘色':[191,27,28],'珊瑚粉':[242,122,122],'玫红色':[208,10,57],'梅子色':[106,18,45],'覆盆子色':[132,40,82],'肉桂色':[229,140,122],
'网红奶茶色':[255,190,181],'豆沙色':[183,128,115]} #口红的颜色
number = 0
for i in colour:
r = colour[i][0]
g = colour[i][1]
b = colour[i][2]
typeface = i
number+=1
good = Battery(r,g,b,typeface,number) #实例化模块
good.lucky()
生成Git动图
import imageio
import os
def generate_gif(image_paths, gif_path, duration=0.35): #duration=0.35为git动图的转换时间
frames = []
for image_path in image_paths:
frames.append(imageio.imread(image_path))
imageio.mimsave(gif_path, frames, 'GIF', duration=duration)
def main():
image_folder = "Snowflakes"
gif_path = "Snowflakes.gif"
image_paths = []
files = os.listdir(image_folder) #打开文件夹
for file in files: #循环文件内容
image_path = os.path.join(image_folder, file)
image_paths.append(image_path)
duration = 2
generate_gif(image_paths, gif_path, duration)
if __name__ == "__main__":
main()
git动图
产生的git动图会在创建的Snowflakes文件夹里
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)