141 lines
4.4 KiB
Python
141 lines
4.4 KiB
Python
import os.path
|
|
import pathlib
|
|
import shutil
|
|
|
|
import cv2
|
|
import fire
|
|
import pandas as pd
|
|
import pytorch_lightning
|
|
from loguru import logger
|
|
from sklearn.model_selection import train_test_split
|
|
import torch
|
|
from torchvision.transforms import RandomHorizontalFlip, Compose
|
|
from torchvision.transforms import transforms
|
|
from tqdm import tqdm
|
|
|
|
from lib.datasets import DatasetSplit
|
|
from lib.datasets.label_extractor import extract_labels
|
|
from lib.datasets.labeled_dataset import LabeledDataset
|
|
from lib.evaluator import eval_classifier
|
|
from lib.models.generic_classifier import GenericClassifier
|
|
from lib.models.pix2pix import Pix2Pix
|
|
from lib.trainer import setup_torch_device, setup
|
|
from lib.transform import transform, ZeroPaddingResize
|
|
from lib.transform.face_crop_transformer import FaceCrop
|
|
from lib.transform.face_segmentation_transformer import FaceSegmentation
|
|
from lib.transform.facial_landmarks_478_transformer import FacialLandmarks478
|
|
from lib.transform.pix2pix_transformer import Pix2PixTransformer
|
|
from lib.utils import glob_dir, get_last_ckpt, move_files
|
|
|
|
from fastapi import FastAPI, HTTPException
|
|
import numpy as np
|
|
|
|
|
|
|
|
|
|
class GANONYMIZATION():
|
|
def __init__(self):
|
|
model_file = "GANonymization.ckpt"
|
|
self.img_size = 512
|
|
self.align = True
|
|
self.device = 0
|
|
self.landmark_model = FacialLandmarks478()
|
|
self.padding_resize = ZeroPaddingResize(self.img_size)
|
|
self.pix2pix_transformer = Pix2PixTransformer(model_file, self.img_size, self.device)
|
|
|
|
def obfuscate(self, face_img: np.ndarray) -> np.ndarray:
|
|
H0, W0 = face_img.shape[:2]
|
|
|
|
with torch.no_grad():
|
|
patch = self.padding_resize(face_img)
|
|
patch = self.landmark_model(patch)
|
|
patch = self.pix2pix_transformer(patch).squeeze(0)
|
|
patch = ((patch + 1) / 2).clamp_(0, 1).detach()
|
|
|
|
patch = (patch * 255).permute(1, 2, 0).byte().cpu().numpy()
|
|
|
|
max_side = max(H0, W0)
|
|
scale = self.img_size / max_side
|
|
new_w = int(round(W0 * scale))
|
|
new_h = int(round(H0 * scale))
|
|
pad_x = (self.img_size - new_w) // 2
|
|
pad_y = (self.img_size - new_h) // 2
|
|
patch = patch[pad_y : pad_y + new_h, pad_x : pad_x + new_w]
|
|
|
|
s = min(W0 / new_w, H0 / new_h)
|
|
if abs(s - 1.0) > 1e-3:
|
|
patch = cv2.resize(
|
|
patch,
|
|
(int(round(new_w * s)), int(round(new_h * s))),
|
|
interpolation=cv2.INTER_LINEAR,
|
|
)
|
|
new_h, new_w = patch.shape[:2]
|
|
|
|
patch_bgr = cv2.cvtColor(patch, cv2.COLOR_RGB2BGR)
|
|
mask = np.full((new_h, new_w), 255, np.uint8)
|
|
|
|
cx = np.clip(W0 // 2, new_w // 2, W0 - new_w // 2)
|
|
cy = np.clip(H0 // 2, new_h // 2, H0 - new_h // 2)
|
|
|
|
#result = cv2.seamlessClone(
|
|
# src = patch_bgr,
|
|
# dst = face_img,
|
|
# mask = mask,
|
|
# p = (int(cx), int(cy)),
|
|
# flags = cv2.NORMAL_CLONE,
|
|
#)
|
|
#return cv2.cvtColor(result, cv2.COLOR_BGR2RGB)
|
|
|
|
x1 = int(cx - new_w // 2)
|
|
y1 = int(cy - new_h // 2)
|
|
x2 = x1 + new_w
|
|
y2 = y1 + new_h
|
|
|
|
result = face_img.copy()
|
|
result[y1:y2, x1:x2] = patch_bgr
|
|
return cv2.cvtColor(result, cv2.COLOR_BGR2RGB)
|
|
|
|
app = FastAPI()
|
|
|
|
ganonymization = None
|
|
image_processing_path = "/mnt/c/Users/bijan/Desktop/obfuscation_platform/project/models/ganonymization/image_cache/"
|
|
|
|
@app.get("/init")
|
|
def init():
|
|
try:
|
|
print("initiating ganonymization")
|
|
global ganonymization
|
|
ganonymization = GANONYMIZATION()
|
|
|
|
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"))
|
|
global ganonymization
|
|
obfuscated_img = ganonymization.obfuscate(img)
|
|
pil_img = transforms.ToPILImage()(obfuscated_img)
|
|
pil_img.save(os.path.join(image_processing_path, "obfuscated_face.jpg"))
|
|
|
|
@app.get("/health")
|
|
def health(): return {"ok": True}
|
|
|
|
|
|
def main():
|
|
print("TEST RUN")
|
|
obfuscator = GANONYMIZATION()
|
|
print("INIT DONE")
|
|
original_image = cv2.imread("face.jpg")
|
|
print("Image LOADING DONE")
|
|
obfuscated = obfuscator.obfuscate(original_image)
|
|
print("OBFUSCATION DONE")
|
|
pil_img = transforms.ToPILImage()(obfuscated)
|
|
pil_img.save("obfuscated_face.jpg")
|
|
print("SAVING DONE")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|