| from __future__ import annotations |
|
|
| import math |
|
|
| import cv2 |
| import numpy as np |
| from PIL import Image |
|
|
| from .image_preprocess import canonical_square, decode_rgb |
|
|
|
|
| FACTORS = ("line", "color", "texture", "geometry") |
| INTERVENTION_VERSION = "lens-safe-v4" |
| TRAIN_FAMILIES = { |
| "line": ("dilate_erode", "blur_sharpen", "darkness_contrast"), |
| "color": ("palette_remap", "split_tone", "tone_curve"), |
| "texture": ("smooth_detail", "frequency", "grain_noise"), |
| "geometry": ("crop_zoom_translate", "perspective", "lens_warp"), |
| } |
| VALIDATION_FAMILIES = { |
| "line": "edge_overlay", |
| "color": "channel_mixer", |
| "texture": "median_speckle", |
| "geometry": "shear", |
| } |
| LEVELS = {"weak": 0.50, "medium": 0.80, "strong": 1.0} |
|
|
|
|
| def _uint8(array: np.ndarray) -> np.ndarray: |
| return np.clip(array, 0, 255).astype(np.uint8) |
|
|
|
|
| def _edges(array: np.ndarray) -> np.ndarray: |
| gray = cv2.cvtColor(array, cv2.COLOR_RGB2GRAY) |
| return cv2.Canny(gray, 60, 150).astype(np.float32) / 255.0 |
|
|
|
|
| def _pixel_transform( |
| image: Image.Image, factor: str, family: str, signed: float, seed: int |
| ) -> Image.Image: |
| magnitude = abs(signed) |
| direction = 1 if signed >= 0 else -1 |
| array = np.asarray(image.convert("RGB"), dtype=np.uint8) |
|
|
| if factor == "line": |
| if family in {"dilate_erode", "edge_overlay"}: |
| edge = _edges(array) |
| kernel_size = 3 if magnitude <= 0.5 else 5 if magnitude < 1.0 else 7 |
| kernel = np.ones((kernel_size, kernel_size), np.uint8) |
| edge = cv2.dilate(edge, kernel) |
| if direction > 0: |
| alpha = (0.72 if family == "edge_overlay" else 0.64) * magnitude |
| result = array.astype(np.float32) * (1.0 - alpha * edge[..., None]) |
| else: |
| smooth = cv2.bilateralFilter(array, 11, 80, 9).astype(np.float32) |
| weight = np.clip(0.90 * magnitude * edge, 0.0, 0.90)[..., None] |
| result = array * (1.0 - weight) + smooth * weight |
| elif family == "blur_sharpen": |
| blurred = cv2.GaussianBlur(array, (0, 0), 1.2 + 2.4 * magnitude) |
| result = blurred if direction < 0 else cv2.addWeighted( |
| array, 1.0 + 1.45 * magnitude, blurred, -1.45 * magnitude, 0 |
| ) |
| elif family == "darkness_contrast": |
| edge = cv2.GaussianBlur(_edges(array), (0, 0), 1.0) |
| if direction > 0: |
| result = array.astype(np.float32) * (1.0 - 0.70 * magnitude * edge[..., None]) |
| else: |
| smooth = cv2.GaussianBlur(array, (0, 0), 2.6) |
| weight = np.clip(0.90 * magnitude * edge, 0.0, 0.90)[..., None] |
| result = array * (1.0 - weight) + smooth * weight |
| else: |
| raise ValueError(f"unknown line family: {family}") |
| return Image.fromarray(_uint8(result)) |
|
|
| if factor == "color": |
| unit = array.astype(np.float32) / 255.0 |
| if family == "palette_remap": |
| hsv = cv2.cvtColor(array, cv2.COLOR_RGB2HSV).astype(np.float32) |
| hsv[..., 0] = np.mod(hsv[..., 0] + direction * 30.0 * magnitude, 180.0) |
| saturation = 1.0 + 0.95 * magnitude if direction > 0 else 1.0 - 0.70 * magnitude |
| hsv[..., 1] *= saturation |
| hsv[..., 2] = 255.0 * np.power( |
| hsv[..., 2] / 255.0, math.exp(-direction * 0.38 * magnitude) |
| ) |
| result = cv2.cvtColor(_uint8(hsv), cv2.COLOR_HSV2RGB).astype(np.float32) |
| balance = direction * 0.16 * magnitude |
| result[..., 0] *= 1.0 + balance |
| result[..., 2] *= 1.0 - balance |
| elif family == "split_tone": |
| luminance = np.sum(unit * np.array([0.213, 0.715, 0.072], np.float32), axis=2) |
| shadows = np.power(1.0 - luminance, 1.4)[..., None] |
| highlights = np.power(luminance, 1.4)[..., None] |
| cool_shadow = np.array([-0.16, 0.02, 0.28], np.float32) |
| warm_highlight = np.array([0.30, 0.12, -0.14], np.float32) |
| result = unit + direction * magnitude * ( |
| shadows * cool_shadow + highlights * warm_highlight |
| ) |
| result = 0.5 + (result - 0.5) * (1.0 + 0.38 * magnitude) |
| result = _uint8(result * 255.0) |
| hsv = cv2.cvtColor(result, cv2.COLOR_RGB2HSV).astype(np.float32) |
| hsv[..., 0] = np.mod(hsv[..., 0] + direction * 12.0 * magnitude, 180.0) |
| hsv[..., 1] *= 1.0 + 0.40 * magnitude |
| result = cv2.cvtColor(_uint8(hsv), cv2.COLOR_HSV2RGB) |
| elif family == "tone_curve": |
| channel_gamma = np.exp( |
| direction * magnitude * np.array([-0.62, -0.18, 0.48], np.float32) |
| ) |
| result = np.power(np.clip(unit, 0.0, 1.0), channel_gamma) |
| contrast = 1.0 + direction * 0.48 * magnitude |
| result = 0.5 + (result - 0.5) * contrast |
| luminance = np.sum(result * np.array([0.213, 0.715, 0.072], np.float32), axis=2, keepdims=True) |
| result = luminance + (result - luminance) * (1.0 + 0.55 * magnitude) |
| result *= 1.0 + direction * 0.10 * magnitude |
| result = result * 255.0 |
| elif family == "channel_mixer": |
| delta = np.array( |
| [[0.22, 0.12, -0.20], [-0.12, 0.20, 0.08], [0.08, -0.20, 0.24]], |
| np.float32, |
| ) |
| matrix = np.eye(3, dtype=np.float32) + direction * magnitude * delta |
| result = unit @ matrix.T |
| result = np.power( |
| np.clip(result, 0.0, 1.0), math.exp(-direction * 0.45 * magnitude) |
| ) |
| result = 255.0 * result |
| else: |
| raise ValueError(f"unknown color family: {family}") |
| return Image.fromarray(_uint8(result)) |
|
|
| if factor == "texture": |
| result = array.astype(np.float32) |
| if family == "smooth_detail": |
| smooth = cv2.bilateralFilter(array, 13, 70 + 55 * magnitude, 11) |
| if direction < 0: |
| result = cv2.addWeighted(array, 1.0 - 0.85 * magnitude, smooth, 0.85 * magnitude, 0) |
| else: |
| result = array + (array.astype(np.float32) - smooth) * 1.35 * magnitude |
| elif family == "frequency": |
| low = cv2.GaussianBlur(array, (0, 0), 1.5 + 1.5 * magnitude) |
| high = array.astype(np.float32) - low.astype(np.float32) |
| result = array + direction * high * 1.55 * magnitude |
| elif family in {"grain_noise", "median_speckle"}: |
| if direction < 0: |
| kernel = 5 if magnitude >= 0.8 else 3 |
| median = cv2.medianBlur(array, kernel) |
| result = cv2.addWeighted(array, 1.0 - 0.85 * magnitude, median, 0.85 * magnitude, 0) |
| else: |
| rng = np.random.default_rng(seed) |
| noise = rng.normal(0, 26.0 * magnitude, array.shape[:2]).astype(np.float32) |
| noise = cv2.GaussianBlur(noise, (0, 0), 0.35)[..., None] |
| result = array.astype(np.float32) + noise |
| else: |
| raise ValueError(f"unknown texture family: {family}") |
| return Image.fromarray(_uint8(result)) |
|
|
| raise ValueError(f"pixel transform does not support factor: {factor}") |
|
|
|
|
| def _apply_homography( |
| image: Image.Image, matrix: np.ndarray |
| ) -> tuple[Image.Image, callable]: |
| array = np.asarray(image) |
| height, width = array.shape[:2] |
| warped = cv2.warpPerspective( |
| array, matrix, (width, height), flags=cv2.INTER_LANCZOS4, borderMode=cv2.BORDER_REFLECT_101 |
| ) |
|
|
| def map_points(points: np.ndarray) -> np.ndarray: |
| return cv2.perspectiveTransform(points.astype(np.float32)[None], matrix)[0] |
|
|
| return Image.fromarray(warped), map_points |
|
|
|
|
| def _geometry_transform( |
| image: Image.Image, family: str, signed: float, seed: int |
| ) -> tuple[Image.Image, callable]: |
| magnitude = abs(signed) |
| direction = 1 if signed >= 0 else -1 |
| width, height = image.size |
| center = np.array([width / 2, height / 2], dtype=np.float32) |
|
|
| if family == "crop_zoom_translate": |
| rng = np.random.default_rng(seed) |
| scale = 1.0 + direction * 0.20 * magnitude |
| shift = np.array( |
| [direction * 0.10 * width, (1 if rng.integers(2) else -1) * 0.07 * height], |
| dtype=np.float32, |
| ) * magnitude |
| matrix = np.array( |
| [[scale, 0, center[0] * (1 - scale) + shift[0]], [0, scale, center[1] * (1 - scale) + shift[1]], [0, 0, 1]], |
| dtype=np.float32, |
| ) |
| return _apply_homography(image, matrix) |
|
|
| if family in {"perspective", "shear"}: |
| source = np.array([[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]], np.float32) |
| if family == "perspective": |
| delta = direction * 0.15 * width * magnitude |
| target = source + np.array([[delta, 0], [-delta, delta * 0.35], [delta, 0], [-delta, -delta * 0.35]], np.float32) |
| else: |
| delta = direction * 0.18 * width * magnitude |
| target = source + np.array([[delta, 0], [delta, 0], [-delta, 0], [-delta, 0]], np.float32) |
| return _apply_homography(image, cv2.getPerspectiveTransform(source, target)) |
|
|
| if family == "lens_warp": |
| |
| radial_strength = float( |
| np.interp(magnitude, [0.5, 0.8, 1.0], [0.035, 0.055, 0.075]) |
| ) |
| k = direction * radial_strength |
| yy, xx = np.indices((height, width), dtype=np.float32) |
| xd = (xx - center[0]) / (width / 2) |
| yd = (yy - center[1]) / (height / 2) |
| xs, ys = xd.copy(), yd.copy() |
| for _ in range(4): |
| radius2 = xs * xs + ys * ys |
| factor = 1.0 + k * radius2 |
| xs, ys = xd / factor, yd / factor |
| map_x = xs * (width / 2) + center[0] |
| map_y = ys * (height / 2) + center[1] |
| warped = cv2.remap( |
| np.asarray(image), map_x, map_y, cv2.INTER_LANCZOS4, borderMode=cv2.BORDER_REFLECT_101 |
| ) |
|
|
| def map_points(points: np.ndarray) -> np.ndarray: |
| normalized = (points - center) / np.array([width / 2, height / 2]) |
| radius2 = np.square(normalized).sum(axis=1, keepdims=True) |
| return center + normalized * (1.0 + k * radius2) * np.array([width / 2, height / 2]) |
|
|
| return Image.fromarray(warped), map_points |
|
|
| raise ValueError(f"unknown geometry family: {family}") |
|
|
|
|
| def _face_box_in_square(metadata: dict, crop_box: tuple[int, int, int, int], size: int) -> np.ndarray | None: |
| box = (metadata.get("face_detection") or {}).get("primary_box") |
| if box is None: |
| return None |
| left, top, right, bottom = crop_box |
| scale_x = size / (right - left) |
| scale_y = size / (bottom - top) |
| x0, y0, x1, y1 = map(float, box) |
| return np.array( |
| [[(x0 - left) * scale_x, (y0 - top) * scale_y], [(x1 - left) * scale_x, (y0 - top) * scale_y], [(x1 - left) * scale_x, (y1 - top) * scale_y], [(x0 - left) * scale_x, (y1 - top) * scale_y]], |
| dtype=np.float32, |
| ) |
|
|
|
|
| def _crop_face(image: Image.Image, points: np.ndarray, size: int, padding: float = 0.25) -> Image.Image: |
| x0, y0 = points.min(axis=0) |
| x1, y1 = points.max(axis=0) |
| if x1 <= 0 or y1 <= 0 or x0 >= image.width or y0 >= image.height: |
| raise ValueError("transformed face left the image") |
| side = max(x1 - x0, y1 - y0) * (1 + 2 * padding) |
| if side < 8: |
| raise ValueError("transformed face is too small") |
| cx, cy = (x0 + x1) / 2, (y0 + y1) / 2 |
| box = (max(0, cx - side / 2), max(0, cy - side / 2), min(image.width, cx + side / 2), min(image.height, cy + side / 2)) |
| crop = image.crop(tuple(map(int, map(round, box)))) |
| if min(crop.size) < 4: |
| raise ValueError("invalid transformed face crop") |
| return crop.resize((size, size), Image.Resampling.LANCZOS) |
|
|
|
|
| def apply_intervention( |
| full_bytes: bytes, |
| face_bytes: bytes | None, |
| metadata: dict, |
| spec: dict, |
| *, |
| size: int = 512, |
| ) -> tuple[Image.Image, Image.Image | None]: |
| full, crop_box = canonical_square(decode_rgb(full_bytes), size) |
| signed = float(spec["signed_intensity"]) |
| seed = int(spec["operation_seed"]) |
| factor = str(spec["factor"]) |
| family = str(spec["family"]) |
|
|
| if factor == "geometry": |
| transformed, map_points = _geometry_transform(full, family, signed, seed) |
| points = _face_box_in_square(metadata, crop_box, size) |
| face = None |
| if points is not None: |
| try: |
| face = _crop_face(transformed, map_points(points), size) |
| except ValueError: |
| face = None |
| if face is None and face_bytes is not None: |
| face_source, _ = canonical_square(decode_rgb(face_bytes), size) |
| face, _ = _geometry_transform(face_source, family, signed, seed ^ 0x5A17) |
| return transformed, face |
|
|
| transformed = _pixel_transform(full, factor, family, signed, seed) |
| face = None |
| if face_bytes is not None: |
| face, _ = canonical_square(decode_rgb(face_bytes), size) |
| face = _pixel_transform(face, factor, family, signed, seed ^ 0x5A17) |
| return transformed, face |
|
|