Files

192 lines
6.6 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)
#gray = cv2.cvtColor(patch_bgr, cv2.COLOR_BGR2GRAY)
#_, fgmask = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)
# 2. Target rectangle in the destination image
#x1 = int(cx - new_w // 2)
#y1 = int(cy - new_h // 2)
#x2 = x1 + new_w
#y2 = y1 + new_h
#result = face_img.copy() # keep the original intact
#roi = result[y1:y2, x1:x2] # region of interest with same size as patch
# 3. Copy only where fgmask == 255
#cv2.copyTo(patch_bgr, fgmask, roi) # OpenCV handles the boolean blend
# ---------------------------------------------------------------------
#return cv2.cvtColor(result, cv2.COLOR_BGR2RGB)
# ---------- paste + seamless-clone onto the original -----------------
# 1) Build a foreground mask for the *patch* (tweak threshold if needed)
gray = cv2.cvtColor(patch_bgr, cv2.COLOR_BGR2GRAY)
_, fgmask = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)
# 2) Coordinates of the patch on the destination canvas
x1 = int(cx - new_w // 2)
y1 = int(cy - new_h // 2)
x2 = x1 + new_w
y2 = y1 + new_h
# 3) Start from a copy of the original; paste the patch with its mask
result = face_img.copy() # same size as face_img
roi = result[y1:y2, x1:x2] # region of interest
cv2.copyTo(patch_bgr, fgmask, roi) # masked paste
# 4) Build a *global* mask the same size as the full image;
# insert the local fgmask in its correct position
big_mask = np.zeros((H0, W0), np.uint8)
big_mask[y1:y2, x1:x2] = fgmask
# 5) Seamlessly clone the modified image back onto the original
blended = cv2.seamlessClone(
src = result, # contains the pasted face
dst = face_img, # original image
mask = big_mask, # which pixels to blend
p = (int(cx), int(cy)), # centre of the mask
flags = cv2.NORMAL_CLONE,
)
return cv2.cvtColor(blended, 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.png"))
global ganonymization
obfuscated_img = ganonymization.obfuscate(img)
pil_img = transforms.ToPILImage()(obfuscated_img)
pil_img.save(os.path.join(image_processing_path, "obfuscated_face.png"))
@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()