199 lines
7.4 KiB
Python
199 lines
7.4 KiB
Python
import os
|
|
#os.environ['CUDA_VISIBLE_DEVICES'] = "0"
|
|
import argparse
|
|
import numpy as np
|
|
import cv2
|
|
import dlib
|
|
import torch
|
|
from torchvision import transforms
|
|
import torch.nn.functional as F
|
|
from tqdm import tqdm
|
|
from model.vtoonify import VToonify
|
|
from model.bisenet.model import BiSeNet
|
|
from model.encoder.align_all_parallel import align_face
|
|
from util import save_image, load_image, visualize, load_psp_standalone, get_video_crop_parameter, tensor2cv2
|
|
import cv2, PIL.Image as Image
|
|
|
|
from fastapi import FastAPI, HTTPException
|
|
|
|
|
|
class VTOONIFY:
|
|
def __init__(self):
|
|
self.device = "cuda"
|
|
self.padding = [200,200,200,200]
|
|
self.transform = transforms.Compose([
|
|
transforms.ToTensor(),
|
|
transforms.Normalize(mean=[0.5, 0.5, 0.5],std=[0.5,0.5,0.5]),
|
|
])
|
|
|
|
self.vtoonify = VToonify(backbone = "dualstylegan")
|
|
self.vtoonify.load_state_dict(torch.load("./checkpoint/vtoonify_d_cartoon/vtoonify_s_d.pt", map_location=lambda storage, loc: storage)['g_ema'])
|
|
self.vtoonify.to(self.device)
|
|
|
|
self.parsingpredictor = BiSeNet(n_classes=19)
|
|
self.parsingpredictor.load_state_dict(torch.load("./checkpoint/faceparsing.pth", map_location=lambda storage, loc: storage))
|
|
self.parsingpredictor.to(self.device).eval()
|
|
|
|
modelname = './checkpoint/shape_predictor_68_face_landmarks.dat'
|
|
if not os.path.exists(modelname):
|
|
import wget, bz2
|
|
wget.download('http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2', modelname+'.bz2')
|
|
zipfile = bz2.BZ2File(modelname+'.bz2')
|
|
data = zipfile.read()
|
|
open(modelname, 'wb').write(data)
|
|
self.landmarkpredictor = dlib.shape_predictor(modelname)
|
|
|
|
self.pspencoder = load_psp_standalone("./checkpoint/encoder.pt", self.device)
|
|
exstyle_path = os.path.join(os.path.dirname("./checkpoint/vtoonify_d_cartoon/"), "exstyle_code.npy")
|
|
exstyles = np.load(exstyle_path, allow_pickle='TRUE').item()
|
|
style_id = 26
|
|
stylename = list(exstyles.keys())[style_id]
|
|
self.exstyle = torch.tensor(exstyles[stylename]).to(self.device)
|
|
with torch.no_grad():
|
|
self.exstyle = self.vtoonify.zplus2wplus(self.exstyle)
|
|
|
|
@staticmethod
|
|
def safe_align(img_bgr: np.ndarray, out_size: int = 256) -> Image.Image:
|
|
h, w = img_bgr.shape[:2]
|
|
side = min(h, w)
|
|
top = (h - side) // 2
|
|
left = (w - side) // 2
|
|
crop = img_bgr[top:top+side, left:left+side]
|
|
crop = cv2.resize(crop, (out_size, out_size), cv2.INTER_AREA)
|
|
crop = cv2.cvtColor(crop, cv2.COLOR_BGR2RGB)
|
|
return Image.fromarray(crop)
|
|
|
|
@staticmethod
|
|
def _pad_to_multiple_center(img: np.ndarray, mod: int = 32):
|
|
h, w = img.shape[:2]
|
|
pad_h = (mod - h % mod) % mod
|
|
pad_w = (mod - w % mod) % mod
|
|
|
|
pad_top = pad_h // 2
|
|
pad_bottom = pad_h - pad_top
|
|
pad_left = pad_w // 2
|
|
pad_right = pad_w - pad_left
|
|
|
|
img_pad = cv2.copyMakeBorder(img,
|
|
pad_top, pad_bottom,
|
|
pad_left, pad_right,
|
|
cv2.BORDER_REFLECT_101)
|
|
return img_pad, (pad_top, pad_bottom, pad_left, pad_right)
|
|
|
|
@staticmethod
|
|
def _resize_if_large(img, max_side=800):
|
|
h, w = img.shape[:2]
|
|
if max(h, w) <= max_side:
|
|
return img
|
|
scale = max_side / max(h, w)
|
|
img_small = cv2.resize(img,
|
|
(int(w * scale), int(h * scale)),
|
|
interpolation=cv2.INTER_LINEAR)
|
|
return img_small
|
|
|
|
|
|
def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray:
|
|
H0, W0 = face_roi_img_bgr.shape[:2]
|
|
|
|
face_roi_img_bgr = self._resize_if_large(face_roi_img_bgr)
|
|
|
|
kernel_1d = np.array([[0.125], [0.375], [0.375], [0.125]])
|
|
|
|
paras = get_video_crop_parameter(face_roi_img_bgr,
|
|
self.landmarkpredictor,
|
|
self.padding)
|
|
if paras is not None:
|
|
h, w, top, bottom, left, right, scale = paras
|
|
if scale <= 0.75:
|
|
face_roi_img_bgr = cv2.sepFilter2D(face_roi_img_bgr, -1,
|
|
kernel_1d, kernel_1d)
|
|
if scale <= 0.375:
|
|
face_roi_img_bgr = cv2.sepFilter2D(face_roi_img_bgr, -1,
|
|
kernel_1d, kernel_1d)
|
|
face_roi_img_bgr = cv2.resize(face_roi_img_bgr, (w, h))[top:bottom,
|
|
left:right]
|
|
|
|
face_rgb = cv2.cvtColor(face_roi_img_bgr, cv2.COLOR_BGR2RGB)
|
|
|
|
I_pil = align_face(face_rgb, self.landmarkpredictor)
|
|
if I_pil is None:
|
|
I_pil = self.safe_align(face_roi_img_bgr)
|
|
|
|
I_tensor = self.transform(I_pil).unsqueeze(0).to(self.device)
|
|
|
|
roi_padded, pads = self._pad_to_multiple_center(face_rgb)
|
|
x = self.transform(roi_padded).unsqueeze(0).to(self.device)
|
|
|
|
|
|
with torch.no_grad():
|
|
s_w = self.pspencoder(I_tensor)
|
|
s_w = self.vtoonify.zplus2wplus(s_w)
|
|
if self.vtoonify.backbone == "dualstylegan":
|
|
s_w[:, :7] = self.exstyle[:, :7]
|
|
|
|
x_p = F.interpolate(
|
|
self.parsingpredictor(
|
|
2 * F.interpolate(x, scale_factor=2, mode="bilinear",
|
|
align_corners=False)
|
|
)[0],
|
|
scale_factor=0.5,
|
|
recompute_scale_factor=False
|
|
).detach()
|
|
|
|
y_tilde = self.vtoonify(
|
|
torch.cat((x, x_p / 16.0), dim=1),
|
|
s_w.repeat(x.size(0), 1, 1),
|
|
d_s=0.5
|
|
)
|
|
y_tilde = torch.clamp(y_tilde, -1, 1)
|
|
|
|
out = tensor2cv2(y_tilde[0].cpu()) # BGR uint8
|
|
|
|
|
|
pad_top, pad_bottom, pad_left, pad_right = pads
|
|
out = out[pad_top: out.shape[0]-pad_bottom,
|
|
pad_left: out.shape[1]-pad_right]
|
|
|
|
out = cv2.resize(out, (W0, H0), cv2.INTER_LINEAR)
|
|
return out
|
|
|
|
|
|
|
|
|
|
app = FastAPI()
|
|
vtoonify = None
|
|
image_processing_path = "/mnt/c/Users/bijan/Desktop/obfuscation_platform/project/models/vtoonify/image_cache/"
|
|
|
|
@app.get("/init")
|
|
def init():
|
|
try:
|
|
print("initiating vtoonify")
|
|
global vtoonify
|
|
vtoonify = VTOONIFY()
|
|
except Exception as e:
|
|
print(e)
|
|
raise HTTPException(500, detail=str(e))
|
|
|
|
@app.get("/obfuscate")
|
|
def obfuscate_api():
|
|
img = cv2.imread(os.path.join(image_processing_path, "face.jpg"), cv2.IMREAD_UNCHANGED)
|
|
if img is None:
|
|
raise HTTPException(500, f"cv2 failed to read image at {image_processing_path}")
|
|
global vtoonify
|
|
obfuscated_img = vtoonify.obfuscate(img)
|
|
cv2.imwrite(os.path.join(image_processing_path, "obfuscated_face.jpg"), obfuscated_img)
|
|
|
|
@app.get("/health")
|
|
def health(): return {"ok": True}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print("Starting test obfuscation")
|
|
path = os.path.join(image_processing_path, "face.jpg")
|
|
if os.path.exists(path):
|
|
img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
|
|
model = VTOONIFY()
|
|
obfuscated_img = model.obfuscate(img)
|
|
cv2.imwrite(os.path.join(image_processing_path, "obfuscated_face.jpg"), cv2.cvtColor(obfuscated_img, cv2.COLOR_RGB2BGR))
|
|
else:
|
|
print("Path is invalid", path) |