diff --git a/project/__pycache__/config.cpython-310.pyc b/project/__pycache__/config.cpython-310.pyc index 78c5376..dfea757 100644 Binary files a/project/__pycache__/config.cpython-310.pyc and b/project/__pycache__/config.cpython-310.pyc differ 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 80d04da..9333af6 100644 Binary files a/project/obfuscation/__pycache__/blurring.cpython-310.pyc and b/project/obfuscation/__pycache__/blurring.cpython-310.pyc differ diff --git a/project/obfuscation/__pycache__/epic.cpython-310.pyc b/project/obfuscation/__pycache__/epic.cpython-310.pyc index c18ed6d..d1c1e6e 100644 Binary files a/project/obfuscation/__pycache__/epic.cpython-310.pyc and b/project/obfuscation/__pycache__/epic.cpython-310.pyc differ diff --git a/project/obfuscation/__pycache__/obfuscation_engine.cpython-310.pyc b/project/obfuscation/__pycache__/obfuscation_engine.cpython-310.pyc index 8925d39..69268be 100644 Binary files a/project/obfuscation/__pycache__/obfuscation_engine.cpython-310.pyc and b/project/obfuscation/__pycache__/obfuscation_engine.cpython-310.pyc differ diff --git a/project/obfuscation/obfuscation_engine.py b/project/obfuscation/obfuscation_engine.py index 9334dcd..cda5a04 100644 --- a/project/obfuscation/obfuscation_engine.py +++ b/project/obfuscation/obfuscation_engine.py @@ -78,4 +78,3 @@ class ObfuscationEngine: #save image cv2.imwrite(obfuscated_image_output_path, obfuscated_image) - diff --git a/project/obfuscation/toonify.py b/project/obfuscation/toonify.py index e90713f..f62ca61 100644 --- a/project/obfuscation/toonify.py +++ b/project/obfuscation/toonify.py @@ -13,15 +13,14 @@ class Toonify(ObfuscationTechnique): Replace face with generated face """ def __init__(self): - print("toonify not active") - # self.image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/epic/image_cache/" - # resp = requests.get(f"http://127.0.0.1:8000/init", timeout=60) - # resp.raise_for_status() + self.image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/vtoonify/image_cache/" + resp = requests.get("http://127.0.0.1:8000/init", timeout=120) + resp.raise_for_status() def obfuscate(self, face_roi_img_bgr: np.ndarray) -> 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