refactored code for gpu usage

This commit is contained in:
2025-07-15 19:56:40 +02:00
parent eec367c528
commit 0e5d468d5a
8 changed files with 12 additions and 69 deletions
-1
View File
@@ -1,6 +1,5 @@
import os
import json
import random
from config import Config
from meta_data.meta_data_extractor import MetaExtractor, ImageMeta
-1
View File
@@ -16,7 +16,6 @@ from visualization.visualizer import Visualizer
# random.seed(Config.seed)
# torch.manual_seed(Config.seed)
def main():
print("Starting obfuscation platform")
#1: Preprocess images and extract metadata
+9 -62
View File
@@ -1,5 +1,4 @@
import os
import random
import matplotlib
@@ -9,17 +8,12 @@ from fastapi import FastAPI, HTTPException
import cv2
import yaml
from argparse import ArgumentParser
# from tqdm import tqdm
import sys
import time
import imageio
import numpy as np
from skimage.transform import resize
from skimage import img_as_ubyte
from skimage.exposure import match_histograms
import json
import torch
from sync_batchnorm import DataParallelWithCallback
import torch.nn.functional as F
@@ -138,31 +132,6 @@ def load_checkpoints(config, checkpoint, blend_scale=0.125, first_order_motion_m
return reconstruction_module, segmentation_module
def load_face_parser(cpu=False):
from face_parsing.model import BiSeNet
face_parser = BiSeNet(n_classes=19)
if not cpu:
face_parser.cuda()
face_parser.load_state_dict(torch.load('face_parsing/cp/79999_iter.pth'))
else:
face_parser.load_state_dict(torch.load('face_parsing/cp/79999_iter.pth', map_location=torch.device('cpu')))
face_parser.eval()
mean = torch.Tensor(np.array([0.485, 0.456, 0.406], dtype=np.float32)).view(1, 3, 1, 1)
std = torch.Tensor(np.array([0.229, 0.224, 0.225], dtype=np.float32)).view(1, 3, 1, 1)
if not cpu:
face_parser.mean = mean.cuda()
face_parser.std = std.cuda()
else:
face_parser.mean = mean
face_parser.std = std
return face_parser
def make_video(swap_index, source_image, target_video, reconstruction_module, segmentation_module, face_parser=None,
hard=False, use_source_segmentation=False, cpu=False):
assert type(swap_index) == list
@@ -205,43 +174,19 @@ def obfuscate(swap_index, source_image, target_image, reconstruction_module, seg
source_image=source_image,
target_video=[resize(target_image, (256, 256))[..., :3]],
reconstruction_module=reconstruction_module,
segmentation_module=segmentation_module, cpu=True)[0])
cv2.imshow("Source", source_image)
cv2.imshow("Target", target_image)
cv2.waitKey()
cv2.imshow("TEST", model_output)
cv2.waitKey()
#TODO entfernen
test_rescale = cv2.resize(model_output, (original_shape[1], original_shape[0]), interpolation=cv2.INTER_LINEAR)
cv2.imshow("TEST0", test_rescale)
cv2.waitKey()
###
segmentation_module=segmentation_module, cpu=False)[0])
matched = match_histograms(model_output, target_image, multichannel=True)
rescaled = cv2.resize(matched, (original_shape[1], original_shape[0]), interpolation=cv2.INTER_LINEAR)
cv2.imshow("TEST1", rescaled)
cv2.waitKey()
mask = np.full((rescaled.shape[0], rescaled.shape[1]), 255, dtype=np.uint8) #cv2.inRange(rescaled, (0,0,0), (250,250,250)) # 0 or 255
center = (mask.shape[1] // 2, mask.shape[0] // 2)
# 4. Blend it ------------------------------------------------------------
output = cv2.seamlessClone(
rescaled,
target_image,
mask, # 8‑bit 1‑channel mask
center, # placement in dst
cv2.NORMAL_CLONE) # or MIXED_CLONE, MONOCHROME_TRANSFER
cv2.imshow("TEST2", output)
cv2.waitKey()
cv2.imshow("TEST3", binary_diff_map(rescaled, output))
cv2.waitKey()
mask,
center,
cv2.NORMAL_CLONE)
return output
@@ -269,7 +214,7 @@ class EPIC:
def __init__(self, checkpoint_path, config_path, fake_face_path):
self.swap_indices = [2, 3, 9, 11, 15] #Indices of face regions to swap
self.fake_face = resize(cv2.imread(fake_face_path), (256, 256))[..., :3]
self.reconstruction_module, self.segmentation_module = load_checkpoints(config_path, checkpoint_path, blend_scale=1, cpu=True)
self.reconstruction_module, self.segmentation_module = load_checkpoints(config_path, checkpoint_path, blend_scale=1, cpu=False)
def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray:
return obfuscate(swap_index=self.swap_indices,
@@ -281,6 +226,8 @@ class EPIC:
app = FastAPI()
if torch.cuda.is_available():
print("torch version: ", torch.__version__, "cuda: ", torch.version.cuda)
epic = None
image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/epic/image_cache/"
@@ -290,7 +237,7 @@ def init():
print("initiating epic")
checkpoint_path = "stuff/vox-15segments.pth.tar"
config_path = "config/vox-256-sem-15segments.yaml"
fake_face_path = "stuff/fake_face.png"
fake_face_path = "stuff/fake_face.jpg"
global epic
epic = EPIC(checkpoint_path, config_path, fake_face_path)
except Exception as e:
Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

@@ -8,4 +8,5 @@ if ERRORLEVEL 1 (
)
echo Environment activated. Starting server...
uvicorn face_obfuscator:app --host 127.0.0.1 --port 8000
uvicorn face_obfuscator:app --host 127.0.0.1 --port 8000
pause
Binary file not shown.
+1 -4
View File
@@ -21,10 +21,7 @@ class Epic(ObfuscationTechnique):
resp = requests.get(f"http://127.0.0.1:8000/obfuscate", timeout=5)
resp.raise_for_status()
obfuscated_face = cv2.imread(os.path.join(self.image_processing_path, "obfuscated_face.jpg"))
exit() #TODO Entfernen
#TODO: Das bild ggf zu RGB bei face_obfuscator.py und dann wieder zurück
#TODO bei epic noch cloning, schauen wie das war
return obfuscated_face
def name(self):
return "EPIC"
return "Epic"