305 lines
13 KiB
Python
305 lines
13 KiB
Python
import os
|
||
|
||
import matplotlib
|
||
|
||
|
||
matplotlib.use('Agg')
|
||
from fastapi import FastAPI, HTTPException
|
||
|
||
import cv2
|
||
import yaml
|
||
import numpy as np
|
||
from skimage.transform import resize
|
||
from skimage import img_as_ubyte
|
||
from skimage.exposure import match_histograms
|
||
import torch
|
||
|
||
from sync_batchnorm import DataParallelWithCallback
|
||
import torch.nn.functional as F
|
||
|
||
from modules.segmentation_module import SegmentationModule
|
||
from modules.reconstruction_module import ReconstructionModule
|
||
|
||
from logger import load_reconstruction_module, load_segmentation_module
|
||
|
||
from modules.util import AntiAliasInterpolation2d
|
||
from modules.dense_motion import DenseMotionNetwork
|
||
|
||
class PartSwapGenerator(ReconstructionModule):
|
||
def __init__(self, blend_scale=1, first_order_motion_model=False, **kwargs):
|
||
super(PartSwapGenerator, self).__init__(**kwargs)
|
||
if blend_scale == 1:
|
||
self.blend_downsample = lambda x: x
|
||
else:
|
||
self.blend_downsample = AntiAliasInterpolation2d(1, blend_scale)
|
||
|
||
if first_order_motion_model:
|
||
self.dense_motion_network = DenseMotionNetwork()
|
||
else:
|
||
self.dense_motion_network = None
|
||
|
||
def forward(self, source_image, target_image, seg_target, seg_source, blend_mask, use_source_segmentation=False):
|
||
# Encoding of source image
|
||
enc_source = self.first(source_image)
|
||
for i in range(len(self.down_blocks)):
|
||
enc_source = self.down_blocks[i](enc_source)
|
||
|
||
# Encoding of target image
|
||
enc_target = self.first(target_image)
|
||
for i in range(len(self.down_blocks)):
|
||
enc_target = self.down_blocks[i](enc_target)
|
||
|
||
output_dict = {}
|
||
# Compute flow field for source image
|
||
if self.dense_motion_network is None:
|
||
segment_motions = self.segment_motion(seg_target, seg_source)
|
||
segment_motions = segment_motions.permute(0, 1, 4, 2, 3)
|
||
mask = seg_target['segmentation'].unsqueeze(2)
|
||
deformation = (segment_motions * mask).sum(dim=1)
|
||
deformation = deformation.permute(0, 2, 3, 1)
|
||
else:
|
||
motion = self.dense_motion_network(source_image=source_image, seg_target=seg_target,
|
||
seg_source=seg_source)
|
||
deformation = motion['deformation']
|
||
|
||
# Deform source encoding according to the motion
|
||
enc_source = self.deform_input(enc_source, deformation)
|
||
|
||
if self.estimate_visibility:
|
||
if self.dense_motion_network is None:
|
||
visibility = seg_source['segmentation'][:, 1:].sum(dim=1, keepdim=True) * \
|
||
(1 - seg_target['segmentation'][:, 1:].sum(dim=1, keepdim=True).detach())
|
||
visibility = 1 - visibility
|
||
else:
|
||
visibility = motion['visibility']
|
||
|
||
if enc_source.shape[2] != visibility.shape[2] or enc_source.shape[3] != visibility.shape[3]:
|
||
visibility = F.interpolate(visibility, size=enc_source.shape[2:], mode='bilinear')
|
||
enc_source = enc_source * visibility
|
||
|
||
blend_mask = self.blend_downsample(blend_mask)
|
||
# If source segmentation is provided use it should be deformed before blending
|
||
if use_source_segmentation:
|
||
blend_mask = self.deform_input(blend_mask, deformation)
|
||
|
||
out = enc_target * (1 - blend_mask) + enc_source * blend_mask
|
||
|
||
out = self.bottleneck(out)
|
||
|
||
for i in range(len(self.up_blocks)):
|
||
out = self.up_blocks[i](out)
|
||
|
||
out = self.final(out)
|
||
out = F.sigmoid(out)
|
||
|
||
output_dict["prediction"] = out
|
||
|
||
return output_dict
|
||
|
||
|
||
def load_checkpoints(config, checkpoint, blend_scale=0.125, first_order_motion_model=False, cpu=False):
|
||
with open(config) as f:
|
||
config = yaml.safe_load(f) #yaml.load(f) #
|
||
|
||
reconstruction_module = PartSwapGenerator(blend_scale=blend_scale,
|
||
first_order_motion_model=first_order_motion_model,
|
||
**config['model_params']['reconstruction_module_params'],
|
||
**config['model_params']['common_params'])
|
||
|
||
if not cpu:
|
||
reconstruction_module.cuda()
|
||
|
||
segmentation_module = SegmentationModule(**config['model_params']['segmentation_module_params'],
|
||
**config['model_params']['common_params'])
|
||
if not cpu:
|
||
segmentation_module.cuda()
|
||
|
||
if cpu:
|
||
checkpoint = torch.load(checkpoint, map_location=torch.device('cpu'))
|
||
else:
|
||
checkpoint = torch.load(checkpoint)
|
||
|
||
load_reconstruction_module(reconstruction_module, checkpoint)
|
||
load_segmentation_module(segmentation_module, checkpoint)
|
||
|
||
if not cpu:
|
||
reconstruction_module = DataParallelWithCallback(reconstruction_module)
|
||
segmentation_module = DataParallelWithCallback(segmentation_module)
|
||
|
||
reconstruction_module.eval()
|
||
segmentation_module.eval()
|
||
|
||
return reconstruction_module, segmentation_module
|
||
|
||
|
||
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
|
||
with torch.no_grad():
|
||
predictions = []
|
||
source = torch.tensor(source_image[np.newaxis].astype(np.float32)).permute(0, 3, 1, 2)
|
||
if not cpu:
|
||
source = source.cuda()
|
||
target = torch.tensor(np.array(target_video)[np.newaxis].astype(np.float32)).permute(0, 4, 1, 2, 3)
|
||
seg_source = segmentation_module(source)
|
||
|
||
for frame_idx in range(target.shape[2]): # tqdm(range(target.shape[2])):
|
||
target_frame = target[:, :, frame_idx]
|
||
if not cpu:
|
||
target_frame = target_frame.cuda()
|
||
|
||
seg_target = segmentation_module(target_frame)
|
||
|
||
# Computing blend mask
|
||
if face_parser is not None:
|
||
blend_mask = F.interpolate(source if use_source_segmentation else target_frame, size=(512, 512))
|
||
blend_mask = (blend_mask - face_parser.mean) / face_parser.std
|
||
blend_mask = torch.softmax(face_parser(blend_mask)[0], dim=1)
|
||
else:
|
||
blend_mask = seg_source['segmentation'] if use_source_segmentation else seg_target['segmentation']
|
||
|
||
blend_mask = blend_mask[:, swap_index].sum(dim=1, keepdim=True)
|
||
if hard:
|
||
blend_mask = (blend_mask > 0.5).type(blend_mask.type())
|
||
|
||
out = reconstruction_module(source, target_frame, seg_source=seg_source, seg_target=seg_target, blend_mask=blend_mask, use_source_segmentation=use_source_segmentation)
|
||
|
||
predictions.append(np.transpose(out['prediction'].data.cpu().numpy(), [0, 2, 3, 1])[0])
|
||
return predictions
|
||
|
||
#python face_obfuscator.py --config config/vox-256-sem-15segments.yaml --checkpoint stuff/vox-15segments.pth.tar --swap_index 2,3,9,11,15
|
||
def obfuscate(swap_index, source_image, target_image, reconstruction_module, segmentation_module):
|
||
original_shape = target_image.shape
|
||
model_output = img_as_ubyte(make_video(swap_index=swap_index,
|
||
source_image=source_image,
|
||
target_video=[resize(target_image, (256, 256))[..., :3]],
|
||
reconstruction_module=reconstruction_module,
|
||
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)
|
||
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)
|
||
|
||
output = cv2.seamlessClone(
|
||
rescaled,
|
||
target_image,
|
||
mask,
|
||
center,
|
||
cv2.NORMAL_CLONE)
|
||
|
||
return output
|
||
|
||
|
||
def binary_diff_map(img_a: np.ndarray,
|
||
img_b: np.ndarray,
|
||
thresh: int = 1) -> np.ndarray:
|
||
if img_a.shape != img_b.shape:
|
||
raise ValueError("Images must have the same shape")
|
||
|
||
# Work in grayscale – colour difference rarely adds useful information
|
||
gray_a = cv2.cvtColor(img_a, cv2.COLOR_BGR2GRAY) if img_a.ndim == 3 else img_a
|
||
gray_b = cv2.cvtColor(img_b, cv2.COLOR_BGR2GRAY) if img_b.ndim == 3 else img_b
|
||
|
||
# Absolute pixel-wise difference
|
||
diff = cv2.absdiff(gray_a, gray_b)
|
||
# Threshold to binary: 0 = same, 255 = changed
|
||
_, mask = cv2.threshold(diff, thresh, 255, cv2.THRESH_BINARY)
|
||
return mask
|
||
|
||
|
||
|
||
|
||
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=False)
|
||
|
||
def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray:
|
||
return obfuscate(swap_index=self.swap_indices,
|
||
source_image=self.fake_face,
|
||
target_image=face_roi_img_bgr,
|
||
reconstruction_module=self.reconstruction_module,
|
||
segmentation_module=self.segmentation_module)
|
||
|
||
|
||
|
||
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/"
|
||
|
||
@app.get("/init")
|
||
def init():
|
||
try:
|
||
print("initiating epic")
|
||
checkpoint_path = "stuff/vox-15segments.pth.tar"
|
||
config_path = "config/vox-256-sem-15segments.yaml"
|
||
fake_face_path = "stuff/fake_face.jpg"
|
||
global epic
|
||
epic = EPIC(checkpoint_path, config_path, fake_face_path)
|
||
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"), cv2.IMREAD_UNCHANGED)
|
||
if img is None:
|
||
raise HTTPException(500, f"cv2 failed to read image at {image_processing_path}")
|
||
global epic
|
||
obfuscated_img = epic.obfuscate(img)
|
||
cv2.imwrite(os.path.join(image_processing_path, "obfuscated_face.jpg"), obfuscated_img)
|
||
|
||
@app.get("/health")
|
||
def health(): return {"ok": True}
|
||
|
||
|
||
# def main_old():
|
||
# print("Running speed_evaluation")
|
||
# checkpoint = "stuff/vox-15segments.pth.tar"
|
||
# config = "config/vox-256-sem-15segments.yaml"
|
||
# fake_face = imageio.imread("stuff/fake_face.jpg")
|
||
# target_image_paths = os.listdir("stuff/speed_eval_images/")
|
||
# random.shuffle(target_image_paths)
|
||
# target_image_paths = [os.path.join("stuff/speed_eval_images/", path) for path in target_image_paths[:1000]]
|
||
# blend_scale = 1
|
||
# reconstruction_module, segmentation_module = load_checkpoints(config, checkpoint, blend_scale=blend_scale, cpu=True)
|
||
# avg_speed = measure_speed(fake_face, target_image_paths, reconstruction_module, segmentation_module)
|
||
# print(avg_speed)
|
||
# print("Done")
|
||
|
||
if __name__ == "__main__":
|
||
print("Starting from main")
|
||
# main()
|
||
# parser = ArgumentParser()
|
||
# parser.add_argument("--config", required=True, help="path to config")
|
||
# parser.add_argument("--checkpoint", default='vox-cpk.pth.tar', help="path to checkpoint to restore")
|
||
# parser.add_argument("--swap_index", default="1,2,5", type=lambda x: list(map(int, x.split(','))),
|
||
# help='index of swaped parts')
|
||
# parser.add_argument("--hard", action="store_true", help="use hard segmentation labels for blending")
|
||
# parser.add_argument("--use_source_segmentation", action="store_true", help="use source segmentation for swaping")
|
||
# parser.add_argument("--first_order_motion_model", action="store_true", help="use first order model for alignment")
|
||
# parser.add_argument("--supervised", action="store_true",
|
||
# help="use supervised segmentation labels for blending. Only for faces.")
|
||
# parser.add_argument("--cpu", action="store_true", help="cpu mode")
|
||
#
|
||
# opt = parser.parse_args()
|
||
#
|
||
# blend_scale = (256 / 4) / 512 if opt.supervised else 1
|
||
# swap_index = opt.swap_index
|
||
# hard = opt.hard
|
||
# cpu = opt.cpu
|
||
# use_source_segmentation = opt.use_source_segmentation
|
||
# if opt.supervised:
|
||
# face_parser = load_face_parser(opt.cpu)
|
||
# else:
|
||
# face_parser = None
|
||
#
|
||
# reconstruction_module, segmentation_module = load_checkpoints(opt.config, opt.checkpoint, blend_scale=blend_scale,
|
||
# first_order_motion_model=opt.first_order_motion_model,
|
||
# cpu=cpu)
|
||
# api.run()
|