2021年3月1日更新2:
1.調整人臉區域為橢圓,比圓形更貼合臉型,占用的面積變小,
2.修復了出現人臉出現黑邊的問題,
如果人臉區域不合適,可調整ratio引數,
2021年3月1日更新:
1.調整人臉區域為圓形,更貼合臉型,占用的面積變小,
2.增加ratio引數,可以調整人臉區域的面積,默認為1.0,代表圓形區域的半徑為臉部的高度,
PaddleGAN套件gitee地址:
https://gitee.com/txyugood/PaddleGAN.git
公眾號:人工智能研習社,歡迎大家關注,
抖音上的螞蟻呀嘿火遍全網,很多小伙伴都不知道如何制作,本文拋棄繁瑣的操作,利用PaddleHub與PaddleGAN框架一鍵生成多人版的”螞蟻呀嘿“視頻,
首先我們需要安裝PaddleHub,利用其中的face detection功能來定位照片中人臉,
先放一張效果圖:

安裝方法如下:
pip install paddlehub==1.6.0
安裝之后paddlehub之后,還需要安裝一下人臉檢測的模型,命令如下:
hub install ultra_light_fast_generic_face_detector_1mb_640
生成”螞蟻呀嘿“視頻需要用到PaddleGAN套件中的動作遷移功能,所以下一步需要安裝PaddleGAN套件,因為我修改了PaddleGAN套件部分代碼,所以這個代碼已經保存在AIStudio環境中,直接安裝就可以了,
AI Stuidio地址:(強烈推薦,fork后可一鍵運行,無需搭建環境)
https://aistudio.baidu.com/aistudio/projectdetail/1285661
也可以從以下地址下載:
https://gitee.com/txyugood/PaddleGAN.git
使用以下命令安裝PaddleGAN,
cd PaddleGAN/
pip install -v -e .
安裝PaddleGAN依賴的PaddlePaddle框架,
python -m pip install https://paddle-wheel.bj.bcebos.com/2.0.0-rc0-gpu-cuda10.1-cudnn7-mkl_gcc8.2%2Fpaddlepaddle_gpu-2.0.0rc0.post101-cp37-cp37m-linux_x86_64.whl
此處借用了GT大佬
https://aistudio.baidu.com/aistudio/projectdetail/1584416
專案中的驅動視頻,
/home/aistudio/1.jpeg是測驗的照片,可以使用右側的上傳功能上傳自己的照片,然后替換–source_image 后面的路徑后,運行腳本即可,
最終/home/aistudio/output/mayiyahei.mp4就是最終生成的"螞蟻呀嘿"視頻,
可以通過ratio引數調整用于動作遷移的人臉的圖片尺寸,1.0代表半徑等于人臉高度的圓形區域,
運行腳本生成視頻:
cd /home/aistudio/PaddleGAN/applications/
python -u tools/first-order-mayi.py \
--driving_video /home/aistudio/MaYiYaHei.mp4 \
--source_image /home/aistudio/1.jpeg \
--relative --adapt_scale \
--output /home/aistudio/output \
--ratio 1.0
PaddleGAN/application/tools/first-order-mayi.py檔案,是生成”螞蟻呀嘿“視頻的主程式,
下面簡單解讀一下代碼:
import argparse
import os
import paddle
from ppgan.apps.first_order_predictor import FirstOrderPredictor
from skimage import img_as_ubyte
import paddlehub as hub
import math
import cv2
import imageio
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument("--config", default=None, help="path to config")
parser.add_argument("--weight_path",
default=None,
help="path to checkpoint to restore")
parser.add_argument("--source_image", type=str, help="path to source image")
parser.add_argument("--driving_video", type=str, help="path to driving video")
parser.add_argument("--output", default='output', help="path to output")
parser.add_argument("--relative",
dest="relative",
action="store_true",
help="use relative or absolute keypoint coordinates")
parser.add_argument(
"--adapt_scale",
dest="adapt_scale",
action="store_true",
help="adapt movement scale based on convex hull of keypoints")
parser.add_argument(
"--find_best_frame",
dest="find_best_frame",
action="store_true",
help=
"Generate from the frame that is the most alligned with source. (Only for faces, requires face_aligment lib)"
)
parser.add_argument("--best_frame",
dest="best_frame",
type=int,
default=None,
help="Set frame to start from.")
parser.add_argument("--cpu", dest="cpu", action="store_true", help="cpu mode.")
parser.add_argument("--ratio", dest="ratio",type=str,default="1.0", help="area ratio of face")
parser.set_defaults(relative=False)
parser.set_defaults(adapt_scale=False)
if __name__ == "__main__":
args = parser.parse_args()
if args.cpu:
paddle.set_device('cpu')
cache_path = os.path.join(args.output,"cache")
if not os.path.exists(cache_path):
os.makedirs(cache_path)
image_path = args.source_image
origin_img = cv2.imread(image_path)
image_width = origin_img.shape[1]
image_hegiht = origin_img.shape[0]
ratio = float(args.ratio)
#獲取人臉模型
module = hub.Module(name="ultra_light_fast_generic_face_detector_1mb_640")
#對照片進行人臉檢測
face_detecions = module.face_detection(paths = [image_path], visualization=True, output_dir='face_detection_output')
#獲取人臉檢測結果
face_detecions = face_detecions[0]['data']
#截取人臉圖片,并保存人臉圖片的屬性在face_list串列中,
face_list = []
for i, face_dect in enumerate(face_detecions):
left = math.ceil(face_dect['left'])
right = math.ceil(face_dect['right'])
top = math.ceil(face_dect['top'])
bottom = math.ceil(face_dect['bottom'])
width = right - left
height = bottom - top
center_x = left + width // 2
center_y = top + height // 2
size = math.ceil(ratio * height)
new_left = max(center_x - size, 0)
new_right = min(center_x + size, image_width)
new_top = max(center_y - size, 0)
new_bottom = min(center_y + size, image_hegiht)
origin_img = cv2.imread(image_path)
face_img = origin_img[new_top:new_bottom, new_left:new_right, :]
face_height = face_img.shape[0]
face_width = face_img.shape[1]
cv2.imwrite(os.path.join(cache_path,'face_{}.jpeg'.format(i)), face_img)
face_list.append({"path" : os.path.join(cache_path,'face_{}.jpeg'.format(i)),
"width":face_width, "height":face_height,
"top":new_top, "bottom":new_bottom,
"left":new_left, "right":new_right, "center_x":center_x, "center_y":center_y,
"origin_width":width, "origin_height":height})
#遍歷face_list,對每一個人臉進行動作遷移,
frames = 0
for face_dict in face_list:
predictor = FirstOrderPredictor(output=args.output,
weight_path=args.weight_path,
config=args.config,
relative=args.relative,
adapt_scale=args.adapt_scale,
find_best_frame=args.find_best_frame,
best_frame=args.best_frame)
predictions,fps = predictor.run(face_dict["path"], args.driving_video)
#將遷移后的結果保存到face_dict中
face_dict['pre'] = predictions
frames = len(predictions)
images = []
#遍歷動作遷移后的幀,將人臉放置到原圖上,
for i in range(frames):
#從原始影像上拷貝一幀影像
new_frame = origin_img.copy()
new_frame = new_frame[:,:,[2,1,0]]
for j, face_dict in enumerate(face_list):
pre = face_dict["pre"][i]
face_width = face_dict["width"]
face_height = face_dict["height"]
top = face_dict["top"]
bottom = face_dict["bottom"]
left = face_dict["left"]
right = face_dict["right"]
img = cv2.resize(pre,(face_width, face_height))
img_expand = np.zeros(origin_img.shape).astype('uint8')
img_expand[top:bottom, left:right, :] = img_as_ubyte(img)
mask = np.zeros(origin_img.shape[:2]).astype('uint8')
center_x = face_dict["center_x"]
center_y = face_dict["center_y"]
origin_width = face_dict["origin_width"]
origin_height = face_dict["origin_height"]
#繪制一個橢圓的蒙版,更貼近臉型,
cv2.ellipse(mask, (int(center_x), int(center_y)),
(math.ceil(ratio * origin_width) - , math.ceil(ratio * origin_height) - 1), 0,0,360,
(255,255,255), -1 ,8 ,0)
#利用蒙版將生成后的幀拷貝到原圖上,
new_frame = cv2.copyTo(img_expand, mask, new_frame)
if isinstance(new_frame, cv2.UMat):
new_frame = new_frame.get()
# cv2.imwrite("face_{}.jpg".format(i), img_expand)
# cv2.imwrite("test_{}.jpg".format(i), new_frame)
#方形放置
# new_frame[top:bottom, left:right, :] = img_as_ubyte(img)
#將生成后的幀保存,
images.append(new_frame)
#將圖片合并為視頻
imageio.mimsave(os.path.join(args.output, 'result.mp4'),
[img_as_ubyte(frame) for frame in images],
fps=fps)
#合并音視頻
os.system("ffmpeg -y -i " + os.path.join(args.output, 'result.mp4') + " -i /home/aistudio/MYYH.mp3 -c:v copy -c:a aac -strict experimental " + os.path.join(args.output, 'mayiyahei.mp4'))
該程式目前還有許多可以改進的地方,后續會繼續優化,
推薦使用AI Studio運行該程式,不但有免費的V100算力可使用,還可以方便的一鍵運行腳本生成視頻,
歡迎關注我的公眾號:人工智能研習社,分享更多的人工智能技術干貨,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/264896.html
標籤:AI
