98 lines
2.8 KiB
Python
98 lines
2.8 KiB
Python
from obfuscation.base_obfuscation_technique import ObfuscationTechnique
|
|
import numpy as np
|
|
import cv2
|
|
import time
|
|
|
|
class Blurring(ObfuscationTechnique):
|
|
"""
|
|
Gaussian-blur the face ROI, but only show the blurred pixels inside the mask.
|
|
"""
|
|
|
|
def __init__(self):
|
|
self.strength = 0.5 # 50% of smaller dim (w/h)
|
|
|
|
@staticmethod
|
|
def _calc_kernel(h, w, strength) -> int:
|
|
k = int(round(strength * min(h, w)))
|
|
k = k | 1 # make odd
|
|
k = max(3, k)
|
|
return k
|
|
|
|
def obfuscate(self, face_roi_img_bgr: np.ndarray, face_mask) -> np.ndarray:
|
|
# 1) copy original
|
|
obf = face_roi_img_bgr.copy()
|
|
# 2) compute full-image blur
|
|
h, w = face_roi_img_bgr.shape[:2]
|
|
k = self._calc_kernel(h, w, self.strength)
|
|
blurred = cv2.GaussianBlur(face_roi_img_bgr, ksize=(k, k), sigmaX=0, sigmaY=0)
|
|
# 3) blend only mask
|
|
obf[face_mask.astype(bool)] = blurred[face_mask.astype(bool)]
|
|
return obf
|
|
|
|
def name(self) -> str:
|
|
return "Blur"
|
|
|
|
def main():
|
|
import time # local import to keep module imports minimal
|
|
|
|
print("BLUR TEST RUN")
|
|
blurrer = Blurring()
|
|
print("INIT DONE")
|
|
|
|
face_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/test/face.png"
|
|
mask_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/test/mask.png"
|
|
|
|
face_roi = cv2.imread(face_path)
|
|
if face_roi is None:
|
|
raise FileNotFoundError(f"Could not load '{face_path}'")
|
|
|
|
# Load mask as grayscale (single channel)
|
|
mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
|
|
if mask is None:
|
|
raise FileNotFoundError(f"Could not load '{mask_path}'")
|
|
|
|
# Ensure mask matches ROI size
|
|
if mask.shape[:2] != face_roi.shape[:2]:
|
|
mask = cv2.resize(
|
|
mask,
|
|
(face_roi.shape[1], face_roi.shape[0]),
|
|
interpolation=cv2.INTER_NEAREST,
|
|
)
|
|
|
|
print("IMAGE & MASK LOADING DONE")
|
|
|
|
# --- Warm-up to avoid one-time costs skewing timings ---
|
|
n_times_warmup = 100
|
|
for n in range(n_times_warmup):
|
|
_ = blurrer.obfuscate(face_roi, mask)
|
|
|
|
# --- Timed runs ---
|
|
n_runs = 1000
|
|
times = []
|
|
|
|
for i in range(n_runs):
|
|
t0 = time.perf_counter()
|
|
obfuscated = blurrer.obfuscate(face_roi, mask)
|
|
t1 = time.perf_counter()
|
|
|
|
dt = t1 - t0
|
|
times.append(dt)
|
|
print(f"Run {i+1}/{n_runs}: {dt*1000:.2f} ms")
|
|
|
|
print(
|
|
"OBFUSCATION TIME — "
|
|
f"mean: {np.mean(times)*1000:.2f} ms, "
|
|
f"median: {np.median(times)*1000:.2f} ms, "
|
|
f"min: {np.min(times)*1000:.2f} ms, "
|
|
f"max: {np.max(times)*1000:.2f} ms"
|
|
)
|
|
|
|
# Save result from the last run
|
|
out_path = "blurred_face_roi.jpg"
|
|
cv2.imwrite(out_path, obfuscated)
|
|
print(f"SAVING DONE -> {out_path}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|