From 4daa75df72968eabca59a5816b2190ba97c5ea7e Mon Sep 17 00:00:00 2001 From: Bijan Date: Thu, 17 Jul 2025 12:44:40 +0200 Subject: [PATCH] Adapted toonify client and server --- project/__pycache__/config.cpython-310.pyc | Bin 1416 -> 1478 bytes project/config.py | 2 + project/main.py | 10 -- project/models/vtoonify/face_obfuscator.py | 115 +++++++++++++----- .../start_obfuscator_server_README.TXT | 12 ++ .../__pycache__/blurring.cpython-310.pyc | Bin 1371 -> 1371 bytes .../__pycache__/epic.cpython-310.pyc | Bin 1226 -> 1226 bytes .../obfuscation_engine.cpython-310.pyc | Bin 3107 -> 3119 bytes project/obfuscation/obfuscation_engine.py | 1 - project/obfuscation/toonify.py | 9 +- 10 files changed, 101 insertions(+), 48 deletions(-) create mode 100644 project/models/vtoonify/start_obfuscator_server_README.TXT diff --git a/project/__pycache__/config.cpython-310.pyc b/project/__pycache__/config.cpython-310.pyc index 78c53760dfcdc9eb268fdbaa318bd93bf30491be..dfea7572846eaa23a8447f58cea0a3bca8dcb059 100644 GIT binary patch delta 298 zcmeC+KE}6DK^2#!%P1N>QNMT4}&*91CjpAiwaA!#2Na1W@Na1W| zisDP*3TDvcp4jEDrpb7VJtRLrFEgz&8Ds)7U;}a-fVj9|;+J%eRIz4;bhaq*$?=SK zY#`f;xF#=V^kL+g{DJX5qr~J7Osb5$i^Z53SvY`_lSNsK$00|xj9!4l+;$akG1^_g2I;;Qy delta 210 zcmX@c-NDV9&&$ij00fH@%QJi?^2#zsP1N=lac4+jPvK}`Na1K^isDJ(3}(>enmEmW z;s+_loXOmb=`882QDT#;812|NfqIKLC+}nQVdS37&Ges9d@?t)DkINgLuSUwW-Nws z5CvdWAc7l2Z~zIAt;HsjTUkuGIDUgg{4{wdA7fc%1?CiC(RYi(CO1E&G$+-L5u}+9 ONboT5FhU`d5HkQvEGH%a diff --git a/project/config.py b/project/config.py index f5e232f..c20ca02 100644 --- a/project/config.py +++ b/project/config.py @@ -5,6 +5,7 @@ from obfuscation.blurring import Blurring from obfuscation.epic import Epic #from obfuscation.fams import FAMS from obfuscation.pixelation import Pixelation +from obfuscation.toonify import Toonify class Config: @@ -38,6 +39,7 @@ class Config: debug_show_preprocessing=False obfuscation_techniques=[ + Toonify(), Epic(), Blackening(), Randoming(), diff --git a/project/main.py b/project/main.py index ad6e541..3ccb021 100644 --- a/project/main.py +++ b/project/main.py @@ -81,16 +81,6 @@ def main(): save=save_path) print(f"📊 {save_path} gespeichert") -#TODO Sehr wichtig!!!!!!!! - #TODO: 1. Img output bei toonify richtiges daten format - #TODO: 2. img output soll rescaled werden auf originalgröße - - -#TODO In toonify den wrapper und server mehr anpassen - -#TODO: VToonify - "Server" erstellen und einbinden - -#TODO Toonify client fertig stellen #TODO: neue technik einbinden UGatIt diff --git a/project/models/vtoonify/face_obfuscator.py b/project/models/vtoonify/face_obfuscator.py index 05fd208..0810494 100644 --- a/project/models/vtoonify/face_obfuscator.py +++ b/project/models/vtoonify/face_obfuscator.py @@ -12,6 +12,7 @@ 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 @@ -49,51 +50,101 @@ class VTOONIFY: 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) + 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) + def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray: - scale = 1 - kernel_1d = np.array([[0.125],[0.375],[0.375],[0.125]]) + H0, W0 = face_roi_img_bgr.shape[:2] + kernel_1d = np.array([[0.125], [0.375], [0.375], [0.125]]) - # We detect the face in the image, and resize the image so that the eye distance is 64 pixels. - # Centered on the eyes, we crop the image to almost 400x400 (based on args.padding). - paras = get_video_crop_parameter(face_roi_img_bgr, self.landmarkpredictor, self.padding) + 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 - H, W = int(bottom-top), int(right-left) - # for HR image, we apply gaussian blur to it to avoid over-sharp stylization results + 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) + 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_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] + + I_pil = align_face(face_roi_img_bgr, self.landmarkpredictor) + if I_pil is None: + I_pil = self.safe_align(face_roi_img_bgr) # fallback square + + I_tensor = self.transform(I_pil).unsqueeze(0).to(self.device) + + roi_padded, pads = self._pad_to_multiple_center(face_roi_img_bgr) + x = self.transform(roi_padded).unsqueeze(0).to(self.device) - y_tilde = None with torch.no_grad(): - I = align_face(face_roi_img_bgr, self.landmarkpredictor) - I = self.transform(I).unsqueeze(dim=0).to(self.device) #TODO: self - s_w = self.pspencoder(I) #TODO self + # style code + s_w = self.pspencoder(I_tensor) s_w = self.vtoonify.zplus2wplus(s_w) - if self.vtoonify.backbone == 'dualstylegan': - s_w[:,:7] = self.exstyle[:,:7] #TODO self + if self.vtoonify.backbone == "dualstylegan": + s_w[:, :7] = self.exstyle[:, :7] - x = self.transform(face_roi_img_bgr).unsqueeze(dim=0).to(self.device) - # parsing network works best on 512x512 images, so we predict parsing maps on upsmapled frames - # followed by downsampling the parsing maps - x_p = F.interpolate(self.parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0], #TODO self - scale_factor=0.5, recompute_scale_factor=False).detach() - # we give parsing maps lower weight (1/16) - inputs = torch.cat((x, x_p/16.), dim=1) - # d_s has no effect when backbone is toonify - y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s = 0.5) + # parsing + generator + 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) - return y_tilde + + 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] # symmetrical un‑pad + + out = cv2.resize(out, (W0, H0), cv2.INTER_LINEAR) # back to caller’s size + return out + + app = FastAPI() -if torch.cuda.is_available(): - print("torch version: ", torch.__version__, "cuda: ", torch.version.cuda) vtoonify = None image_processing_path = "/mnt/c/Users/bijan/Desktop/obfuscation_platform/project/models/vtoonify/image_cache/" @@ -114,7 +165,7 @@ def obfuscate_api(): 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) + cv2.imwrite(os.path.join(image_processing_path, "obfuscated_face.jpg"), cv2.cvtColor(obfuscated_img, cv2.COLOR_RGB2BGR)) @app.get("/health") def health(): return {"ok": True} @@ -127,6 +178,6 @@ if __name__ == "__main__": 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"), obfuscated_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) \ No newline at end of file diff --git a/project/models/vtoonify/start_obfuscator_server_README.TXT b/project/models/vtoonify/start_obfuscator_server_README.TXT new file mode 100644 index 0000000..ee9b288 --- /dev/null +++ b/project/models/vtoonify/start_obfuscator_server_README.TXT @@ -0,0 +1,12 @@ +@echo off +REM — Activate your conda env and return here +call conda activate obfuscation_platform_p38 +if ERRORLEVEL 1 ( + echo Failed to activate obda environment. + pause + exit /b 1 +) + +echo Environment activated. Starting server... +uvicorn face_obfuscator:app --host 127.0.0.1 --port 8000 +pause \ No newline at end of file diff --git a/project/obfuscation/__pycache__/blurring.cpython-310.pyc b/project/obfuscation/__pycache__/blurring.cpython-310.pyc index 80d04da43c713f19d960b8dd1235a328f17d7f62..9333af6d7641311cf1016abc5284c2378abd24c0 100644 GIT binary patch delta 19 Zcmcc3b(@PTpO=@50SGuRY~%`L1pqKz1X2J1 delta 19 Zcmcc3b(@PTpO=@50SL_cHgW~B0st@}1U&!% diff --git a/project/obfuscation/__pycache__/epic.cpython-310.pyc b/project/obfuscation/__pycache__/epic.cpython-310.pyc index c18ed6d251f248c8c659e666d50c0d008e5d7782..d1c1e6e7866bd34db635d0970bb13fe62e878f17 100644 GIT binary patch delta 50 zcmX@bd5V)SpO=@50SGSsEzjU!*~qt%k&$on0me>7M$yS$%-M`GleaNfF>*~dWSPOp F3;7Mv=*0%-M|6leaNfF>+2eWSPOp F1OQmP4Iuyk diff --git a/project/obfuscation/__pycache__/obfuscation_engine.cpython-310.pyc b/project/obfuscation/__pycache__/obfuscation_engine.cpython-310.pyc index 8925d39a6ddb74e7ac270724d841c1db532fa8fe..69268be4b71a92fa49d2babb4657fd6dc1e14c7b 100644 GIT binary patch delta 84 zcmZ21v0j2VpO=@50SHttRb(98$ji^p_+hdvy9s0Lw{p(|0HE|1-~a#s delta 74 zcmZ24u~>pPpO=@50SI_jmu1Y|$ji^p_-e8&y9r~| np.ndarray: cv2.imwrite(os.path.join(self.image_processing_path, "face.jpg"), face_roi_img_bgr) - resp = requests.get(f"http://127.0.0.1:8000/obfuscate", timeout=60) + resp = requests.get("http://127.0.0.1:8000/obfuscate", timeout=120) resp.raise_for_status() obfuscated_face = cv2.imread(os.path.join(self.image_processing_path, "obfuscated_face.jpg")) return obfuscated_face