git clone https://github.com/minivision-ai/photo2cartoon.git
cd ./photo2cartoon
python test.py --photo_path images/photo_test.jpg --save_path images/cartoon_result.png
1. 效果圖
官方效果圖如下:
效果圖1如下:
效果圖2如下:
效果圖3如下:
2. 原理
人像卡通風(fēng)格渲染的目標(biāo)是,在保持原圖像 ID 信息和紋理細(xì)節(jié)的同時(shí),將真實(shí)照片轉(zhuǎn)換為卡通風(fēng)格的非真實(shí)感圖像。
但是圖像卡通化任務(wù)面臨著一些難題:
- 卡通圖像往往有清晰的邊緣,平滑的色塊和經(jīng)過簡化的紋理,與其他藝術(shù)風(fēng)格有很大區(qū)別。使用傳統(tǒng)圖像處理技術(shù)生成的卡通圖無法自適應(yīng)地處理復(fù)雜的光照和紋理,效果較差;基于風(fēng)格遷移的方法無法對細(xì)節(jié)進(jìn)行準(zhǔn)確地勾勒。
- 數(shù)據(jù)獲取難度大。繪制風(fēng)格精美且統(tǒng)一的卡通畫耗時(shí)較多、成本較高,且轉(zhuǎn)換后的卡通畫和原照片的臉型及五官形狀有差異,因此不構(gòu)成像素級的成對數(shù)據(jù),難以采用基于成對數(shù)據(jù)的圖像翻譯(Paired Image Translation)方法。
- 照片卡通化后容易丟失身份信息?;诜浅蓪?shù)據(jù)的圖像翻譯(Unpaired Image Translation)方法中的循環(huán)一致性損失(Cycle Loss)無法對輸入輸出的 id 進(jìn)行有效約束。
小視科技的研究團(tuán)隊(duì)提出了一種基于生成對抗網(wǎng)絡(luò)的卡通化模型,只需少量非成對訓(xùn)練數(shù)據(jù),就能獲得漂亮的結(jié)果??ㄍL(fēng)格渲染網(wǎng)絡(luò)是該解決方案的核心,它主要由特征提取、特征融合和特征重建三部分組成。
3. 源碼
源碼及示例文件模型等見資源:https://download.csdn.net/download/qq_40985985/87739184
代碼下載 https://github.com/minivision-ai/photo2cartoon
模型下載 https://drive.google.com/uc?id=1eDNGZT3jszHLXQ9XGIUPtcu72HdBmHuX&export=download文章來源:http://www.zghlxwxcb.cn/news/detail-431076.html
人像卡通化預(yù)訓(xùn)練模型:photo2cartoon_weights.pt,存放在 models 路徑下。
頭像分割模型:seg_model_384.pb,存放在 utils 路徑下。
人臉識別預(yù)訓(xùn)練模型:model_mobilefacenet.pth,存放在 models 路徑下。
卡通畫開源數(shù)據(jù):cartoon_data,包含 trainB 和 testB文章來源地址http://www.zghlxwxcb.cn/news/detail-431076.html
# 使用預(yù)訓(xùn)練的模型生成漫畫頭像
# python test.py --photo_path images/ml.jpg --save_path images/cartoon_ml_result.png
import argparse
import os
import cv2
import numpy as np
import torch
from models import ResnetGenerator
from utils import Preprocess
parser = argparse.ArgumentParser()
parser.add_argument('--photo_path', type=str, default='images/photo_test.jpg', help='input photo path')
parser.add_argument('--save_path', type=str, default='images/photo_test_cartoon.jpg', help='cartoon save path')
args = parser.parse_args()
os.makedirs(os.path.dirname(args.save_path), exist_ok=True)
class Photo2Cartoon:
def __init__(self):
self.pre = Preprocess()
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
self.net = ResnetGenerator(ngf=32, img_size=256, light=True).to(self.device)
assert os.path.exists(
'./models/photo2cartoon_weights.pt'), "[Step1: load weights] Can not find 'photo2cartoon_weights.pt' in folder 'models!!!'"
params = torch.load('./models/photo2cartoon_weights.pt', map_location=self.device)
self.net.load_state_dict(params['genA2B'])
print('[Step1: load weights] success!')
def inference(self, img):
# face alignment and segmentation
face_rgba = self.pre.process(img)
if face_rgba is None:
print('[Step2: face detect] can not detect face!!!')
return None
print('[Step2: face detect] success!')
face_rgba = cv2.resize(face_rgba, (256, 256), interpolation=cv2.INTER_AREA)
face = face_rgba[:, :, :3].copy()
mask = face_rgba[:, :, 3][:, :, np.newaxis].copy() / 255.
face = (face * mask + (1 - mask) * 255) / 127.5 - 1
face = np.transpose(face[np.newaxis, :, :, :], (0, 3, 1, 2)).astype(np.float32)
face = torch.from_numpy(face).to(self.device)
# inference
with torch.no_grad():
cartoon = self.net(face)[0][0]
# post-process
cartoon = np.transpose(cartoon.cpu().numpy(), (1, 2, 0))
cartoon = (cartoon + 1) * 127.5
cartoon = (cartoon * mask + 255 * (1 - mask)).astype(np.uint8)
cartoon = cv2.cvtColor(cartoon, cv2.COLOR_RGB2BGR)
print('[Step3: photo to cartoon] success!')
return cartoon
if __name__ == '__main__':
img = cv2.cvtColor(cv2.imread(args.photo_path), cv2.COLOR_BGR2RGB)
c2p = Photo2Cartoon()
cartoon = c2p.inference(img)
if cartoon is not None:
cv2.imwrite(args.save_path, cartoon)
print('Cartoon portrait has been saved successfully!')
origin = cv2.resize(cv2.imread(args.photo_path), (256, 256))
res = cv2.imread(args.save_path)
print(origin.shape, res.shape)
cv2.imshow("origin VS cartoon", np.hstack([origin, res]))
cv2.waitKey(0)
參考
- https://blog.csdn.net/weixin_47196664/article/details/106542463
- 代碼下載 https://github.com/minivision-ai/photo2cartoon
- 模型下載 https://drive.google.com/uc?id=1eDNGZT3jszHLXQ9XGIUPtcu72HdBmHuX&export=download
- https://blog.csdn.net/kexuanxiu1163/article/details/105858528
到了這里,關(guān)于Python使用AI photo2cartoon制作屬于你的漫畫頭像的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!