├── .gitignore ├── Thumbs.db ├── image_postprocess ├── __init__.py ├── utils │ ├── exif.py │ ├── gaussian_noise.py │ ├── perturbation.py │ ├── __init__.py │ ├── autowb.py │ ├── clahe.py │ ├── non_semantic_unmarker.py │ ├── lbp_normalization.py │ ├── glcm_normalization.py │ ├── fourier_pipeline.py │ ├── fourier_pipeline_new_algo.py │ ├── blend.py │ └── color_lut.py ├── camera_pipeline.py └── processor.py ├── __init__.py ├── ui_utils ├── __init__.py ├── worker.py ├── collapsible_box.py ├── theme.py ├── analysis_panel.py └── main_window.py ├── nodes_utils ├── __init__.py ├── ns_opt.py └── cam_opt.py ├── run.sh ├── requirements.txt ├── run.py ├── config.ini ├── utils.py ├── README.md ├── nodes.py └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | .vscode/ -------------------------------------------------------------------------------- /Thumbs.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PurinNyova/Image-Detection-Bypass-Utility/HEAD/Thumbs.db -------------------------------------------------------------------------------- /image_postprocess/__init__.py: -------------------------------------------------------------------------------- 1 | from .processor import process_image 2 | 3 | __all__ = ['process_image'] -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS 2 | 3 | __all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS'] -------------------------------------------------------------------------------- /ui_utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .main_window import MainWindow 2 | from .theme import apply_dark_palette 3 | 4 | __all__ = ['MainWindow', 'apply_dark_palette'] -------------------------------------------------------------------------------- /nodes_utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .cam_opt import CameraOptionsNode 2 | from .ns_opt import NSOptionsNode 3 | 4 | __all__ = [ 5 | "CameraOptionsNode", 6 | "NSOptionsNode", 7 | ] -------------------------------------------------------------------------------- /image_postprocess/utils/exif.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | 3 | def remove_exif_pil(img: Image.Image) -> Image.Image: 4 | data = img.tobytes() 5 | new = Image.frombytes(img.mode, img.size, data) 6 | return new -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | pip install pyqt5 pillow numpy matplotlib piexif lpips 3 | pip install torch torchvision --index-url https://download.pytorch.org/whl/cu126 4 | pip install torch torchvision 5 | pip install scikit-image 6 | python run.py 7 | 8 | 9 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | scikit-image 2 | pyqt5 3 | pillow 4 | numpy 5 | matplotlib 6 | scikit-image 7 | piexif 8 | opencv-python 9 | --extra-index-url https://download.pytorch.org/whl/cu126 10 | torch==2.8.0+cu126 11 | torchvision==0.23.0+cu126 12 | scipy 13 | lpips 14 | -------------------------------------------------------------------------------- /image_postprocess/utils/gaussian_noise.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def add_gaussian_noise(img_arr: np.ndarray, std_frac=0.02, seed=None) -> np.ndarray: 4 | if seed is not None: 5 | np.random.seed(seed) 6 | std = std_frac * 255.0 7 | noise = np.random.normal(loc=0.0, scale=std, size=img_arr.shape) 8 | out = img_arr.astype(np.float32) + noise 9 | out = np.clip(out, 0, 255).astype(np.uint8) 10 | return out -------------------------------------------------------------------------------- /image_postprocess/utils/perturbation.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def randomized_perturbation(img_arr: np.ndarray, magnitude_frac=0.008, seed=None) -> np.ndarray: 4 | if seed is not None: 5 | np.random.seed(seed) 6 | mag = magnitude_frac * 255.0 7 | perturb = np.random.uniform(low=-mag, high=mag, size=img_arr.shape) 8 | out = img_arr.astype(np.float32) + perturb 9 | out = np.clip(out, 0, 255).astype(np.uint8) 10 | return out -------------------------------------------------------------------------------- /image_postprocess/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .autowb import auto_white_balance_ref 2 | from .clahe import clahe_color_correction 3 | from .color_lut import load_lut, apply_lut 4 | from .exif import remove_exif_pil 5 | from .fourier_pipeline import fourier_match_spectrum 6 | from .gaussian_noise import add_gaussian_noise 7 | from .perturbation import randomized_perturbation 8 | from .glcm_normalization import glcm_normalize 9 | from .lbp_normalization import lbp_normalize 10 | from .non_semantic_unmarker import attack_non_semantic 11 | from .blend import blend_colors 12 | 13 | __all__ = [ 14 | 'auto_white_balance_ref', 15 | 'clahe_color_correction', 16 | 'load_lut', 17 | 'apply_lut', 18 | 'remove_exif_pil', 19 | 'fourier_match_spectrum', 20 | 'add_gaussian_noise', 21 | 'randomized_perturbation', 22 | 'glcm_normalize', 23 | 'lbp_normalize', 24 | 'attack_non_semantic', 25 | 'blend_colors', 26 | ] -------------------------------------------------------------------------------- /image_postprocess/utils/autowb.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def auto_white_balance_ref(img_arr: np.ndarray, ref_img_arr: np.ndarray = None) -> np.ndarray: 4 | """ 5 | Auto white-balance correction using a reference image. 6 | If ref_img_arr is None, uses a gray-world assumption instead. 7 | """ 8 | img = img_arr.astype(np.float32) 9 | 10 | if ref_img_arr is not None: 11 | ref = ref_img_arr.astype(np.float32) 12 | ref_mean = ref.reshape(-1, 3).mean(axis=0) 13 | else: 14 | # Gray-world assumption: target is neutral gray 15 | ref_mean = np.array([128.0, 128.0, 128.0], dtype=np.float32) 16 | 17 | img_mean = img.reshape(-1, 3).mean(axis=0) 18 | 19 | # Avoid divide-by-zero 20 | eps = 1e-6 21 | scale = (ref_mean + eps) / (img_mean + eps) 22 | 23 | corrected = img * scale 24 | corrected = np.clip(corrected, 0, 255).astype(np.uint8) 25 | 26 | return corrected -------------------------------------------------------------------------------- /image_postprocess/utils/clahe.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from PIL import Image, ImageOps 3 | 4 | try: 5 | import cv2 6 | _HAS_CV2 = True 7 | except Exception: 8 | cv2 = None 9 | _HAS_CV2 = False 10 | 11 | def clahe_color_correction(img_arr: np.ndarray, clip_limit=2.0, tile_grid_size=(8,8)) -> np.ndarray: 12 | if _HAS_CV2: 13 | lab = cv2.cvtColor(img_arr, cv2.COLOR_RGB2LAB) 14 | l, a, b = cv2.split(lab) 15 | clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=tile_grid_size) 16 | l2 = clahe.apply(l) 17 | lab2 = cv2.merge((l2, a, b)) 18 | out = cv2.cvtColor(lab2, cv2.COLOR_LAB2RGB) 19 | return out 20 | else: 21 | pil = Image.fromarray(img_arr) 22 | channels = pil.split() 23 | new_ch = [] 24 | for ch in channels: 25 | eq = ImageOps.equalize(ch) 26 | new_ch.append(eq) 27 | merged = Image.merge('RGB', new_ch) 28 | return np.array(merged) -------------------------------------------------------------------------------- /run.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Entry point for Image Postprocess GUI (camera simulator). 4 | Handles the import check for image_postprocess and launches the MainWindow. 5 | """ 6 | 7 | import sys 8 | from pathlib import Path 9 | from PyQt5.QtWidgets import QApplication, QMessageBox 10 | 11 | try: 12 | from image_postprocess import process_image 13 | except Exception as e: 14 | IMPORT_ERROR = str(e) 15 | else: 16 | IMPORT_ERROR = None 17 | 18 | from ui_utils import MainWindow, apply_dark_palette 19 | 20 | def main(): 21 | app = QApplication([]) 22 | apply_dark_palette(app) 23 | 24 | if IMPORT_ERROR: 25 | msg = QMessageBox(QMessageBox.Critical, "Import error", 26 | "Could not import image_postprocess module:\n" + IMPORT_ERROR) 27 | msg.setStyleSheet("QLabel{ color: black; } QPushButton{ color: black; }") 28 | msg.exec_() 29 | 30 | w = MainWindow() 31 | w.show() 32 | sys.exit(app.exec_()) 33 | 34 | if __name__ == '__main__': 35 | main() 36 | -------------------------------------------------------------------------------- /ui_utils/worker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Worker thread for image processing. 4 | """ 5 | 6 | from PyQt5.QtCore import QThread, pyqtSignal 7 | import traceback 8 | 9 | try: 10 | from image_postprocess import process_image 11 | except Exception: 12 | process_image = None 13 | IMPORT_ERROR = "Could not import process_image module" 14 | else: 15 | IMPORT_ERROR = None 16 | 17 | class Worker(QThread): 18 | finished = pyqtSignal(str) 19 | error = pyqtSignal(str, str) # error message + traceback 20 | 21 | def __init__(self, inpath, outpath, args): 22 | super().__init__() 23 | self.inpath = inpath 24 | self.outpath = outpath 25 | self.args = args 26 | 27 | def run(self): 28 | try: 29 | if process_image is None: 30 | raise RuntimeError("Could not import process_image: " + (IMPORT_ERROR or "unknown")) 31 | process_image(self.inpath, self.outpath, self.args) 32 | self.finished.emit(self.outpath) 33 | except Exception as e: 34 | tb = traceback.format_exc() 35 | self.error.emit(str(e), tb) -------------------------------------------------------------------------------- /ui_utils/collapsible_box.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import QWidget, QToolButton, QVBoxLayout 2 | from PyQt5.QtCore import Qt 3 | 4 | class CollapsibleBox(QWidget): 5 | """A simple collapsible container widget with a chevron arrow.""" 6 | def __init__(self, title: str = "", parent=None): 7 | super().__init__(parent) 8 | self.toggle = QToolButton(text=title, checkable=True, checked=True) 9 | self.toggle.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) 10 | self.toggle.setArrowType(Qt.DownArrow) 11 | self.toggle.clicked.connect(self.on_toggled) 12 | self.toggle.setStyleSheet("QToolButton { border: none; font-weight:600; padding:6px; }") 13 | 14 | self.content = QWidget() 15 | self.content_layout = QVBoxLayout() 16 | self.content_layout.setContentsMargins(8, 4, 8, 8) 17 | self.content.setLayout(self.content_layout) 18 | 19 | lay = QVBoxLayout(self) 20 | lay.setSpacing(0) 21 | lay.setContentsMargins(0, 0, 0, 0) 22 | lay.addWidget(self.toggle) 23 | lay.addWidget(self.content) 24 | 25 | def on_toggled(self): 26 | checked = self.toggle.isChecked() 27 | self.toggle.setArrowType(Qt.DownArrow if checked else Qt.RightArrow) 28 | self.content.setVisible(checked) -------------------------------------------------------------------------------- /config.ini: -------------------------------------------------------------------------------- 1 | [General] 2 | auto_mode = false 3 | 4 | [AutoMode] 5 | strength = 25 6 | 7 | [Blend] 8 | enabled = true 9 | tolerance = 2 10 | min_region = 5 11 | max_samples = 100000 12 | n_jobs = 4 13 | 14 | [AINormalizer] 15 | enabled = true 16 | iterations = 500 17 | learning_rate = 0.0002 18 | t_lpips = 0.0404 19 | t_l2 = 0.00001 20 | c_lpips = 0.01 21 | c_l2 = 1.0 22 | grad_clip = 0.05 23 | 24 | [ManualParameters] 25 | noise_enable = false 26 | clahe_enable = false 27 | fft_enable = true 28 | perturb_enable = true 29 | noise_std = 0.02 30 | clahe_clip = 1.0 31 | tile = 4 32 | cutoff = 0.6 33 | fstrength = 0.8 34 | randomness = 0.07 35 | phase_perturb = 0.1 36 | radial_smooth = 2 37 | fft_mode = auto 38 | fft_alpha = 1.0 39 | perturb = 0.01 40 | seed = 1 41 | 42 | [AWB] 43 | enabled = false 44 | 45 | [CameraSimulator] 46 | enabled = true 47 | bayer = true 48 | jpeg_cycles = 4 49 | jpeg_qmin = 43 50 | jpeg_qmax = 75 51 | vignette_strength = 0.1 52 | chroma_strength = 1.0 53 | iso_scale = 1.0 54 | read_noise = 2.0 55 | hot_pixel_prob = 0.000001 56 | banding_strength = 0.0 57 | motion_blur_kernel = 2 58 | 59 | [LUT] 60 | enabled = false 61 | file = 62 | strength = 1.0 63 | 64 | [TextureNormalization] 65 | glcm_enabled = false 66 | glcm_distances = 1 67 | glcm_angles = 0 0.785 1.571 2.356 68 | glcm_levels = 256 69 | glcm_strength = 0.4 70 | lbp_enabled = false 71 | lbp_radius = 3 72 | lbp_n_points = 24 73 | lbp_method = uniform 74 | lbp_strength = 0.9 -------------------------------------------------------------------------------- /ui_utils/theme.py: -------------------------------------------------------------------------------- 1 | from PyQt5.QtWidgets import QApplication 2 | from PyQt5.QtGui import QPalette, QColor 3 | 4 | def apply_dark_palette(app: QApplication): 5 | pal = QPalette() 6 | # base 7 | pal.setColor(QPalette.Window, QColor(18, 18, 19)) 8 | pal.setColor(QPalette.WindowText, QColor(220, 220, 220)) 9 | pal.setColor(QPalette.Base, QColor(28, 28, 30)) 10 | pal.setColor(QPalette.AlternateBase, QColor(24, 24, 26)) 11 | pal.setColor(QPalette.ToolTipBase, QColor(220, 220, 220)) 12 | pal.setColor(QPalette.ToolTipText, QColor(220, 220, 220)) 13 | pal.setColor(QPalette.Text, QColor(230, 230, 230)) 14 | pal.setColor(QPalette.Button, QColor(40, 40, 42)) 15 | pal.setColor(QPalette.ButtonText, QColor(230, 230, 230)) 16 | pal.setColor(QPalette.Highlight, QColor(70, 130, 180)) 17 | pal.setColor(QPalette.HighlightedText, QColor(255, 255, 255)) 18 | app.setPalette(pal) 19 | 20 | # global stylesheet for a modern gray look 21 | app.setStyleSheet(r""" 22 | QWidget { font-family: 'Segoe UI', Roboto, Arial, sans-serif; font-size:11pt } 23 | QToolButton { padding:6px; } 24 | QLineEdit, QSpinBox, QDoubleSpinBox, QComboBox { background: #1e1e1f; border: 1px solid #333; padding:4px; border-radius:6px } 25 | QPushButton { background: #2a2a2c; border: 1px solid #3a3a3c; padding:6px 10px; border-radius:8px } 26 | QPushButton:hover { background: #333336 } 27 | QPushButton:pressed { background: #232325 } 28 | QProgressBar { background: #222; border: 1px solid #333; border-radius:6px; text-align:center } 29 | QProgressBar::chunk { background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #4b9bd6, stop:1 #3b83c0); } 30 | QLabel { color: #ffffff } 31 | QCheckBox { padding:4px } 32 | QGroupBox { color : #e6e6e6; } 33 | QGroupBox:title { color : #e6e6e6; } 34 | """) -------------------------------------------------------------------------------- /nodes_utils/ns_opt.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | class NSOptionsNode: 4 | """ 5 | Node that encapsulates non-semantic attack parameters. Returns a JSON string 6 | that can be connected to the main NovaNodes node's "NS_Opt" input. 7 | """ 8 | 9 | @classmethod 10 | def INPUT_TYPES(s): 11 | return { 12 | "required": { 13 | "non_semantic": ("BOOLEAN", {"default": False}), 14 | "ns_iterations": ("INT", {"default": 500, "min": 1, "max": 10000, "step": 1}), 15 | "ns_learning_rate": ("FLOAT", {"default": 3e-4, "min": 1e-6, "max": 1.0, "step": 1e-6}), 16 | "ns_t_lpips": ("FLOAT", {"default": 4e-2, "min": 0.0, "max": 1.0, "step": 1e-4}), 17 | "ns_t_l2": ("FLOAT", {"default": 3e-5, "min": 0.0, "max": 1.0, "step": 1e-6}), 18 | "ns_c_lpips": ("FLOAT", {"default": 1e-2, "min": 0.0, "max": 1.0, "step": 1e-4}), 19 | "ns_c_l2": ("FLOAT", {"default": 0.6, "min": 0.0, "max": 10.0, "step": 1e-3}), 20 | "ns_grad_clip": ("FLOAT", {"default": 0.05, "min": 0.0, "max": 1.0, "step": 1e-4}), 21 | } 22 | } 23 | 24 | RETURN_TYPES = ("NONSEMANTICOP",) 25 | RETURN_NAMES = ("NS_OPT",) 26 | FUNCTION = "get_ns_opts" 27 | CATEGORY = "postprocessing" 28 | 29 | def get_ns_opts(self, 30 | non_semantic=False, 31 | ns_iterations=500, 32 | ns_learning_rate=3e-4, 33 | ns_t_lpips=4e-2, 34 | ns_t_l2=3e-5, 35 | ns_c_lpips=1e-2, 36 | ns_c_l2=0.6, 37 | ns_grad_clip=0.05, 38 | ): 39 | ns_opts = { 40 | "non_semantic": bool(non_semantic), 41 | "ns_iterations": int(ns_iterations), 42 | "ns_learning_rate": float(ns_learning_rate), 43 | "ns_t_lpips": float(ns_t_lpips), 44 | "ns_t_l2": float(ns_t_l2), 45 | "ns_c_lpips": float(ns_c_lpips), 46 | "ns_c_l2": float(ns_c_l2), 47 | "ns_grad_clip": float(ns_grad_clip), 48 | } 49 | return (json.dumps(ns_opts),) 50 | -------------------------------------------------------------------------------- /nodes_utils/cam_opt.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | class CameraOptionsNode: 4 | """ 5 | Node that encapsulates camera simulation / JPEG / vignette / chromatic aberration / noise 6 | settings. Returns a JSON string that can be connected to the main NovaNodes node's "Cam_Opt" input. 7 | """ 8 | 9 | @classmethod 10 | def INPUT_TYPES(s): 11 | return { 12 | "required": { 13 | "enable_bayer": ("BOOLEAN", {"default": True}), 14 | "apply_jpeg_cycles_o": ("BOOLEAN", {"default": True}), 15 | "jpeg_cycles": ("INT", {"default": 1, "min": 1, "max": 10, "step": 1}), 16 | "jpeg_quality": ("INT", {"default": 88, "min": 10, "max": 100, "step": 1}), 17 | "jpeg_qmax": ("INT", {"default": 96, "min": 10, "max": 100, "step": 1}), 18 | "apply_vignette_o": ("BOOLEAN", {"default": True}), 19 | "vignette_strength": ("FLOAT", {"default": 0.35, "min": 0.0, "max": 1.0, "step": 0.01}), 20 | "apply_chromatic_aberration_o": ("BOOLEAN", {"default": True}), 21 | "ca_shift": ("FLOAT", {"default": 1.20, "min": 0.0, "max": 5.0, "step": 0.1}), 22 | "iso_scale": ("FLOAT", {"default": 1.00, "min": 0.1, "max": 16.0, "step": 0.1}), 23 | "read_noise": ("FLOAT", {"default": 2.00, "min": 0.0, "max": 50.0, "step": 0.1}), 24 | "hot_pixel_prob": ("FLOAT", {"default": 1e-7, "min": 0.0, "max": 1e-3, "step": 1e-7}), 25 | "apply_banding_o": ("BOOLEAN", {"default": True}), 26 | "banding_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}), 27 | "apply_motion_blur_o": ("BOOLEAN", {"default": True}), 28 | "motion_blur_ksize": ("INT", {"default": 1, "min": 1, "max": 31, "step": 2}), 29 | } 30 | } 31 | 32 | RETURN_TYPES = ("CAMERAOPT",) 33 | RETURN_NAMES = ("CAM_OPT",) 34 | FUNCTION = "get_cam_opts" 35 | CATEGORY = "postprocessing" 36 | 37 | def get_cam_opts(self, 38 | enable_bayer=True, 39 | apply_jpeg_cycles_o=True, 40 | jpeg_cycles=1, 41 | jpeg_quality=88, 42 | jpeg_qmax=96, 43 | apply_vignette_o=True, 44 | vignette_strength=0.35, 45 | apply_chromatic_aberration_o=True, 46 | ca_shift=1.20, 47 | iso_scale=1.0, 48 | read_noise=2.0, 49 | hot_pixel_prob=1e-7, 50 | apply_banding_o=True, 51 | banding_strength=0.0, 52 | apply_motion_blur_o=True, 53 | motion_blur_ksize=1, 54 | ): 55 | cam_opts = { 56 | "enable_bayer": bool(enable_bayer), 57 | "apply_jpeg_cycles_o": bool(apply_jpeg_cycles_o), 58 | "jpeg_cycles": int(jpeg_cycles), 59 | "jpeg_quality": int(jpeg_quality), 60 | "jpeg_qmax": int(jpeg_qmax), 61 | "apply_vignette_o": bool(apply_vignette_o), 62 | "vignette_strength": float(vignette_strength), 63 | "apply_chromatic_aberration_o": bool(apply_chromatic_aberration_o), 64 | "ca_shift": float(ca_shift), 65 | "iso_scale": float(iso_scale), 66 | "read_noise": float(read_noise), 67 | "hot_pixel_prob": float(hot_pixel_prob), 68 | "apply_banding_o": bool(apply_banding_o), 69 | "banding_strength": float(banding_strength), 70 | "apply_motion_blur_o": bool(apply_motion_blur_o), 71 | "motion_blur_ksize": int(motion_blur_ksize), 72 | } 73 | return (json.dumps(cam_opts),) 74 | -------------------------------------------------------------------------------- /image_postprocess/utils/non_semantic_unmarker.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.optim as optim 3 | import lpips 4 | import torchvision.transforms as transforms 5 | import numpy as np 6 | 7 | def attack_non_semantic(img_arr: np.ndarray, 8 | iterations: int = 500, 9 | learning_rate: float = 3e-4, 10 | t_lpips: float = 4e-2, 11 | t_l2: float = 3e-5, 12 | c_lpips: float = 1e-2, 13 | c_l2: float = 0.6, 14 | grad_clip_value: float = 0.05 15 | ) -> np.ndarray: 16 | """ 17 | Implements the non-semantic attack from the UnMarker paper using numpy input/output. 18 | 19 | Args: 20 | img_arr: Input image as a numpy array (H, W, 3) in range [0, 255]. 21 | iterations: Number of optimization iterations. 22 | learning_rate: Learning rate for the optimizer. 23 | t_lpips: Threshold for LPIPS loss. 24 | t_l2: Threshold for L2 loss. 25 | c_lpips: LPIPS loss weight constant. 26 | c_l2: L2 loss weight constant. 27 | grad_clip_value: Gradient clipping value. 28 | 29 | Returns: 30 | Attacked image as a numpy array (H, W, 3) in range [0, 255]. 31 | """ 32 | # Build configuration dictionary from parameters 33 | config = { 34 | 'iterations': iterations, 35 | 'learning_rate': learning_rate, 36 | 't_lpips': t_lpips, 37 | 't_l2': t_l2, 38 | 'c_lpips': c_lpips, 39 | 'c_l2': c_l2, 40 | 'grad_clip_value': grad_clip_value 41 | } 42 | 43 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 44 | 45 | # Preprocess: Convert numpy array to tensor and normalize to [-1, 1] 46 | transform = transforms.Compose([ 47 | transforms.ToTensor(), 48 | transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) 49 | ]) 50 | img_tensor = transform(img_arr).unsqueeze(0).to(device) 51 | 52 | # Initialize perturbation 53 | delta = (torch.randn_like(img_tensor) * 1e-5).requires_grad_(True).to(device) 54 | 55 | # Setup optimizer and LPIPS model 56 | optimizer = optim.Adam([delta], lr=config['learning_rate']) 57 | lpips_model = lpips.LPIPS(net='alex').to(device) 58 | 59 | # Precompute FFT of input image 60 | img_fft = torch.fft.fft2(img_tensor) 61 | 62 | # Optimization loop 63 | for i in range(config['iterations']): 64 | optimizer.zero_grad() 65 | 66 | # Perturbed image 67 | x_nw = img_tensor + delta 68 | x_nw = torch.clamp(x_nw, -1, 1) 69 | 70 | # Spectral Loss (DFL) 71 | x_nw_fft = torch.fft.fft2(x_nw) 72 | loss_dfl = -torch.abs(x_nw_fft - img_fft).sum() 73 | 74 | # Perceptual Loss (LPIPS) 75 | loss_lpips = lpips_model(x_nw, img_tensor).mean() 76 | 77 | # Geometric Loss (L2 Norm) 78 | loss_l2 = torch.linalg.norm(delta) 79 | 80 | # Combine losses 81 | lpips_penalty = config['c_lpips'] * torch.relu(loss_lpips - config['t_lpips']) 82 | l2_penalty = config['c_l2'] * torch.relu(loss_l2 - config['t_l2']) 83 | total_loss = loss_dfl + lpips_penalty + l2_penalty 84 | 85 | # Backpropagation 86 | total_loss.backward() 87 | 88 | # Gradient clipping 89 | if delta.grad is not None: 90 | delta.grad.data.clamp_(-config['grad_clip_value'], config['grad_clip_value']) 91 | 92 | optimizer.step() 93 | 94 | # Postprocess: Convert back to numpy array 95 | final_x_nw = torch.clamp(img_tensor + delta, -1, 1) 96 | final_x_nw = final_x_nw.squeeze(0).cpu().detach() 97 | final_x_nw = (final_x_nw + 1) / 2 # Denormalize to [0, 1] 98 | final_x_nw = final_x_nw.permute(1, 2, 0) # (C, H, W) to (H, W, C) 99 | final_x_nw = final_x_nw.clamp(0, 1) * 255 # Scale to [0, 255] 100 | result = final_x_nw.numpy().astype(np.uint8) 101 | 102 | return result -------------------------------------------------------------------------------- /image_postprocess/utils/lbp_normalization.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from skimage.feature import local_binary_pattern 3 | from PIL import Image 4 | 5 | def lbp_normalize(img_arr: np.ndarray, 6 | ref_img_arr: np.ndarray = None, 7 | radius: int = 3, 8 | n_points: int = 24, 9 | method: str = 'uniform', 10 | strength: float = 0.9, 11 | seed: int = None, 12 | eps: float = 1e-8): 13 | """ 14 | Optimized LBP histogram normalization. 15 | 16 | Key optimizations: 17 | - compute LBP and its histogram once (not per channel) 18 | - use np.bincount (faster) instead of np.histogram for integer LBP 19 | - compute mapping & per-bin operations once, then apply vectorized indexing 20 | - generate noise once for all channels 21 | - fewer temporaries, consistent dtypes 22 | """ 23 | if seed is not None: 24 | rng = np.random.default_rng(seed) 25 | else: 26 | rng = np.random.default_rng() 27 | 28 | img = np.asarray(img_arr) 29 | h, w = img.shape[:2] 30 | n_bins = n_points + 2 if method == 'uniform' else 2 ** n_points 31 | 32 | # Grayscale conversion (float32) 33 | img_gray = np.mean(img.astype(np.float32), axis=2) if img.ndim == 3 else img.astype(np.float32) 34 | 35 | # Compute LBP for input (float or int result) 36 | lbp_img = local_binary_pattern(img_gray, n_points, radius, method=method) 37 | # Convert LBP to integer indices for bincount (safe cast) 38 | lbp_int = np.rint(lbp_img).astype(np.int32) 39 | # Use bincount for integer labels which is faster than histogram 40 | lbp_counts = np.bincount(lbp_int.ravel(), minlength=n_bins).astype(np.float64) 41 | lbp_hist = lbp_counts / (lbp_counts.sum() + eps) 42 | 43 | ref_lbp_hist = None 44 | if ref_img_arr is not None: 45 | ref = np.asarray(ref_img_arr) 46 | # Resize reference only once if needed 47 | if ref.shape[0] != h or ref.shape[1] != w: 48 | ref_img = Image.fromarray(ref).resize((w, h), resample=Image.BICUBIC) 49 | ref = np.array(ref_img) 50 | ref_gray = np.mean(ref.astype(np.float32), axis=2) if ref.ndim == 3 else ref.astype(np.float32) 51 | ref_lbp = local_binary_pattern(ref_gray, n_points, radius, method=method) 52 | ref_int = np.rint(ref_lbp).astype(np.int32) 53 | ref_counts = np.bincount(ref_int.ravel(), minlength=n_bins).astype(np.float64) 54 | ref_lbp_hist = ref_counts / (ref_counts.sum() + eps) 55 | 56 | out = np.empty_like(img, dtype=np.float32) 57 | channels = img.shape[2] if img.ndim == 3 else 1 58 | 59 | # Precompute mapping and scale-image-level arrays only once 60 | if ref_lbp_hist is not None: 61 | cdf_img = np.cumsum(lbp_hist) 62 | cdf_ref = np.cumsum(ref_lbp_hist) 63 | # Vectorized mapping: for each possible lbp bin value find target bin 64 | mapping = np.searchsorted(cdf_ref, cdf_img, side='left') 65 | mapping = np.clip(mapping, 0, n_bins - 1).astype(np.float32) 66 | # mapping_per_pixel (h,w) 67 | mapping_per_pixel = mapping[lbp_int] 68 | # denom per pixel (avoid divide by zero) 69 | denom = (lbp_int.astype(np.float32) + eps) 70 | # precompute scale per pixel 71 | scale_per_pixel = mapping_per_pixel / denom 72 | else: 73 | # Unused but create placeholders to keep code simpler 74 | scale_per_pixel = None 75 | 76 | # Prepare noise for all channels at once (if needed) 77 | if strength > 0.0: 78 | noise_all = rng.normal(loc=0.0, scale=0.02 * strength, size=(h, w, channels)).astype(np.float32) * 255.0 79 | else: 80 | noise_all = np.zeros((h, w, channels), dtype=np.float32) 81 | 82 | # Process channels: mostly vectorized 83 | if channels == 1: 84 | channel = img.astype(np.float32) 85 | if scale_per_pixel is not None: 86 | adjusted = channel * scale_per_pixel 87 | blended = (1.0 - strength) * channel + strength * adjusted 88 | else: 89 | blended = channel 90 | blended += noise_all[:, :, 0] 91 | out[:, :] = blended 92 | else: 93 | for c in range(channels): 94 | channel = img[:, :, c].astype(np.float32) 95 | if scale_per_pixel is not None: 96 | # vectorized multiply 97 | adjusted = channel * scale_per_pixel 98 | blended = (1.0 - strength) * channel + strength * adjusted 99 | else: 100 | blended = channel 101 | blended += noise_all[:, :, c] 102 | out[:, :, c] = blended 103 | 104 | out = np.clip(out, 0, 255).astype(np.uint8) 105 | return out 106 | -------------------------------------------------------------------------------- /image_postprocess/utils/glcm_normalization.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from skimage.feature import graycomatrix, graycoprops 3 | from scipy.ndimage import gaussian_filter 4 | from PIL import Image 5 | 6 | def glcm_normalize(img_arr: np.ndarray, 7 | ref_img_arr: np.ndarray = None, 8 | distances: list = [1], 9 | angles: list = [0, np.pi/4, np.pi/2, 3*np.pi/4], 10 | levels: int = 256, 11 | strength: float = 0.9, 12 | seed: int = None, 13 | max_levels_for_speed: int = None, 14 | eps: float = 1e-8): 15 | """ 16 | Optimized GLCM normalization. 17 | 18 | Key optimizations: 19 | - quantize grayscale to fewer levels if max_levels_for_speed is provided (speeds up graycomatrix drastically) 20 | - compute glcm / properties once (not per channel) 21 | - use gaussian_filter (single multi-dimensional filter) instead of two gaussian_filter1d calls 22 | - generate noise once for all channels 23 | """ 24 | if seed is not None: 25 | rng = np.random.default_rng(seed) 26 | else: 27 | rng = np.random.default_rng() 28 | 29 | img = np.asarray(img_arr) 30 | h, w = img.shape[:2] 31 | channels = img.shape[2] if img.ndim == 3 else 1 32 | 33 | # Grayscale and quantization 34 | img_gray_f = np.mean(img.astype(np.float32), axis=2) if img.ndim == 3 else img.astype(np.float32) 35 | img_gray = (img_gray_f / 255.0 * (levels - 1)).astype(np.int32) 36 | 37 | # Optionally reduce levels for speed (safe; only if caller requests) 38 | use_levels = levels 39 | if max_levels_for_speed is not None and max_levels_for_speed < levels: 40 | use_levels = max_levels_for_speed 41 | # quantize into `use_levels` bins 42 | img_gray = np.floor(img_gray_f / 255.0 * (use_levels - 1)).astype(np.uint8) 43 | else: 44 | img_gray = img_gray.astype(np.uint8) 45 | 46 | # Compute GLCM and properties (image-level) 47 | glcm = graycomatrix(img_gray, distances=distances, angles=angles, 48 | levels=use_levels, symmetric=True, normed=True) 49 | contrast = graycoprops(glcm, 'contrast').mean() 50 | homogeneity = graycoprops(glcm, 'homogeneity').mean() 51 | 52 | ref_contrast = None 53 | ref_homogeneity = None 54 | if ref_img_arr is not None: 55 | ref = np.asarray(ref_img_arr) 56 | # Resize reference only once if needed 57 | if ref.shape[0] != h or ref.shape[1] != w: 58 | ref_img = Image.fromarray(ref).resize((w, h), resample=Image.BICUBIC) 59 | ref = np.array(ref_img) 60 | ref_gray_f = np.mean(ref.astype(np.float32), axis=2) if ref.ndim == 3 else ref.astype(np.float32) 61 | if max_levels_for_speed is not None and max_levels_for_speed < levels: 62 | ref_gray = np.floor(ref_gray_f / 255.0 * (use_levels - 1)).astype(np.uint8) 63 | else: 64 | ref_gray = (ref_gray_f / 255.0 * (use_levels - 1)).astype(np.uint8) 65 | ref_glcm = graycomatrix(ref_gray, distances=distances, angles=angles, 66 | levels=use_levels, symmetric=True, normed=True) 67 | ref_contrast = graycoprops(ref_glcm, 'contrast').mean() 68 | ref_homogeneity = graycoprops(ref_glcm, 'homogeneity').mean() 69 | 70 | out = np.empty_like(img, dtype=np.float32) 71 | 72 | # Pre-generate noise if needed for all channels 73 | if strength > 0.0: 74 | noise_all = rng.normal(loc=0.0, scale=0.02 * strength, size=(h, w, channels)).astype(np.float32) * 255.0 75 | else: 76 | noise_all = np.zeros((h, w, channels), dtype=np.float32) 77 | 78 | # If reference features exist, precompute global transforms 79 | if (ref_contrast is not None) and (ref_homogeneity is not None): 80 | contrast_ratio = ref_contrast / (contrast + eps) 81 | homogeneity_ratio = ref_homogeneity / (homogeneity + eps) 82 | # contrast adjustment uses sqrt scaling 83 | contrast_scale = np.sqrt(contrast_ratio).astype(np.float32) 84 | # homogeneity: sigma for smoothing - keep within reasonable bounds 85 | sigma = float(np.clip(1.0 / (homogeneity_ratio + eps), 0.5, 5.0)) 86 | else: 87 | contrast_scale = None 88 | sigma = None 89 | 90 | # Apply per-channel transforms (vectorized where possible) 91 | if channels == 1: 92 | channel = img.astype(np.float32) 93 | if contrast_scale is not None: 94 | adjusted = channel * contrast_scale 95 | # single multi-dimensional gaussian instead of two 1D passes 96 | adjusted = gaussian_filter(adjusted, sigma=(sigma, sigma)) 97 | blended = (1.0 - strength) * channel + strength * adjusted 98 | else: 99 | blended = channel 100 | blended += noise_all[:, :, 0] 101 | out[:, :] = blended 102 | else: 103 | for c in range(channels): 104 | channel = img[:, :, c].astype(np.float32) 105 | if contrast_scale is not None: 106 | adjusted = channel * contrast_scale 107 | adjusted = gaussian_filter(adjusted, sigma=(sigma, sigma)) 108 | blended = (1.0 - strength) * channel + strength * adjusted 109 | else: 110 | blended = channel 111 | blended += noise_all[:, :, c] 112 | out[:, :, c] = blended 113 | 114 | out = np.clip(out, 0, 255).astype(np.uint8) 115 | return out 116 | -------------------------------------------------------------------------------- /image_postprocess/utils/fourier_pipeline.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy.ndimage import gaussian_filter1d 3 | from PIL import Image 4 | 5 | def radial_profile(mag: np.ndarray, center=None, nbins=None): 6 | h, w = mag.shape 7 | if center is None: 8 | cy, cx = h // 2, w // 2 9 | else: 10 | cy, cx = center 11 | 12 | if nbins is None: 13 | nbins = int(max(h, w) / 2) 14 | nbins = max(1, int(nbins)) 15 | 16 | y = np.arange(h) - cy 17 | x = np.arange(w) - cx 18 | X, Y = np.meshgrid(x, y) 19 | R = np.sqrt(X * X + Y * Y) 20 | 21 | Rmax = R.max() 22 | if Rmax <= 0: 23 | Rnorm = R 24 | else: 25 | Rnorm = R / (Rmax + 1e-12) 26 | Rnorm = np.minimum(Rnorm, 1.0 - 1e-12) 27 | 28 | bin_edges = np.linspace(0.0, 1.0, nbins + 1) 29 | bin_idx = np.digitize(Rnorm.ravel(), bin_edges) - 1 30 | bin_idx = np.clip(bin_idx, 0, nbins - 1) 31 | 32 | sums = np.bincount(bin_idx, weights=mag.ravel(), minlength=nbins) 33 | counts = np.bincount(bin_idx, minlength=nbins) 34 | 35 | radial_mean = np.zeros(nbins, dtype=np.float64) 36 | nonzero = counts > 0 37 | radial_mean[nonzero] = sums[nonzero] / counts[nonzero] 38 | 39 | bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:]) 40 | return bin_centers, radial_mean 41 | 42 | def fourier_match_spectrum(img_arr: np.ndarray, 43 | ref_img_arr: np.ndarray = None, 44 | mode='auto', 45 | alpha=1.0, 46 | cutoff=0.25, 47 | strength=0.9, 48 | randomness=0.05, 49 | phase_perturb=0.08, 50 | radial_smooth=5, 51 | seed=None): 52 | if seed is not None: 53 | rng = np.random.default_rng(seed) 54 | else: 55 | rng = np.random.default_rng() 56 | 57 | h, w = img_arr.shape[:2] 58 | cy, cx = h // 2, w // 2 59 | nbins = max(8, int(max(h, w) / 2)) 60 | 61 | if mode == 'auto': 62 | mode = 'ref' if ref_img_arr is not None else 'model' 63 | 64 | bin_centers_src = np.linspace(0.0, 1.0, nbins) 65 | 66 | model_radial = None 67 | if mode == 'model': 68 | eps = 1e-8 69 | model_radial = (1.0 / (bin_centers_src + eps)) ** (alpha / 2.0) 70 | lf = max(1, nbins // 8) 71 | model_radial = model_radial / (np.median(model_radial[:lf]) + 1e-12) 72 | model_radial = gaussian_filter1d(model_radial, sigma=max(1, radial_smooth)) 73 | 74 | ref_radial = None 75 | ref_bin_centers = None 76 | if mode == 'ref' and ref_img_arr is not None: 77 | if ref_img_arr.shape[0] != h or ref_img_arr.shape[1] != w: 78 | ref_img = Image.fromarray(ref_img_arr).resize((w, h), resample=Image.BICUBIC) 79 | ref_img_arr = np.array(ref_img) 80 | ref_gray = np.mean(ref_img_arr.astype(np.float32), axis=2) if ref_img_arr.ndim == 3 else ref_img_arr.astype(np.float32) 81 | Fref = np.fft.fftshift(np.fft.fft2(ref_gray)) 82 | Mref = np.abs(Fref) 83 | ref_bin_centers, ref_radial = radial_profile(Mref, center=(h // 2, w // 2), nbins=nbins) 84 | ref_radial = gaussian_filter1d(ref_radial, sigma=max(1, radial_smooth)) 85 | 86 | out = np.zeros_like(img_arr, dtype=np.float32) 87 | 88 | y = np.linspace(-1, 1, h, endpoint=False)[:, None] 89 | x = np.linspace(-1, 1, w, endpoint=False)[None, :] 90 | r = np.sqrt(x * x + y * y) 91 | r = np.clip(r, 0.0, 1.0 - 1e-6) 92 | 93 | for c in range(img_arr.shape[2]): 94 | channel = img_arr[:, :, c].astype(np.float32) 95 | F = np.fft.fft2(channel) 96 | Fshift = np.fft.fftshift(F) 97 | mag = np.abs(Fshift) 98 | phase = np.angle(Fshift) 99 | 100 | bin_centers_src_calc, src_radial = radial_profile(mag, center=(h // 2, w // 2), nbins=nbins) 101 | src_radial = gaussian_filter1d(src_radial, sigma=max(1, radial_smooth)) 102 | bin_centers_src = bin_centers_src_calc 103 | 104 | if mode == 'ref' and ref_radial is not None: 105 | ref_interp = np.interp(bin_centers_src, ref_bin_centers, ref_radial) 106 | eps = 1e-8 107 | ratio = (ref_interp + eps) / (src_radial + eps) 108 | desired_radial = src_radial * ratio 109 | elif mode == 'model' and model_radial is not None: 110 | lf = max(1, nbins // 8) 111 | scale = (np.median(src_radial[:lf]) + 1e-12) / (np.median(model_radial[:lf]) + 1e-12) 112 | desired_radial = model_radial * scale 113 | else: 114 | desired_radial = src_radial.copy() 115 | 116 | eps = 1e-8 117 | multiplier_1d = (desired_radial + eps) / (src_radial + eps) 118 | multiplier_1d = np.clip(multiplier_1d, 0.2, 5.0) 119 | mult_2d = np.interp(r.ravel(), bin_centers_src, multiplier_1d).reshape(h, w) 120 | 121 | edge = 0.05 + 0.02 * (1.0 - cutoff) if 'cutoff' in globals() else 0.05 122 | edge = max(edge, 1e-6) 123 | weight = np.where(r <= 0.25, 1.0, 124 | np.where(r <= 0.25 + edge, 125 | 0.5 * (1 + np.cos(np.pi * (r - 0.25) / edge)), 126 | 0.0)) 127 | 128 | final_multiplier = 1.0 + (mult_2d - 1.0) * (weight * strength) 129 | 130 | if randomness and randomness > 0.0: 131 | noise = rng.normal(loc=1.0, scale=randomness, size=final_multiplier.shape) 132 | final_multiplier *= (1.0 + (noise - 1.0) * weight) 133 | 134 | mag2 = mag * final_multiplier 135 | 136 | if phase_perturb and phase_perturb > 0.0: 137 | phase_sigma = phase_perturb * np.clip((r - 0.25) / (1.0 - 0.25 + 1e-6), 0.0, 1.0) 138 | phase_noise = rng.standard_normal(size=phase_sigma.shape) * phase_sigma 139 | phase2 = phase + phase_noise 140 | else: 141 | phase2 = phase 142 | 143 | Fshift2 = mag2 * np.exp(1j * phase2) 144 | F_ishift = np.fft.ifftshift(Fshift2) 145 | img_back = np.fft.ifft2(F_ishift) 146 | img_back = np.real(img_back) 147 | 148 | blended = (1.0 - strength) * channel + strength * img_back 149 | out[:, :, c] = blended 150 | 151 | out = np.clip(out, 0, 255).astype(np.uint8) 152 | return out -------------------------------------------------------------------------------- /image_postprocess/utils/fourier_pipeline_new_algo.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy.ndimage import gaussian_filter1d 3 | from PIL import Image 4 | 5 | def radial_profile(mag: np.ndarray, center=None, nbins=None): 6 | h, w = mag.shape 7 | if center is None: 8 | cy, cx = h // 2, w // 2 9 | else: 10 | cy, cx = center 11 | 12 | if nbins is None: 13 | nbins = int(max(h, w) / 2) 14 | nbins = max(1, int(nbins)) 15 | 16 | y = np.arange(h) - cy 17 | x = np.arange(w) - cx 18 | X, Y = np.meshgrid(x, y) 19 | R = np.sqrt(X * X + Y * Y) 20 | 21 | Rmax = R.max() 22 | if Rmax <= 0: 23 | Rnorm = R 24 | else: 25 | Rnorm = R / (Rmax + 1e-12) 26 | Rnorm = np.minimum(Rnorm, 1.0 - 1e-12) 27 | 28 | bin_edges = np.linspace(0.0, 1.0, nbins + 1) 29 | bin_idx = np.digitize(Rnorm.ravel(), bin_edges) - 1 30 | bin_idx = np.clip(bin_idx, 0, nbins - 1) 31 | 32 | sums = np.bincount(bin_idx, weights=mag.ravel(), minlength=nbins) 33 | counts = np.bincount(bin_idx, minlength=nbins) 34 | 35 | radial_mean = np.zeros(nbins, dtype=np.float64) 36 | nonzero = counts > 0 37 | radial_mean[nonzero] = sums[nonzero] / counts[nonzero] 38 | 39 | bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:]) 40 | return bin_centers, radial_mean 41 | 42 | def fourier_match_spectrum(img_arr: np.ndarray, 43 | ref_img_arr: np.ndarray = None, 44 | mode='auto', 45 | alpha=1.0, 46 | cutoff=0.25, 47 | strength=0.9, 48 | randomness=0.05, 49 | phase_perturb=0.08, 50 | radial_smooth=5, 51 | seed=None): 52 | if seed is not None: 53 | rng = np.random.default_rng(seed) 54 | else: 55 | rng = np.random.default_rng() 56 | 57 | # Ensure image well defined 58 | if img_arr.ndim == 2: 59 | h, w = img_arr.shape 60 | nch = 1 61 | elif img_arr.ndim == 3: 62 | h, w, nch = img_arr.shape 63 | else: 64 | raise ValueError("img_arr must be 2D or 3D") 65 | 66 | nbins = max(8, int(max(h, w) / 2)) 67 | 68 | # Determine mode if auto: use 'ref' if reference image is provided, else 'model' 69 | if mode == 'auto': 70 | mode = 'ref' if ref_img_arr is not None else 'model' 71 | 72 | # Create a coordinate grid for building a 2D radial map 73 | y = np.linspace(-1, 1, h, endpoint=False)[:, None] 74 | x = np.linspace(-1, 1, w, endpoint=False)[None, :] 75 | r = np.sqrt(x * x + y * y) 76 | r = np.clip(r, 0.0, 1.0 - 1e-6) 77 | 78 | # Compute luminance (or gray) from img_arr once. 79 | if nch == 1: 80 | src_gray = img_arr.astype(np.float32) 81 | else: 82 | # Using simple average; optionally use luma weights (0.2126,0.7152,0.0722) 83 | src_gray = np.mean(img_arr.astype(np.float32), axis=2) 84 | 85 | # FFT of the source luminance & compute radial profile 86 | Fsrc = np.fft.fftshift(np.fft.fft2(src_gray)) 87 | Msrc = np.abs(Fsrc) 88 | bin_centers_src, src_radial = radial_profile(Msrc, center=(h//2, w//2), nbins=nbins) 89 | src_radial = gaussian_filter1d(src_radial, sigma=max(1, radial_smooth)) 90 | 91 | model_radial = None 92 | if mode == 'model': 93 | eps = 1e-8 94 | model_radial = (1.0 / (bin_centers_src + eps)) ** (alpha / 2.0) 95 | lf = max(1, nbins // 8) 96 | model_radial = model_radial / (np.median(model_radial[:lf]) + 1e-12) 97 | model_radial = gaussian_filter1d(model_radial, sigma=max(1, radial_smooth)) 98 | 99 | ref_radial = None 100 | ref_bin_centers = None 101 | if mode == 'ref' and ref_img_arr is not None: 102 | # Resize ref image if needed 103 | if ref_img_arr.shape[0] != h or ref_img_arr.shape[1] != w: 104 | ref_img = Image.fromarray(ref_img_arr).resize((w, h), resample=Image.BICUBIC) 105 | ref_img_arr = np.array(ref_img) 106 | # Convert ref image to grayscale 107 | if ref_img_arr.ndim == 3: 108 | ref_gray = np.mean(ref_img_arr.astype(np.float32), axis=2) 109 | else: 110 | ref_gray = ref_img_arr.astype(np.float32) 111 | Fref = np.fft.fftshift(np.fft.fft2(ref_gray)) 112 | Mref = np.abs(Fref) 113 | ref_bin_centers, ref_radial = radial_profile(Mref, center=(h//2, w//2), nbins=nbins) 114 | ref_radial = gaussian_filter1d(ref_radial, sigma=max(1, radial_smooth)) 115 | 116 | # Compute desired radial profile based on mode 117 | eps = 1e-8 118 | if mode == 'ref' and ref_radial is not None: 119 | ref_interp = np.interp(bin_centers_src, ref_bin_centers, ref_radial) 120 | lf = max(1, nbins // 8) 121 | scale = (np.median(src_radial[:lf]) + eps) / (np.median(ref_interp[:lf]) + eps) 122 | ref_interp *= scale 123 | desired_radial = ref_interp.copy() 124 | elif mode == 'model' and model_radial is not None: 125 | lf = max(1, nbins // 8) 126 | scale = (np.median(src_radial[:lf]) + eps) / (np.median(model_radial[:lf]) + eps) 127 | desired_radial = model_radial * scale 128 | else: 129 | desired_radial = src_radial.copy() 130 | 131 | # Compute 1D multiplier and clip 132 | eps = 1e-8 133 | # adjust clip range and re-introduce strength into multiplier 134 | multiplier_1d = (desired_radial + eps) / (src_radial + eps) 135 | multiplier_1d = np.clip(multiplier_1d, 0.05, 10.0) # wider range -> stronger effect 136 | 137 | # Build the 2D multiplier map (weight remains computed as before) 138 | edge = 0.05 + 0.02 * (1.0 - cutoff) 139 | edge = max(edge, 1e-6) 140 | weight = np.where(r <= cutoff, 1.0, 141 | np.where(r <= cutoff + edge, 142 | 0.5 * (1 + np.cos(np.pi * (r - cutoff) / edge)), 143 | 0.0)) 144 | mult_2d = np.interp(r.ravel(), bin_centers_src, multiplier_1d).reshape(h, w) 145 | # include strength in multiplier application (stronger spectral change) 146 | final_multiplier = 1.0 + (mult_2d - 1.0) * (weight * strength) 147 | 148 | # optional randomness (kept weighted) 149 | if randomness and randomness > 0.0: 150 | noise = rng.normal(loc=1.0, scale=randomness, size=final_multiplier.shape) 151 | final_multiplier *= (1.0 + (noise - 1.0) * weight) 152 | 153 | # Prepare output buffer. 154 | if nch == 1: 155 | out = np.zeros((h, w), dtype=np.uint8) 156 | else: 157 | out = np.zeros((h, w, nch), dtype=np.uint8) 158 | 159 | # Process each channel (for grayscale, loop once) 160 | for c in range(nch): 161 | if nch == 1: 162 | channel = img_arr.astype(np.float32) 163 | else: 164 | channel = img_arr[:, :, c].astype(np.float32) 165 | 166 | F = np.fft.fft2(channel) 167 | Fshift = np.fft.fftshift(F) 168 | mag = np.abs(Fshift) 169 | phase = np.angle(Fshift) 170 | 171 | # Apply final multiplier computed from luminance. 172 | mag2 = mag * final_multiplier 173 | 174 | # Apply phase perturbation using cutoff instead of hard-coded value. 175 | if phase_perturb and phase_perturb > 0.0: 176 | phase_sigma = phase_perturb * np.clip((r - cutoff) / (1.0 - cutoff + 1e-6), 0.0, 1.0) 177 | phase_noise = rng.standard_normal(size=phase_sigma.shape) * phase_sigma 178 | phase2 = phase + phase_noise 179 | else: 180 | phase2 = phase 181 | 182 | Fshift2 = mag2 * np.exp(1j * phase2) 183 | F_ishift = np.fft.ifftshift(Fshift2) 184 | img_back = np.fft.ifft2(F_ishift) 185 | img_back = np.real(img_back) 186 | 187 | # Blend lightly (so you still can dial strength) 188 | blended = (1.0 - min(0.5, 1.0 - strength)) * channel + min(1.0, strength + 0.2) * img_back 189 | 190 | if nch == 1: 191 | out[:, :] = np.clip(blended, 0, 255).astype(np.uint8) 192 | else: 193 | out[:, :, c] = np.clip(blended, 0, 255).astype(np.uint8) 194 | 195 | return out -------------------------------------------------------------------------------- /image_postprocess/utils/blend.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy.cluster.vq import kmeans2 3 | from scipy.ndimage import label, mean as ndi_mean 4 | from scipy.spatial import cKDTree 5 | import os 6 | from concurrent.futures import ThreadPoolExecutor, as_completed 7 | 8 | # Vectorized color conversions 9 | def rgb_to_hsv(rgb: np.ndarray) -> np.ndarray: 10 | """ 11 | Vectorized RGB->[H(0..360), S(0..1), V(0..1)]. 12 | rgb: (..., 3) in [0,255] 13 | """ 14 | rgb = rgb.astype(np.float32) / 255.0 15 | r = rgb[..., 0] 16 | g = rgb[..., 1] 17 | b = rgb[..., 2] 18 | 19 | maxc = np.maximum(np.maximum(r, g), b) 20 | minc = np.minimum(np.minimum(r, g), b) 21 | delta = maxc - minc 22 | 23 | # Hue 24 | h = np.zeros_like(maxc) 25 | nonzero = delta > 1e-8 26 | 27 | # r is max 28 | mask = nonzero & (maxc == r) 29 | h[mask] = ((g[mask] - b[mask]) / delta[mask]) % 6 30 | # g is max 31 | mask = nonzero & (maxc == g) 32 | h[mask] = ((b[mask] - r[mask]) / delta[mask]) + 2 33 | # b is max 34 | mask = nonzero & (maxc == b) 35 | h[mask] = ((r[mask] - g[mask]) / delta[mask]) + 4 36 | 37 | h = h * 60.0 # degrees 38 | h[~nonzero] = 0.0 39 | 40 | # Saturation 41 | s = np.zeros_like(maxc) 42 | nonzero_max = maxc > 1e-8 43 | s[nonzero_max] = delta[nonzero_max] / maxc[nonzero_max] 44 | 45 | v = maxc 46 | hsv = np.stack([h, s, v], axis=-1) 47 | return hsv 48 | 49 | def hsv_to_rgb(hsv: np.ndarray) -> np.ndarray: 50 | """ 51 | Vectorized HSV->[0..255] RGB. 52 | hsv: (...,3) with H in [0,360], S,V in [0,1] 53 | """ 54 | h = hsv[..., 0] / 60.0 # sector 55 | s = hsv[..., 1] 56 | v = hsv[..., 2] 57 | 58 | c = v * s 59 | x = c * (1 - np.abs((h % 2) - 1)) 60 | m = v - c 61 | 62 | rp = np.zeros_like(h) 63 | gp = np.zeros_like(h) 64 | bp = np.zeros_like(h) 65 | 66 | seg0 = (0 <= h) & (h < 1) 67 | seg1 = (1 <= h) & (h < 2) 68 | seg2 = (2 <= h) & (h < 3) 69 | seg3 = (3 <= h) & (h < 4) 70 | seg4 = (4 <= h) & (h < 5) 71 | seg5 = (5 <= h) & (h < 6) 72 | 73 | rp[seg0] = c[seg0]; gp[seg0] = x[seg0]; bp[seg0] = 0 74 | rp[seg1] = x[seg1]; gp[seg1] = c[seg1]; bp[seg1] = 0 75 | rp[seg2] = 0; gp[seg2] = c[seg2]; bp[seg2] = x[seg2] 76 | rp[seg3] = 0; gp[seg3] = x[seg3]; bp[seg3] = c[seg3] 77 | rp[seg4] = x[seg4]; gp[seg4] = 0; bp[seg4] = c[seg4] 78 | rp[seg5] = c[seg5]; gp[seg5] = 0; bp[seg5] = x[seg5] 79 | 80 | r = (rp + m) 81 | g = (gp + m) 82 | b = (bp + m) 83 | 84 | rgb = np.stack([r, g, b], axis=-1) 85 | rgb = np.clip(rgb * 255.0, 0, 255).astype(np.uint8) 86 | return rgb 87 | 88 | # Main blending pipeline 89 | 90 | def blend_colors(image: np.ndarray, tolerance: float = 10.0, min_region_size: int = 50, 91 | max_kmeans_samples: int = 100000, n_jobs: int | None = None) -> np.ndarray: 92 | """ 93 | Parallelized version of blend_colors. 94 | n_jobs: number of worker threads (None -> os.cpu_count()). 95 | """ 96 | if not isinstance(image, np.ndarray) or image.dtype != np.uint8 or image.ndim != 3: 97 | raise ValueError("Input must be a 3D NumPy array with uint8 dtype (H, W, C)") 98 | 99 | height, width, channels = image.shape 100 | assert channels == 3 101 | 102 | img_f = image.astype(np.float32) 103 | pixels = img_f.reshape(-1, 3) 104 | n_pixels = pixels.shape[0] 105 | 106 | num_clusters = max(1, int(256 / tolerance)) 107 | 108 | # Subsample for kmeans 109 | rng = np.random.default_rng(seed=12345) 110 | if n_pixels > max_kmeans_samples: 111 | sample_idx = rng.choice(n_pixels, size=max_kmeans_samples, replace=False) 112 | else: 113 | sample_idx = np.arange(n_pixels) 114 | sample_data = pixels[sample_idx] 115 | 116 | centroids, _ = kmeans2(sample_data, num_clusters, minit='points') 117 | 118 | # Assign every pixel to nearest centroid in chunks (same as original) 119 | labels_all = np.empty(n_pixels, dtype=np.int32) 120 | chunk = 1_000_000 121 | for start in range(0, n_pixels, chunk): 122 | end = min(start + chunk, n_pixels) 123 | block = pixels[start:end] # (M,3) 124 | a2 = np.sum(block * block, axis=1)[:, None] 125 | b2 = np.sum(centroids * centroids, axis=1)[None, :] 126 | ab = block.dot(centroids.T) 127 | d2 = a2 + b2 - 2 * ab 128 | labels_all[start:end] = np.argmin(d2, axis=1) 129 | 130 | label_map = labels_all.reshape(height, width) 131 | output_image = image.copy() 132 | 133 | structure = np.ones((3, 3), dtype=np.int8) 134 | 135 | # Worker for a single cluster (runs in thread) 136 | def process_cluster(cluster_id: int): 137 | cluster_mask = (label_map == cluster_id).astype(np.uint8) 138 | if cluster_mask.sum() == 0: 139 | return 0 # nothing done 140 | 141 | labeled_array, num_features = label(cluster_mask, structure=structure) 142 | if num_features == 0: 143 | return 0 144 | 145 | counts = np.bincount(labeled_array.ravel()) 146 | valid_ids = np.nonzero(counts >= min_region_size)[0] 147 | valid_ids = valid_ids[valid_ids != 0] 148 | if valid_ids.size == 0: 149 | return 0 150 | 151 | idx_list = valid_ids.tolist() 152 | means_r = ndi_mean(img_f[..., 0], labels=labeled_array, index=idx_list) 153 | means_g = ndi_mean(img_f[..., 1], labels=labeled_array, index=idx_list) 154 | means_b = ndi_mean(img_f[..., 2], labels=labeled_array, index=idx_list) 155 | region_means = np.stack([means_r, means_g, means_b], axis=-1) # float 0..255 156 | 157 | # convert region means to HSV and generate new colors per region 158 | region_mean_hsv = rgb_to_hsv(region_means[np.newaxis, :, :].reshape(-1, 3)) 159 | # iterate regions (small loop per region; still OK) 160 | for i, region_label in enumerate(idx_list): 161 | seed_val = 42 + cluster_id + int(region_label) 162 | rng_region = np.random.default_rng(seed_val) 163 | shifts = rng_region.uniform(-0.05, 0.05, size=3) 164 | hsv = region_mean_hsv[i].copy() 165 | hsv += shifts * np.array([10.0, 0.1, 0.1]) 166 | hsv[0] = np.clip(hsv[0], 0, 360) 167 | hsv[1] = np.clip(hsv[1], 0, 1) 168 | hsv[2] = np.clip(hsv[2], 0, 1) 169 | rgb_new = hsv_to_rgb(hsv[np.newaxis, :])[0] 170 | 171 | mask = (labeled_array == int(region_label)) 172 | # assign directly into shared output_image; clusters don't overlap so this is safe 173 | output_image[mask] = rgb_new 174 | 175 | return 1 # done something 176 | 177 | # Run cluster processing in thread pool 178 | if n_jobs is None: 179 | n_jobs = os.cpu_count() or 1 180 | n_jobs = max(1, int(n_jobs)) 181 | 182 | with ThreadPoolExecutor(max_workers=n_jobs) as ex: 183 | futures = [ex.submit(process_cluster, cid) for cid in range(num_clusters)] 184 | # optional: iterate to ensure completion 185 | for _ in as_completed(futures): 186 | pass 187 | 188 | # Island absorbtion (parallelize KD-tree queries by chunking queries) 189 | changed_mask = np.any(output_image != image, axis=2) 190 | if not np.all(changed_mask) and changed_mask.any(): 191 | changed_coords = np.column_stack(np.nonzero(changed_mask)) # (M,2) 192 | changed_colors = output_image[changed_mask] # (M,3) 193 | unchanged_coords = np.column_stack(np.nonzero(~changed_mask)) # (U,2) 194 | 195 | if changed_coords.shape[0] > 0 and unchanged_coords.shape[0] > 0: 196 | tree = cKDTree(changed_coords) 197 | 198 | # We'll chunk the unchanged coords and parallel query 199 | def query_chunk(start_end): 200 | s, e = start_end 201 | sub = unchanged_coords[s:e] 202 | _, idxs = tree.query(sub, k=1) 203 | return (s, e, idxs) 204 | 205 | # prepare ranges 206 | U = unchanged_coords.shape[0] 207 | qchunk = max(1_000, U // (n_jobs * 4) + 1) 208 | ranges = [(i, min(i + qchunk, U)) for i in range(0, U, qchunk)] 209 | 210 | nearest_colors = np.empty((U, 3), dtype=np.uint8) 211 | with ThreadPoolExecutor(max_workers=n_jobs) as ex: 212 | futures = [ex.submit(query_chunk, r) for r in ranges] 213 | for fut in as_completed(futures): 214 | s, e, idxs = fut.result() 215 | nearest_colors[s:e] = changed_colors[idxs] 216 | 217 | # assign back 218 | # flatten indexing: map (r,c) to flat index 219 | flat_idx = unchanged_coords[:, 0] * width + unchanged_coords[:, 1] 220 | out_flat = output_image.reshape(-1, 3) 221 | out_flat[flat_idx] = nearest_colors 222 | 223 | return output_image 224 | -------------------------------------------------------------------------------- /ui_utils/analysis_panel.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Analysis panel for histogram, FFT, radial profile, GLCM, and LBP plots. 4 | Designed to plug straight into the provided run.py / MainWindow. 5 | 6 | Exposes AnalysisPanel(title: str) with method update_from_path(path) 7 | and clear_plots(). Uses helpers from utils: 8 | - compute_gray_array(path) -> 2D numpy.ndarray (grayscale 0-255) 9 | - compute_fft_magnitude(gray) -> (mag, mag_log) 10 | - radial_profile(mag) -> (centers, radial) 11 | - compute_glcm(gray) -> (glcm, features) 12 | - compute_lbp(gray) -> (lbp, hist) 13 | - make_canvas(width, height) -> (FigureCanvas, Axes) 14 | """ 15 | 16 | from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QGroupBox, QSizePolicy, QLabel 17 | from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas 18 | import numpy as np 19 | import os 20 | 21 | from utils import compute_gray_array, compute_fft_magnitude, radial_profile, compute_glcm, compute_lbp, make_canvas 22 | 23 | 24 | class AnalysisPanel(QWidget): 25 | def __init__(self, title: str = "Analysis", parent=None): 26 | super().__init__(parent) 27 | self.setMinimumHeight(360) # Increased to accommodate additional plots 28 | 29 | # Top-level layout + framed group 30 | v = QVBoxLayout(self) 31 | box = QGroupBox(title) 32 | vbox = QVBoxLayout() 33 | box.setLayout(vbox) 34 | 35 | # Two rows of plots: top row for histogram/FFT/radial, bottom for GLCM/LBP 36 | row1 = QHBoxLayout() 37 | row2 = QHBoxLayout() 38 | 39 | # Create canvases using project's make_canvas helper 40 | self.hist_canvas, self.hist_ax = make_canvas(width=3, height=2) 41 | self.fft_canvas, self.fft_ax = make_canvas(width=3, height=2) 42 | self.radial_canvas, self.radial_ax = make_canvas(width=3, height=2) 43 | self.glcm_canvas, self.glcm_ax = make_canvas(width=4.5, height=2) # Wider for multiple features 44 | self.lbp_canvas, self.lbp_ax = make_canvas(width=4.5, height=2) 45 | 46 | # Configure size policy and margins for all canvases 47 | for c in (self.hist_canvas, self.fft_canvas, self.radial_canvas, self.glcm_canvas, self.lbp_canvas): 48 | c.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) 49 | try: 50 | c.figure.subplots_adjust(top=0.88, bottom=0.12, left=0.12, right=0.96) 51 | except Exception: 52 | pass 53 | 54 | # Add to layouts 55 | row1.addWidget(self.hist_canvas) 56 | row1.addWidget(self.fft_canvas) 57 | row1.addWidget(self.radial_canvas) 58 | row2.addWidget(self.glcm_canvas) 59 | row2.addWidget(self.lbp_canvas) 60 | 61 | vbox.addLayout(row1) 62 | vbox.addLayout(row2) 63 | 64 | # Status label for diagnostics 65 | self.status_label = QLabel("") 66 | self.status_label.setWordWrap(True) 67 | self.status_label.setVisible(False) 68 | vbox.addWidget(self.status_label) 69 | 70 | v.addWidget(box) 71 | 72 | def update_from_path(self, path: str): 73 | """Update all five plots using the image at `path`. 74 | 75 | If path is invalid or an error occurs, plots are cleared and a status message is shown. 76 | """ 77 | if not path or not os.path.exists(path): 78 | self.status_label.setText(f"No image: {path}") 79 | self.status_label.setVisible(True) 80 | self.clear_plots() 81 | return 82 | 83 | try: 84 | gray = compute_gray_array(path) 85 | if gray is None: 86 | raise ValueError("compute_gray_array returned None") 87 | gray = np.asarray(gray) 88 | if gray.ndim != 2: 89 | raise ValueError("expected 2D grayscale array") 90 | except Exception as e: 91 | self.status_label.setText(f"Failed to load image: {e}") 92 | self.status_label.setVisible(True) 93 | self.clear_plots() 94 | return 95 | 96 | self.status_label.setVisible(False) 97 | 98 | # -------------------- Histogram -------------------- 99 | try: 100 | self.hist_ax.cla() 101 | self.hist_ax.set_title('Grayscale histogram') 102 | self.hist_ax.set_xlabel('Intensity') 103 | self.hist_ax.set_ylabel('Count') 104 | flat = gray.ravel() 105 | if flat.dtype.kind == 'f' and flat.max() <= 1.0: 106 | flat = (flat * 255.0).astype(np.uint8) 107 | self.hist_ax.hist(flat, bins=256, range=(0, 255)) 108 | self.hist_canvas.draw() 109 | except Exception as e: 110 | self.hist_ax.cla() 111 | self.hist_canvas.draw() 112 | self.status_label.setText(f"Histogram error: {e}") 113 | self.status_label.setVisible(True) 114 | 115 | # -------------------- FFT magnitude -------------------- 116 | try: 117 | mag, mag_log = compute_fft_magnitude(gray) 118 | if mag_log is None: 119 | raise ValueError("compute_fft_magnitude returned None") 120 | self.fft_ax.cla() 121 | self.fft_ax.set_title('FFT magnitude (log)') 122 | self.fft_ax.imshow(mag_log, origin='lower', aspect='auto', cmap='inferno') 123 | self.fft_ax.set_xticks([]) 124 | self.fft_ax.set_yticks([]) 125 | try: 126 | self.fft_canvas.figure.subplots_adjust(right=0.92) 127 | except Exception: 128 | pass 129 | self.fft_canvas.draw() 130 | except Exception as e: 131 | self.fft_ax.cla() 132 | self.fft_canvas.draw() 133 | self.status_label.setText(f"FFT error: {e}") 134 | self.status_label.setVisible(True) 135 | 136 | # -------------------- Radial profile -------------------- 137 | try: 138 | centers, radial = radial_profile(mag) 139 | if centers is None or radial is None: 140 | raise ValueError("radial_profile returned invalid data") 141 | self.radial_ax.cla() 142 | self.radial_ax.set_title('Radial freq profile') 143 | self.radial_ax.set_xlabel('Normalized radius') 144 | self.radial_ax.set_ylabel('Mean magnitude') 145 | self.radial_ax.plot(centers, radial) 146 | self.radial_canvas.draw() 147 | except Exception as e: 148 | self.radial_ax.cla() 149 | self.radial_canvas.draw() 150 | self.status_label.setText(f"Radial profile error: {e}") 151 | self.status_label.setVisible(True) 152 | 153 | # -------------------- GLCM Features -------------------- 154 | try: 155 | _, features = compute_glcm(gray) 156 | if features is None: 157 | raise ValueError("compute_glcm returned None") 158 | self.glcm_ax.cla() 159 | self.glcm_ax.set_title('GLCM Features') 160 | self.glcm_ax.set_xlabel('Offset') 161 | self.glcm_ax.set_ylabel('Value') 162 | offsets = ['(0,1)', '(1,0)', '(1,1)', '(-1,1)'] 163 | x = np.arange(len(offsets)) 164 | for feature in ['contrast', 'correlation', 'energy', 'homogeneity']: 165 | self.glcm_ax.plot(x, features[feature], label=feature, marker='o') 166 | self.glcm_ax.set_xticks(x) 167 | self.glcm_ax.set_xticklabels(offsets) 168 | self.glcm_ax.legend() 169 | self.glcm_canvas.draw() 170 | except Exception as e: 171 | self.glcm_ax.cla() 172 | self.glcm_canvas.draw() 173 | self.status_label.setText(f"GLCM error: {e}") 174 | self.status_label.setVisible(True) 175 | 176 | # -------------------- LBP Histogram -------------------- 177 | try: 178 | _, hist = compute_lbp(gray) 179 | if hist is None: 180 | raise ValueError("compute_lbp returned None") 181 | self.lbp_ax.cla() 182 | self.lbp_ax.set_title('LBP Histogram') 183 | self.lbp_ax.set_xlabel('Pattern') 184 | self.lbp_ax.set_ylabel('Frequency') 185 | self.lbp_ax.bar(range(len(hist)), hist) 186 | self.lbp_ax.set_xticks(range(len(hist))) 187 | self.lbp_canvas.draw() 188 | except Exception as e: 189 | self.lbp_ax.cla() 190 | self.lbp_canvas.draw() 191 | self.status_label.setText(f"LBP error: {e}") 192 | self.status_label.setVisible(True) 193 | 194 | def clear_plots(self): 195 | """Clear all axes and redraw empty canvases.""" 196 | for ax, canvas in ( 197 | (self.hist_ax, self.hist_canvas), 198 | (self.fft_ax, self.fft_canvas), 199 | (self.radial_ax, self.radial_canvas), 200 | (self.glcm_ax, self.glcm_canvas), 201 | (self.lbp_ax, self.lbp_canvas) 202 | ): 203 | try: 204 | ax.cla() 205 | if ax is self.hist_ax: 206 | ax.text(0.5, 0.5, 'No image', horizontalalignment='center', verticalalignment='center', transform=ax.transAxes) 207 | canvas.draw() 208 | except Exception: 209 | pass -------------------------------------------------------------------------------- /image_postprocess/utils/color_lut.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import re, os 3 | from PIL import Image 4 | 5 | def apply_1d_lut(img_arr: np.ndarray, lut: np.ndarray, strength: float = 1.0) -> np.ndarray: 6 | """ 7 | Apply a 1D LUT to an image. 8 | - img_arr: HxWx3 uint8 9 | - lut: either shape (256,) (applied equally to all channels), (256,3) (per-channel), 10 | or (N,) / (N,3) (interpolated across [0..255]) 11 | - strength: 0..1 blending between original and LUT result 12 | Returns uint8 array. 13 | """ 14 | if img_arr.ndim != 3 or img_arr.shape[2] != 3: 15 | raise ValueError("apply_1d_lut expects an HxWx3 image array") 16 | 17 | # Normalize indices 0..255 18 | arr = img_arr.astype(np.float32) 19 | # Prepare LUT as float in 0..255 range if necessary 20 | lut_arr = np.array(lut, dtype=np.float32) 21 | 22 | # If single channel LUT (N,) expand to three channels 23 | if lut_arr.ndim == 1: 24 | lut_arr = np.stack([lut_arr, lut_arr, lut_arr], axis=1) # (N,3) 25 | 26 | if lut_arr.shape[1] != 3: 27 | raise ValueError("1D LUT must have shape (N,) or (N,3)") 28 | 29 | # Build index positions in source LUT space (0..255) 30 | N = lut_arr.shape[0] 31 | src_positions = np.linspace(0, 255, N) 32 | 33 | # Flatten and interpolate per channel 34 | out = np.empty_like(arr) 35 | for c in range(3): 36 | channel = arr[..., c].ravel() 37 | mapped = np.interp(channel, src_positions, lut_arr[:, c]) 38 | out[..., c] = mapped.reshape(arr.shape[0], arr.shape[1]) 39 | 40 | out = np.clip(out, 0, 255).astype(np.uint8) 41 | if strength >= 1.0: 42 | return out 43 | else: 44 | blended = ((1.0 - strength) * img_arr.astype(np.float32) + strength * out.astype(np.float32)) 45 | return np.clip(blended, 0, 255).astype(np.uint8) 46 | 47 | def _trilinear_sample_lut(img_float: np.ndarray, lut: np.ndarray) -> np.ndarray: 48 | """ 49 | Vectorized trilinear sampling of 3D LUT. 50 | - img_float: HxWx3 floats in [0,1] 51 | - lut: SxSxS x 3 floats in [0,1] 52 | Returns HxWx3 floats in [0,1] 53 | """ 54 | S = lut.shape[0] 55 | if lut.shape[0] != lut.shape[1] or lut.shape[1] != lut.shape[2]: 56 | raise ValueError("3D LUT must be cubic (SxSxSx3)") 57 | 58 | # map [0,1] -> [0, S-1] 59 | idx = img_float * (S - 1) 60 | r_idx = idx[..., 0] 61 | g_idx = idx[..., 1] 62 | b_idx = idx[..., 2] 63 | 64 | r0 = np.floor(r_idx).astype(np.int32) 65 | g0 = np.floor(g_idx).astype(np.int32) 66 | b0 = np.floor(b_idx).astype(np.int32) 67 | 68 | r1 = np.clip(r0 + 1, 0, S - 1) 69 | g1 = np.clip(g0 + 1, 0, S - 1) 70 | b1 = np.clip(b0 + 1, 0, S - 1) 71 | 72 | dr = (r_idx - r0)[..., None] 73 | dg = (g_idx - g0)[..., None] 74 | db = (b_idx - b0)[..., None] 75 | 76 | # gather 8 corners: c000 ... c111 77 | c000 = lut[r0, g0, b0] 78 | c001 = lut[r0, g0, b1] 79 | c010 = lut[r0, g1, b0] 80 | c011 = lut[r0, g1, b1] 81 | c100 = lut[r1, g0, b0] 82 | c101 = lut[r1, g0, b1] 83 | c110 = lut[r1, g1, b0] 84 | c111 = lut[r1, g1, b1] 85 | 86 | # interpolate along b 87 | c00 = c000 * (1 - db) + c001 * db 88 | c01 = c010 * (1 - db) + c011 * db 89 | c10 = c100 * (1 - db) + c101 * db 90 | c11 = c110 * (1 - db) + c111 * db 91 | 92 | # interpolate along g 93 | c0 = c00 * (1 - dg) + c01 * dg 94 | c1 = c10 * (1 - dg) + c11 * dg 95 | 96 | # interpolate along r 97 | c = c0 * (1 - dr) + c1 * dr 98 | 99 | return c # float in same range as lut (expected [0,1]) 100 | 101 | def apply_3d_lut(img_arr: np.ndarray, lut3d: np.ndarray, strength: float = 1.0) -> np.ndarray: 102 | """ 103 | Apply a 3D LUT to the image. 104 | - img_arr: HxWx3 uint8 105 | - lut3d: SxSxSx3 float (expected range 0..1) 106 | - strength: blending 0..1 107 | Returns uint8 image. 108 | """ 109 | if img_arr.ndim != 3 or img_arr.shape[2] != 3: 110 | raise ValueError("apply_3d_lut expects an HxWx3 image array") 111 | 112 | img_float = img_arr.astype(np.float32) / 255.0 113 | sampled = _trilinear_sample_lut(img_float, lut3d) # HxWx3 floats in [0,1] 114 | out = np.clip(sampled * 255.0, 0, 255).astype(np.uint8) 115 | if strength >= 1.0: 116 | return out 117 | else: 118 | blended = ((1.0 - strength) * img_arr.astype(np.float32) + strength * out.astype(np.float32)) 119 | return np.clip(blended, 0, 255).astype(np.uint8) 120 | 121 | def apply_lut(img_arr: np.ndarray, lut: np.ndarray, strength: float = 1.0) -> np.ndarray: 122 | """ 123 | Auto-detect LUT type and apply. 124 | - If lut.ndim in (1,2) treat as 1D LUT (per-channel if shape (N,3)). 125 | - If lut.ndim == 4 treat as 3D LUT (SxSxSx3) in [0,1]. 126 | """ 127 | lut = np.array(lut) 128 | if lut.ndim == 4 and lut.shape[3] == 3: 129 | # 3D LUT (assumed normalized [0..1]) 130 | # If lut is in 0..255, normalize 131 | if lut.dtype != np.float32 and lut.max() > 1.0: 132 | lut = lut.astype(np.float32) / 255.0 133 | return apply_3d_lut(img_arr, lut, strength=strength) 134 | elif lut.ndim in (1, 2): 135 | return apply_1d_lut(img_arr, lut, strength=strength) 136 | else: 137 | raise ValueError("Unsupported LUT shape: {}".format(lut.shape)) 138 | 139 | def load_cube_lut(path: str) -> np.ndarray: 140 | """ 141 | Parse a .cube file and return a 3D LUT array of shape (S,S,S,3) with float values in [0,1]. 142 | Note: .cube file order sometimes varies; this function assumes standard ordering 143 | where data lines are triples of floats and LUT_3D_SIZE specifies S. 144 | """ 145 | with open(path, 'r', encoding='utf-8', errors='ignore') as f: 146 | lines = [ln.strip() for ln in f if ln.strip() and not ln.strip().startswith('#')] 147 | 148 | size = None 149 | data = [] 150 | domain_min = np.array([0.0, 0.0, 0.0], dtype=np.float32) 151 | domain_max = np.array([1.0, 1.0, 1.0], dtype=np.float32) 152 | 153 | for ln in lines: 154 | if ln.upper().startswith('LUT_3D_SIZE'): 155 | parts = ln.split() 156 | if len(parts) >= 2: 157 | size = int(parts[1]) 158 | elif ln.upper().startswith('DOMAIN_MIN'): 159 | parts = ln.split() 160 | domain_min = np.array([float(p) for p in parts[1:4]], dtype=np.float32) 161 | elif ln.upper().startswith('DOMAIN_MAX'): 162 | parts = ln.split() 163 | domain_max = np.array([float(p) for p in parts[1:4]], dtype=np.float32) 164 | elif re.match(r'^-?\d+(\.\d+)?\s+-?\d+(\.\d+)?\s+-?\d+(\.\d+)?$', ln): 165 | parts = [float(x) for x in ln.split()] 166 | data.append(parts) 167 | 168 | if size is None: 169 | raise ValueError("LUT_3D_SIZE not found in .cube file: {}".format(path)) 170 | 171 | data = np.array(data, dtype=np.float32) 172 | if data.shape[0] != size**3: 173 | raise ValueError("Cube LUT data length does not match size^3 (got {}, expected {})".format(data.shape[0], size**3)) 174 | 175 | # Data ordering in many .cube files is: for r in 0..S-1: for g in 0..S-1: for b in 0..S-1: write RGB 176 | # We'll reshape into (S,S,S,3) with indices [r,g,b] 177 | lut = data.reshape((size, size, size, 3)) 178 | # Map domain_min..domain_max to 0..1 if domain specified (rare) 179 | if not np.allclose(domain_min, [0.0, 0.0, 0.0]) or not np.allclose(domain_max, [1.0, 1.0, 1.0]): 180 | # scale lut values from domain range into 0..1 181 | lut = (lut - domain_min) / (domain_max - domain_min + 1e-12) 182 | lut = np.clip(lut, 0.0, 1.0) 183 | else: 184 | # ensure LUT is in [0,1] if not already 185 | if lut.max() > 1.0 + 1e-6: 186 | lut = lut / 255.0 187 | return lut.astype(np.float32) 188 | 189 | def load_lut(path: str) -> np.ndarray: 190 | """ 191 | Load a LUT from: 192 | - .npy (numpy saved array) 193 | - .cube (3D LUT) 194 | - image (PNG/JPG) that is a 1D LUT strip (common 256x1 or 1x256) 195 | Returns numpy array (1D, 2D, or 4D LUT). 196 | """ 197 | ext = os.path.splitext(path)[1].lower() 198 | if ext == '.npy': 199 | return np.load(path) 200 | elif ext == '.cube': 201 | return load_cube_lut(path) 202 | else: 203 | # try interpreting as image-based 1D LUT 204 | try: 205 | im = Image.open(path).convert('RGB') 206 | arr = np.array(im) 207 | h, w = arr.shape[:2] 208 | # 256x1 or 1x256 typical 1D LUT 209 | if (w == 256 and h == 1) or (h == 256 and w == 1): 210 | if h == 1: 211 | lut = arr[0, :, :].astype(np.float32) 212 | else: 213 | lut = arr[:, 0, :].astype(np.float32) 214 | return lut # shape (256,3) 215 | # sometimes embedded as 512x16 or other tile layouts; attempt to flatten 216 | # fallback: flatten and try to build (N,3) 217 | flat = arr.reshape(-1, 3).astype(np.float32) 218 | # if length is perfect power-of-two and <= 1024, assume 1D 219 | L = flat.shape[0] 220 | if L <= 4096: 221 | return flat # (L,3) 222 | raise ValueError("Image LUT not recognized size") 223 | except Exception as e: 224 | raise ValueError(f"Unsupported LUT file or parse error for {path}: {e}") 225 | -------------------------------------------------------------------------------- /image_postprocess/camera_pipeline.py: -------------------------------------------------------------------------------- 1 | """ 2 | camera_pipeline.py 3 | 4 | Functions for simulating a realistic camera pipeline, including Bayer mosaic/demosaic, 5 | chromatic aberration, vignette, sensor noise, hot pixels, banding, motion blur, and JPEG recompression. 6 | """ 7 | 8 | from io import BytesIO 9 | from PIL import Image 10 | import numpy as np 11 | try: 12 | import cv2 13 | _HAS_CV2 = True 14 | except Exception: 15 | cv2 = None 16 | _HAS_CV2 = False 17 | from scipy.ndimage import convolve 18 | 19 | def _bayer_mosaic(img: np.ndarray, pattern='RGGB') -> np.ndarray: 20 | """Create a single-channel Bayer mosaic from an RGB image. 21 | 22 | pattern currently supports 'RGGB' (most common). Returns uint8 2D array. 23 | """ 24 | h, w = img.shape[:2] 25 | mosaic = np.zeros((h, w), dtype=np.uint8) 26 | 27 | # pattern mapping for RGGB: 28 | # (0,0) R, (0,1) G 29 | # (1,0) G, (1,1) B 30 | R = img[:, :, 0] 31 | G = img[:, :, 1] 32 | B = img[:, :, 2] 33 | 34 | # fill mosaic according to RGGB 35 | mosaic[0::2, 0::2] = R[0::2, 0::2] 36 | mosaic[0::2, 1::2] = G[0::2, 1::2] 37 | mosaic[1::2, 0::2] = G[1::2, 0::2] 38 | mosaic[1::2, 1::2] = B[1::2, 1::2] 39 | return mosaic 40 | 41 | def _demosaic_bilinear(mosaic: np.ndarray) -> np.ndarray: 42 | """Simple bilinear demosaic fallback (no cv2). Outputs RGB uint8 image. 43 | 44 | Not perfect but good enough to add demosaic artifacts. 45 | """ 46 | h, w = mosaic.shape 47 | # Work in float to avoid overflow 48 | m = mosaic.astype(np.float32) 49 | 50 | # We'll compute each channel by averaging available mosaic samples 51 | R = np.zeros_like(m) 52 | G = np.zeros_like(m) 53 | B = np.zeros_like(m) 54 | 55 | # RGGB pattern 56 | R[0::2, 0::2] = m[0::2, 0::2] 57 | G[0::2, 1::2] = m[0::2, 1::2] 58 | G[1::2, 0::2] = m[1::2, 0::2] 59 | B[1::2, 1::2] = m[1::2, 1::2] 60 | 61 | # Convolution kernels for interpolation (simple) 62 | k_cross = np.array([[0, 1, 0], [1, 4, 1], [0, 1, 0]], dtype=np.float32) / 8.0 63 | k_diag = np.array([[1, 0, 1], [0, 0, 0], [1, 0, 1]], dtype=np.float32) / 4.0 64 | 65 | # convolve using scipy.ndimage.convolve 66 | R_interp = convolve(R, k_cross, mode='mirror') 67 | G_interp = convolve(G, k_cross, mode='mirror') 68 | B_interp = convolve(B, k_cross, mode='mirror') 69 | 70 | out = np.stack((R_interp, G_interp, B_interp), axis=2) 71 | out = np.clip(out, 0, 255).astype(np.uint8) 72 | return out 73 | 74 | def _apply_chromatic_aberration(img: np.ndarray, strength=1.0, seed=None): 75 | """Shift R and B channels slightly in opposite directions to emulate CA. 76 | 77 | strength is in pixels (float). Uses cv2.warpAffine if available; integer 78 | fallback uses np.roll. 79 | """ 80 | if seed is not None: 81 | rng = np.random.default_rng(seed) 82 | else: 83 | rng = np.random.default_rng() 84 | 85 | h, w = img.shape[:2] 86 | max_shift = max(1.0, strength) 87 | # small random subpixel shift sampled from normal distribution 88 | shift_r = rng.normal(loc=0.0, scale=max_shift * 0.6) 89 | shift_b = rng.normal(loc=0.0, scale=max_shift * 0.6) 90 | # apply opposite horizontal shifts to R and B for lateral CA 91 | r_x = shift_r 92 | r_y = rng.normal(scale=0.3 * abs(shift_r)) 93 | b_x = -shift_b 94 | b_y = rng.normal(scale=0.3 * abs(shift_b)) 95 | 96 | out = img.copy().astype(np.float32) 97 | if _HAS_CV2: 98 | def warp_channel(ch, tx, ty): 99 | M = np.array([[1, 0, tx], [0, 1, ty]], dtype=np.float32) 100 | return cv2.warpAffine(ch, M, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT) 101 | out[:, :, 0] = warp_channel(out[:, :, 0], r_x, r_y) 102 | out[:, :, 2] = warp_channel(out[:, :, 2], b_x, b_y) 103 | else: 104 | # integer fallback 105 | ix_r = int(round(r_x)) 106 | iy_r = int(round(r_y)) 107 | ix_b = int(round(b_x)) 108 | iy_b = int(round(b_y)) 109 | out[:, :, 0] = np.roll(out[:, :, 0], shift=(iy_r, ix_r), axis=(0, 1)) 110 | out[:, :, 2] = np.roll(out[:, :, 2], shift=(iy_b, ix_b), axis=(0, 1)) 111 | 112 | out = np.clip(out, 0, 255).astype(np.uint8) 113 | return out 114 | 115 | def _apply_vignette(img: np.ndarray, strength=0.4): 116 | h, w = img.shape[:2] 117 | y = np.linspace(-1, 1, h)[:, None] 118 | x = np.linspace(-1, 1, w)[None, :] 119 | r = np.sqrt(x * x + y * y) 120 | mask = 1.0 - (r ** 2) * strength 121 | mask = np.clip(mask, 0.0, 1.0) 122 | out = (img.astype(np.float32) * mask[:, :, None]) 123 | out = np.clip(out, 0, 255).astype(np.uint8) 124 | return out 125 | 126 | def _add_poisson_gaussian_noise(img: np.ndarray, iso_scale=1.0, read_noise_std=2.0, seed=None): 127 | """Poisson-Gaussian sensor noise model. 128 | 129 | iso_scale scales the signal before Poisson sampling (higher -> more Poisson), 130 | read_noise_std is the sigma (in DN) of additive Gaussian read noise. 131 | """ 132 | if seed is not None: 133 | rng = np.random.default_rng(seed) 134 | else: 135 | rng = np.random.default_rng() 136 | 137 | img_f = img.astype(np.float32) 138 | # scale to simulate exposure/iso 139 | scaled = img_f * iso_scale 140 | # Poisson: we need integer counts; scale to a reasonable photon budget 141 | # choose scale so that typical pixel values map to ~[0..2000] photons 142 | photon_scale = 4.0 143 | lam = np.clip(scaled * photon_scale, 0, 1e6) 144 | noisy = rng.poisson(lam).astype(np.float32) / photon_scale 145 | # add read noise 146 | noisy += rng.normal(loc=0.0, scale=read_noise_std, size=noisy.shape) 147 | noisy = np.clip(noisy, 0, 255).astype(np.uint8) 148 | return noisy 149 | 150 | def _add_hot_pixels_and_banding(img: np.ndarray, hot_pixel_prob=1e-6, banding_strength=0.0, seed=None): 151 | if seed is not None: 152 | rng = np.random.default_rng(seed) 153 | else: 154 | rng = np.random.default_rng() 155 | 156 | h, w = img.shape[:2] 157 | out = img.copy().astype(np.float32) 158 | # hot pixels 159 | n_pixels = int(h * w * hot_pixel_prob) 160 | if n_pixels > 0: 161 | ys = rng.integers(0, h, size=n_pixels) 162 | xs = rng.integers(0, w, size=n_pixels) 163 | vals = rng.integers(200, 256, size=n_pixels) 164 | for y, x, v in zip(ys, xs, vals): 165 | out[y, x, :] = v 166 | # banding: add low-amplitude sinusoidal horizontal banding 167 | if banding_strength > 0.0: 168 | rows = np.arange(h)[:, None] 169 | band = (np.sin(rows * 0.5) * 255.0 * banding_strength) 170 | out += band[:, :, None] 171 | out = np.clip(out, 0, 255).astype(np.uint8) 172 | return out 173 | 174 | def _motion_blur(img: np.ndarray, kernel_size=5): 175 | if kernel_size <= 1: 176 | return img 177 | # simple linear motion kernel horizontally 178 | kernel = np.zeros((kernel_size, kernel_size), dtype=np.float32) 179 | kernel[kernel_size // 2, :] = 1.0 / kernel_size 180 | out = np.zeros_like(img) 181 | for c in range(3): 182 | out[:, :, c] = convolve(img[:, :, c].astype(np.float32), kernel, mode='mirror') 183 | out = np.clip(out, 0, 255).astype(np.uint8) 184 | return out 185 | 186 | def _jpeg_recompress(img: np.ndarray, quality=90) -> np.ndarray: 187 | pil = Image.fromarray(img) 188 | buf = BytesIO() 189 | pil.save(buf, format='JPEG', quality=int(quality), optimize=False) 190 | buf.seek(0) 191 | rec = Image.open(buf).convert('RGB') 192 | return np.array(rec) 193 | 194 | def simulate_camera_pipeline(img_arr: np.ndarray, 195 | bayer=True, 196 | jpeg_cycles=1, 197 | jpeg_quality_range=(88, 96), 198 | vignette_strength=0.35, 199 | chroma_aberr_strength=1.2, 200 | iso_scale=1.0, 201 | read_noise_std=2.0, 202 | hot_pixel_prob=1e-6, 203 | banding_strength=0.0, 204 | motion_blur_kernel=1, 205 | seed=None): 206 | """Apply a set of realistic camera/capture artifacts to img_arr (RGB uint8). 207 | 208 | Returns an RGB uint8 image. 209 | """ 210 | if seed is not None: 211 | rng = np.random.default_rng(seed) 212 | else: 213 | rng = np.random.default_rng() 214 | 215 | out = img_arr.copy() 216 | 217 | # 1) Bayer mosaic + demosaic (if enabled) 218 | if bayer: 219 | try: 220 | mosaic = _bayer_mosaic(out[:, :, ::-1]) # we built mosaic assuming R,G,B order; send RGB 221 | if _HAS_CV2: 222 | # cv2 expects a single-channel Bayer and provides demosaicing codes 223 | # We'll use RGGB code (COLOR_BAYER_RG2BGR) so convert back to RGB after 224 | dem = cv2.demosaicing(mosaic, cv2.COLOR_BAYER_RG2BGR) 225 | # cv2 returns BGR 226 | dem = dem[:, :, ::-1] 227 | out = dem 228 | else: 229 | out = _demosaic_bilinear(mosaic) 230 | except Exception: 231 | # if anything fails, keep original 232 | out = img_arr.copy() 233 | 234 | # 2) chromatic aberration 235 | out = _apply_chromatic_aberration(out, strength=chroma_aberr_strength, seed=seed) 236 | 237 | # 3) vignette 238 | out = _apply_vignette(out, strength=vignette_strength) 239 | 240 | # 4) noise (Poisson-Gaussian) 241 | out = _add_poisson_gaussian_noise(out, iso_scale=iso_scale, read_noise_std=read_noise_std, seed=seed) 242 | 243 | # 5) hot pixels and banding 244 | out = _add_hot_pixels_and_banding(out, hot_pixel_prob=hot_pixel_prob, banding_strength=banding_strength, seed=seed) 245 | 246 | # 6) motion blur 247 | if motion_blur_kernel and motion_blur_kernel > 1: 248 | out = _motion_blur(out, kernel_size=motion_blur_kernel) 249 | 250 | # 7) JPEG recompression cycles 251 | for i in range(max(1, int(jpeg_cycles))): 252 | q = int(rng.integers(jpeg_quality_range[0], jpeg_quality_range[1] + 1)) 253 | out = _jpeg_recompress(out, quality=q) 254 | 255 | return out -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Utility functions for image processing GUI. 4 | """ 5 | 6 | from PyQt5.QtGui import QPixmap 7 | from PyQt5.QtCore import Qt 8 | from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas 9 | from matplotlib.figure import Figure 10 | from PIL import Image 11 | import numpy as np 12 | from concurrent.futures import ThreadPoolExecutor 13 | 14 | def qpixmap_from_path(p: str, max_size=(480, 360)) -> QPixmap: 15 | """ 16 | Load an image from a path into a QPixmap, scaled to a maximum size. 17 | 18 | Parameters: 19 | - p (str): The file path of the image. 20 | - max_size (tuple): A tuple (width, height) for the maximum dimensions. 21 | 22 | Returns: 23 | - QPixmap: The scaled pixmap. Returns an empty QPixmap if the path is invalid. 24 | """ 25 | pix = QPixmap(p) 26 | if pix.isNull(): 27 | return QPixmap() 28 | w, h = max_size 29 | return pix.scaled(w, h, Qt.KeepAspectRatio, Qt.SmoothTransformation) 30 | 31 | def make_canvas(width=4, height=3, dpi=100): 32 | """ 33 | Create a Matplotlib canvas and axes for embedding in a PyQt GUI. 34 | 35 | Parameters: 36 | - width (int): The width of the figure in inches. 37 | - height (int): The height of the figure in inches. 38 | - dpi (int): The resolution of the figure in dots per inch. 39 | 40 | Returns: 41 | - tuple: A tuple containing the FigureCanvas and the Axes object (canvas, ax). 42 | """ 43 | fig = Figure(figsize=(width, height), dpi=dpi) 44 | canvas = FigureCanvas(fig) 45 | ax = fig.add_subplot(111) 46 | fig.tight_layout() 47 | return canvas, ax 48 | 49 | def compute_gray_array(path): 50 | """ 51 | Open an image, convert it to grayscale, and return it as a NumPy array. 52 | 53 | The conversion uses the luminosity method: Y = 0.299*R + 0.587*G + 0.114*B. 54 | 55 | Parameters: 56 | - path (str): The file path of the image. 57 | 58 | Returns: 59 | - np.ndarray: A 2D NumPy array of type float32 representing the grayscale image. 60 | """ 61 | img = Image.open(path).convert('RGB') 62 | arr = np.array(img) 63 | gray = (0.299 * arr[:, :, 0] + 0.587 * arr[:, :, 1] + 0.114 * arr[:, :, 2]).astype(np.float32) 64 | return gray 65 | 66 | def compute_fft_magnitude(gray_arr, eps=1e-8): 67 | """ 68 | Compute the 2D FFT magnitude spectrum of a grayscale image. 69 | 70 | This function calculates the Fast Fourier Transform, shifts the zero-frequency 71 | component to the center, and returns both the absolute magnitude and a 72 | log-scaled version for better visualization. 73 | 74 | Parameters: 75 | - gray_arr (np.ndarray): The input 2D grayscale image array. 76 | - eps (float): A small epsilon value (currently unused in the implementation). 77 | 78 | Returns: 79 | - tuple: A tuple containing: 80 | - mag (np.ndarray): The centered FFT magnitude spectrum. 81 | - mag_log (np.ndarray): The log-scaled magnitude spectrum (log(1 + mag)). 82 | """ 83 | f = np.fft.fft2(gray_arr) 84 | fshift = np.fft.fftshift(f) 85 | mag = np.abs(fshift) 86 | mag_log = np.log1p(mag) 87 | return mag, mag_log 88 | 89 | def radial_profile(mag, center=None, nbins=100): 90 | """ 91 | Compute the radially averaged profile of a 2D array (e.g., FFT magnitude). 92 | 93 | This calculates the average value in concentric rings starting from a center point. 94 | 95 | Parameters: 96 | - mag (np.ndarray): The 2D input array. 97 | - center (tuple, optional): The (y, x) coordinates of the center. If None, 98 | the geometric center of the array is used. 99 | - nbins (int): The number of radial bins to use. 100 | 101 | Returns: 102 | - tuple: A tuple containing: 103 | - centers (np.ndarray): The normalized radial distance for each bin (0 to 1). 104 | - radial_mean (np.ndarray): The mean value for each radial bin. 105 | """ 106 | h, w = mag.shape 107 | if center is None: 108 | center = (int(h / 2), int(w / 2)) 109 | y, x = np.indices((h, w)) 110 | r = np.sqrt((x - center[1]) ** 2 + (y - center[0]) ** 2) 111 | r_flat = r.ravel() 112 | mag_flat = mag.ravel() 113 | max_r = np.max(r_flat) 114 | if max_r <= 0: 115 | return np.linspace(0, 1, nbins), np.zeros(nbins) 116 | bins = np.linspace(0, max_r, nbins + 1) 117 | inds = np.digitize(r_flat, bins) - 1 118 | radial_mean = np.zeros(nbins) 119 | for i in range(nbins): 120 | sel = inds == i 121 | if np.any(sel): 122 | radial_mean[i] = mag_flat[sel].mean() 123 | else: 124 | radial_mean[i] = 0.0 125 | centers = 0.5 * (bins[:-1] + bins[1:]) / max_r 126 | return centers, radial_mean 127 | 128 | 129 | def compute_glcm(gray_arr, levels=8, offsets=[(0, 1), (1, 0), (1, 1), (-1, 1)], eps=1e-8): 130 | """ 131 | Vectorized Gray-Level Co-occurrence Matrix (GLCM) computation. 132 | 133 | Replaces per-pixel Python loops with NumPy-indexed operations and 134 | np.bincount to accumulate co-occurrence counts. This yields large 135 | speedups for typical image sizes. 136 | """ 137 | # Quantize grayscale image to 'levels' bins 138 | gray = gray_arr.astype(np.float32) 139 | gray_min, gray_max = gray.min(), gray.max() 140 | if gray_max > gray_min: 141 | gray_quant = np.floor((gray - gray_min) / (gray_max - gray_min + eps) * (levels - 1)).astype(np.int32) 142 | else: 143 | gray_quant = np.zeros_like(gray, dtype=np.int32) 144 | 145 | h, w = gray_quant.shape 146 | glcm = np.zeros((levels, levels, len(offsets)), dtype=np.float32) 147 | features = { 148 | 'contrast': np.zeros(len(offsets), dtype=np.float32), 149 | 'correlation': np.zeros(len(offsets), dtype=np.float32), 150 | 'energy': np.zeros(len(offsets), dtype=np.float32), 151 | 'homogeneity': np.zeros(len(offsets), dtype=np.float32) 152 | } 153 | 154 | # Precompute index grids 155 | rows, cols = np.indices((h, w)) 156 | 157 | # Precompute i,j matrices for feature computation 158 | i_idx = np.arange(levels).reshape(levels, 1) 159 | j_idx = np.arange(levels).reshape(1, levels) 160 | 161 | for k, (dy, dx) in enumerate(offsets): 162 | r2 = rows + dy 163 | c2 = cols + dx 164 | valid = (r2 >= 0) & (r2 < h) & (c2 >= 0) & (c2 < w) 165 | if not np.any(valid): 166 | continue 167 | 168 | q1 = gray_quant[rows[valid], cols[valid]] 169 | q2 = gray_quant[r2[valid], c2[valid]] 170 | 171 | # Flatten pair indices to accumulate with bincount (fast C loop) 172 | pairs = q1 * levels + q2 173 | counts = np.bincount(pairs, minlength=levels * levels).astype(np.float32) 174 | glcm_k = counts.reshape((levels, levels)) 175 | 176 | # Normalize 177 | total = glcm_k.sum() 178 | if total > 0: 179 | glcm_k /= total 180 | 181 | # Features 182 | contrast = np.sum((i_idx - j_idx) ** 2 * glcm_k) 183 | mu_i = np.sum(i_idx * glcm_k) 184 | mu_j = np.sum(j_idx * glcm_k) 185 | sigma_i = np.sqrt(np.sum((i_idx - mu_i) ** 2 * glcm_k) + eps) 186 | sigma_j = np.sqrt(np.sum((j_idx - mu_j) ** 2 * glcm_k) + eps) 187 | if sigma_i > 0 and sigma_j > 0: 188 | correlation = np.sum((i_idx - mu_i) * (j_idx - mu_j) * glcm_k) / (sigma_i * sigma_j) 189 | else: 190 | correlation = 0.0 191 | energy = np.sum(glcm_k ** 2) 192 | homogeneity = np.sum(glcm_k / (1.0 + np.abs(i_idx - j_idx) + eps)) 193 | 194 | glcm[:, :, k] = glcm_k 195 | features['contrast'][k] = contrast 196 | features['correlation'][k] = correlation 197 | features['energy'][k] = energy 198 | features['homogeneity'][k] = homogeneity 199 | 200 | return glcm, features 201 | 202 | 203 | # ---------------------- Optimized LBP ---------------------- 204 | 205 | def compute_lbp(gray_arr, radius=1, n_points=8, eps=1e-8): 206 | """ 207 | Vectorized Local Binary Pattern (uniform, rotation-invariant). 208 | 209 | Uses NumPy operations to sample all neighbor points at once and 210 | build LBP codes without explicit per-pixel Python loops. 211 | """ 212 | gray = gray_arr.astype(np.float32) 213 | h, w = gray.shape 214 | 215 | # Pad to avoid boundary checks during interpolation 216 | pad = int(np.ceil(radius)) + 1 217 | padded = np.pad(gray, pad_width=pad, mode='edge') 218 | 219 | # Center coordinates in padded image 220 | Y, X = np.indices((h, w)) 221 | Y = Y + pad 222 | X = X + pad 223 | 224 | angles = np.linspace(0, 2 * np.pi, n_points, endpoint=False) 225 | lbp = np.zeros((h, w), dtype=np.uint32) 226 | 227 | for k, theta in enumerate(angles): 228 | # Note: y increases downward in image coordinates 229 | dy = -radius * np.sin(theta) 230 | dx = radius * np.cos(theta) 231 | 232 | sample_y = Y.astype(np.float32) + dy 233 | sample_x = X.astype(np.float32) + dx 234 | 235 | # Bilinear interpolation indices and weights 236 | y0 = np.floor(sample_y).astype(np.int32) 237 | x0 = np.floor(sample_x).astype(np.int32) 238 | y1 = y0 + 1 239 | x1 = x0 + 1 240 | 241 | wy = sample_y - y0 242 | wx = sample_x - x0 243 | 244 | # Gather values 245 | v00 = padded[y0, x0] 246 | v10 = padded[y1, x0] 247 | v01 = padded[y0, x1] 248 | v11 = padded[y1, x1] 249 | 250 | vals = (1 - wy) * (1 - wx) * v00 + wy * (1 - wx) * v10 + (1 - wy) * wx * v01 + wy * wx * v11 251 | 252 | # Compare with center 253 | center = padded[Y, X] 254 | bit = (vals >= center).astype(np.uint32) 255 | lbp |= (bit << k) 256 | 257 | # Map to rotation-invariant uniform patterns 258 | n_codes = 1 << n_points 259 | codes = np.arange(n_codes, dtype=np.uint32) 260 | bits = ((codes[:, None] >> np.arange(n_points)) & 1).astype(np.uint8) 261 | transitions = np.sum(bits != np.roll(bits, -1, axis=1), axis=1) 262 | uniform_mask = transitions <= 2 263 | 264 | lbp_map = np.full(n_codes, n_points + 1, dtype=np.int32) 265 | lbp_map[uniform_mask] = np.arange(np.count_nonzero(uniform_mask), dtype=np.int32)[np.argsort(np.nonzero(uniform_mask)[0])] 266 | # The above ensures uniform codes get unique indices from 0..(num_uniform-1) 267 | 268 | lbp_mapped = lbp_map[lbp] 269 | 270 | n_bins = lbp_map.max() + 1 271 | hist = np.bincount(lbp_mapped.ravel(), minlength=n_bins).astype(np.float32) 272 | hist /= (hist.sum() + eps) 273 | 274 | return lbp_mapped, hist 275 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Image Detection Bypass Utility 2 | 3 | Circumvention of AI Detection — all wrapped in a clean, user-friendly interface. 4 | 5 | ![MIT License](https://img.shields.io/badge/License-MIT-green.svg) 6 | ![Python 3.13](https://img.shields.io/badge/Python-3.13-yellow) 7 | ![PyQt5](https://img.shields.io/badge/PyQt5-latest-blue) 8 | ![Pillow](https://img.shields.io/badge/Pillow-latest-lightgrey) 9 | ![NumPy](https://img.shields.io/badge/NumPy-latest-lightgrey) 10 | ![Matplotlib](https://img.shields.io/badge/Matplotlib-latest-lightgrey) 11 | ![piexif](https://img.shields.io/badge/piexif-latest-lightgrey) 12 | ![SciPy](https://img.shields.io/badge/SciPy-latest-lightgrey) 13 | ![OpenCV](https://img.shields.io/badge/OpenCV-latest-darkgreen) 14 | ![Torch 2.8.0+cu126](https://img.shields.io/badge/Torch-2.8.0%2Bcu126-red) 15 | ![TorchVision 0.23.0+cu126](https://img.shields.io/badge/TorchVision-0.23.0%2Bcu126-orange) 16 | 17 | 18 | --- 19 | 20 | ## Screenshot 21 | 22 | ![Screenshot](https://i.imgur.com/y0tuDcK.png) 23 | 24 | ## Notice 25 | Due to the nature of this project, future updates will be under AGPL V3 license to ensure this project and its derivatives remains Open Source. 26 | 27 | ## Features 28 | 29 | * Select input, optional auto white-balance reference, optional FFT reference, and output paths with live previews. 30 | * **Auto Mode**: one slider to control an expressive preset of postprocess parameters. 31 | * **Manual Mode**: full access to noise, CLAHE, FFT, phase perturbation, pixel perturbation, etc. 32 | * Camera pipeline simulator: Bayer/demosaic, JPEG cycles/quality, vignette, chromatic aberration, motion blur, hot pixels, read-noise, banding. 33 | * Input / output analysis panels (via `AnalysisPanel`) to inspect images before/after processing. 34 | * Background worker thread with progress reporting and rich error dialog (traceback viewer). 35 | 36 | --- 37 | 38 | ## ComfyUI Integration 39 | 40 | ![Screenshot](https://i.imgur.com/KzjEfxf.png) 41 | 42 | Use ComfyUI Manager and install via GitHub link. 43 | Or manually clone to custom\_nodes folder. 44 | 45 | ```bash 46 | git clone https://github.com/PurinNyova/Image-Detection-Bypass-Utility 47 | ``` 48 | 49 | then 50 | 51 | ```bash 52 | cd Image-Detection-Bypass-Utility 53 | pip install -r requirements.txt 54 | ``` 55 | 56 | Thanks to u/Race88 for the help on the ComfyUI code. 57 | 58 | ### Requirements 59 | 60 | * Python 3.8+ recommended 61 | * PyPI packages: 62 | 63 | ```bash 64 | pip install pyqt5 pillow numpy matplotlib piexif lpips 65 | # optional but recommended for extra functionality: 66 | pip install opencv-python 67 | # optional but needed for AI Normalizer (Install CPU OR Cuda) 68 | #Torch Cuda 12.6 69 | pip install torch torchvision --index-url https://download.pytorch.org/whl/cu126 70 | #Torch CPU 71 | pip install torch torchvision 72 | 73 | ``` 74 | 75 | OR 76 | 77 | ```bash 78 | pip install -r requirements.txt 79 | ``` 80 | 81 | ### Files expected in the same folder 82 | 83 | * `image_postprocess` — your processing logic (export `process_image(...)` or compatible API). 84 | * `worker.py` — Worker thread wrapper used to run the pipeline in background. 85 | * `analysis_panel.py` — UI widget used for input/output analysis. 86 | * `utils.py` — must provide `qpixmap_from_path(path, max_size=(w,h))`. 87 | 88 | ### Run 89 | 90 | ```bash 91 | python run.py 92 | 93 | # Alternatively, if you're having issues, a "run.sh" script has been created that will also install dependencies 94 | # properly and run the GUI 95 | ./run.sh # also installs dependencies before running `python run.py` 96 | ``` 97 | 98 | --- 99 | 100 | ## Using the GUI (at-a-glance) 101 | 102 | 1. **Choose Input** — opens file dialog; sets suggested output path automatically. 103 | 2. *(optional)* **Choose Reference** — used for FFT/color reference (OpenCV-based color match supported). 104 | 3. *(optional)* **Choose Auto White-Balance Reference** — used for auto white-balance correction (applied before CLAHE). 105 | 4. **Choose Output** — where processed image will be written. 106 | 5. **Auto Mode** — enable for a single slider to control a bundled preset. 107 | 6. **Manual Mode** — tune individual parameters in the Parameters group. 108 | 7. **Camera Simulator** — enable to reveal camera-specific controls (Bayer, JPEG cycles, vignette, chroma, etc.). 109 | 8. Click **Run — Process Image** to start. The GUI disables controls while running and shows progress. 110 | 9. When finished, the output preview and Output analysis panel update automatically. 111 | 112 | --- 113 | 114 | ## Parameter Explanation 115 | 116 | This section documents every manual parameter exposed by the GUI and gives guidance for usage. 117 | 118 | --- 119 | 120 | ## Manual Parameters 121 | 122 | When **Auto Mode** is disabled, you can fine-tune the image post-processing pipeline manually using the following parameters: 123 | 124 | ### Noise & Contrast 125 | 126 | * **Noise std (0–0.1)** 127 | Standard deviation of Gaussian noise applied to the image. Higher values introduce more noise, useful for simulating sensor artifacts. 128 | 129 | * **CLAHE clip** 130 | Clip limit for Contrast Limited Adaptive Histogram Equalization (CLAHE). Controls the amount of contrast enhancement. 131 | 132 | * **CLAHE tile** 133 | Number of tiles used in CLAHE grid. Larger values give finer local contrast adjustments. 134 | 135 | --- 136 | 137 | ### Fourier Domain Controls 138 | 139 | * **Fourier cutoff (0–1)** 140 | Frequency cutoff threshold. Lower values preserve only low frequencies (smoothing), higher values retain more high-frequency detail. 141 | 142 | * **Fourier strength (0–1)** 143 | Blending ratio for Fourier-domain filtering. At 1.0, full effect is applied; at 0.0, no effect. 144 | 145 | * **Fourier randomness** 146 | Amount of stochastic variation introduced in the Fourier transform domain to simulate non-uniform distortions. 147 | 148 | * **Phase perturb (rad)** 149 | Random perturbation of phase in the Fourier spectrum, measured in radians. Adds controlled irregularity to frequency response. 150 | 151 | * **Radial smooth (bins)** 152 | Number of bins used for radial frequency smoothing. Higher values smooth the frequency response more aggressively. 153 | 154 | * **FFT mode** 155 | Mode selection for FFT-based processing (e.g., `auto`, `ref`, `model`). 156 | `auto` will choose the most appropriate mode automatically. 157 | `ref` uses your FFT reference image as a reference. 158 | `model` uses a preset mathematical formula to find a natural FFT spectrum. 159 | 160 | * **FFT alpha (model)** 161 | Scaling factor for FFT filtering. Controls how strongly frequency components are weighted. Only affects model mode. 162 | 163 | --- 164 | 165 | ### Pixel-Level Perturbations 166 | 167 | * **Pixel perturb** 168 | Standard deviation of per-pixel perturbations applied in the spatial domain. Adds small jitter to pixel intensities. 169 | 170 | --- 171 | 172 | ### Texture-based Normalization (GLCM) 173 | 174 | * **What it is** — Gray-Level Co-occurrence Matrix (GLCM) features capture second-order texture statistics (how often pairs of gray levels occur at specified distances and angles). GLCM normalization aims to match these texture statistics between the input and an FFT reference image, producing more realistic-looking sensor/textural artifacts. 175 | 176 | * **When to use** — Use GLCM when the goal is to emulate or match textural properties (fine-grain patterns, structural noise) of a reference image. It is complementary to Fourier-domain matching: FFT shapes the spectral envelope while GLCM shapes spatial texture statistics. 177 | 178 | * **Controls** 179 | 180 | * **Distances** — distance(s) in pixels used when building GLCM (default `[1]`). Use larger distances to capture coarser texture. 181 | * **Angles** — angles (radians) for directional co-occurrence (default `[0, π/4, π/2, 3π/4]`). More angles give rotation-robust matching. 182 | * **Levels** — number of quantized gray levels used for GLCM (default `256`). Lower values are faster and smooth the texture statistics. 183 | * **Strength** — blending factor (0..1) controlling how strongly GLCM features from the reference influence the output (default `0.9`). Lower values apply subtler texture matching. 184 | 185 | * **Practical tips** 186 | 187 | * Combine moderate `glcm_strength` (0.4–0.8) with FFT matching for subtle realism. 188 | * Use fewer `glcm_levels` (e.g., 64 or 32) for speed and to avoid overfitting to noisy reference images. 189 | 190 | --- 191 | 192 | ### Local Binary Patterns (LBP) 193 | 194 | * **What it is** — Local Binary Patterns encode a small neighbourhood around each pixel as a binary pattern, creating histograms that are very effective at characterizing micro-texture and local structure. 195 | 196 | * **When to use** — LBP histogram matching is useful when you want to replicate micro-textural characteristics like sensor grain, cloth weave, or repetitive fine structure from a reference image. 197 | 198 | * **Controls** 199 | 200 | * **Radius** — radius of the circular neighbourhood (in pixels) used to compute LBP (default `3`). Larger radii capture coarser patterns. 201 | * **N points** — number of sampling points around the circle (default `24`). More points increase descriptor resolution. 202 | * **Method** — one of `default`, `ror` (rotation invariant), `uniform` (compact uniform patterns), or `var` (variance-based). Use `uniform` for compact, robust histograms by default. 203 | * **Strength** — blending factor (0..1) controlling how strongly the LBP histogram from the reference influences the output (default `0.9`). 204 | 205 | * **Practical tips** 206 | 207 | * Use `lbp_method='uniform'` and `lbp_n_points` 8–24 for stable results across natural images. 208 | * Decrease `lbp_strength` for subtle grain matching; increase it if the output needs to closely follow the reference micro-texture. 209 | 210 | --- 211 | 212 | ### Randomization 213 | 214 | * **Seed (0=none)** 215 | Random seed for reproducibility. 216 | 217 | * `0` → fully random each run 218 | * Any other integer → deterministic output for given settings 219 | 220 | --- 221 | 222 | Use these parameters to experiment with different looks. 223 | 224 | Generally: 225 | For **Minimum destructiveness**, keep noise and perturb values low. 226 | For **Increased Evation**, increase Fourier randomness, Fourier Strength, phase perturb, and pixel perturb. 227 | 228 | --- 229 | 230 | ## AI Normalizer 231 | 232 | When enabled, the AI Normalizer applies a non-semantic attack using PyTorch and LPIPS to subtly modify the image without introducing perceptible artifacts. The following parameters control its behavior: 233 | 234 | * **Iterations** — Number of optimization steps to perform. 235 | * **Learning Rate** — Step size for the optimizer. 236 | * **T LPIPS** — Threshold for the LPIPS perceptual loss. If the LPIPS loss exceeds this threshold, it is penalized. 237 | * **T L2** — Threshold for the L2 loss on the perturbation. 238 | * **C LPIPS** — Weighting factor for the LPIPS loss penalty. 239 | * **C L2** — Weighting factor for the L2 loss penalty. 240 | * **Gradient Clip** — Maximum allowed gradient value during optimization to prevent exploding gradients. 241 | 242 | --- 243 | 244 | ## Contributing 245 | 246 | * PRs welcome. If you modify UI layout or parameter names, keep the `args` mapping consistent or update `README` and `worker.py` accordingly. 247 | * Add unit tests for `worker.py` and the parameter serialization if you intend to refactor. 248 | 249 | --- 250 | 251 | ## Paper Used 252 | 253 | This project credits and draws inspiration from: 254 | 255 | **UnMarker: A Universal Attack on Defensive Image Watermarking** 256 | Andre Kassis, Urs Hengartner 257 | 258 | ## License 259 | 260 | MIT — free to use and adapt. Please include attribution if you fork or republish. 261 | 262 | --- 263 | -------------------------------------------------------------------------------- /image_postprocess/processor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | processor.py 4 | 5 | Main pipeline for image postprocessing with an optional realistic camera-pipeline simulator. 6 | Added support for applying 1D PNG/.npy LUTs and .cube 3D LUTs via --lut. 7 | Added GLCM and LBP normalization using the same reference as FFT. 8 | """ 9 | 10 | import argparse 11 | import os 12 | from PIL import Image 13 | import numpy as np 14 | import piexif 15 | from datetime import datetime 16 | 17 | from .utils import ( 18 | add_gaussian_noise, 19 | clahe_color_correction, 20 | randomized_perturbation, 21 | fourier_match_spectrum, 22 | auto_white_balance_ref, 23 | load_lut, 24 | apply_lut, 25 | glcm_normalize, 26 | lbp_normalize, 27 | attack_non_semantic, 28 | blend_colors 29 | 30 | ) 31 | from .camera_pipeline import simulate_camera_pipeline 32 | 33 | 34 | def add_fake_exif(): 35 | """ 36 | Generates a plausible set of fake EXIF data. 37 | Returns: 38 | bytes: The EXIF data as a byte string, ready for insertion. 39 | """ 40 | now = datetime.now() 41 | datestamp = now.strftime("%Y:%m:%d %H:%M:%S") 42 | 43 | zeroth_ifd = { 44 | piexif.ImageIFD.Make: b"PurinCamera", 45 | piexif.ImageIFD.Model: b"Model420X", 46 | piexif.ImageIFD.Software: b"NovaImageProcessor", 47 | piexif.ImageIFD.DateTime: datestamp.encode('utf-8'), 48 | } 49 | exif_ifd = { 50 | piexif.ExifIFD.DateTimeOriginal: datestamp.encode('utf-8'), 51 | piexif.ExifIFD.DateTimeDigitized: datestamp.encode('utf-8'), 52 | piexif.ExifIFD.ExposureTime: (1, 125), # 1/125s 53 | piexif.ExifIFD.FNumber: (28, 10), # F/2.8 54 | piexif.ExifIFD.ISOSpeedRatings: 200, 55 | piexif.ExifIFD.FocalLength: (50, 1), # 50mm 56 | } 57 | gps_ifd = {} 58 | 59 | exif_dict = {"0th": zeroth_ifd, "Exif": exif_ifd, "GPS": gps_ifd, "1st": {}, "thumbnail": None} 60 | exif_bytes = piexif.dump(exif_dict) 61 | return exif_bytes 62 | 63 | 64 | def process_image(path_in, path_out, args): 65 | img = Image.open(path_in).convert('RGB') 66 | arr = np.array(img) 67 | 68 | # Load FFT reference independently (used for FFT, GLCM, and LBP) 69 | ref_arr_fft = None 70 | if args.fft_ref: 71 | try: 72 | ref_img_fft = Image.open(args.fft_ref).convert('RGB') 73 | ref_arr_fft = np.array(ref_img_fft) 74 | except Exception as e: 75 | print(f"Warning: failed to load FFT reference '{args.fft_ref}': {e}. Skipping FFT reference matching.") 76 | ref_arr_fft = None 77 | 78 | # blend system 79 | if args.blend: 80 | try: 81 | arr = blend_colors(arr, tolerance=args.blend_tolerance, min_region_size=args.blend_min_region, 82 | max_kmeans_samples=args.blend_max_samples, n_jobs=args.blend_n_jobs) 83 | except Exception as e: 84 | print(f"Warning: Blending failed: {e}. Skipping blending.") 85 | 86 | # --- Non-semantic attack (if enabled) executed first --- 87 | if args.non_semantic: 88 | print("Applying non-semantic attack...") 89 | try: 90 | arr = attack_non_semantic( 91 | arr, 92 | iterations=args.ns_iterations, 93 | learning_rate=args.ns_learning_rate, 94 | t_lpips=args.ns_t_lpips, 95 | t_l2=args.ns_t_l2, 96 | c_lpips=args.ns_c_lpips, 97 | c_l2=args.ns_c_l2, 98 | grad_clip_value=args.ns_grad_clip 99 | ) 100 | except Exception as e: 101 | print(f"Warning: Non-semantic attack failed: {e}. Skipping non-semantic attack.") 102 | 103 | # --- CLAHE color correction (if enabled) --- 104 | if args.clahe: 105 | arr = clahe_color_correction(arr, clip_limit=args.clahe_clip, tile_grid_size=(args.tile, args.tile)) 106 | 107 | # --- FFT spectral matching (if enabled) --- 108 | if args.fft: 109 | arr = fourier_match_spectrum(arr, ref_img_arr=ref_arr_fft, mode=args.fft_mode, 110 | alpha=args.fft_alpha, cutoff=args.cutoff, 111 | strength=args.fstrength, randomness=args.randomness, 112 | phase_perturb=args.phase_perturb, radial_smooth=args.radial_smooth, 113 | seed=args.seed) 114 | 115 | # GLCM normalization 116 | if args.glcm: 117 | arr = glcm_normalize(arr, ref_img_arr=ref_arr_fft, distances=args.glcm_distances, 118 | angles=args.glcm_angles, levels=args.glcm_levels, 119 | strength=args.glcm_strength, seed=args.seed) 120 | 121 | # LBP normalization 122 | if args.lbp: 123 | arr = lbp_normalize(arr, ref_img_arr=ref_arr_fft, radius=args.lbp_radius, 124 | n_points=args.lbp_n_points, method=args.lbp_method, 125 | strength=args.lbp_strength, seed=args.seed) 126 | 127 | # Gaussian noise addition 128 | if args.noise: 129 | arr = add_gaussian_noise(arr, std_frac=args.noise_std, seed=args.seed) 130 | 131 | # Randomized perturbation 132 | if args.perturb: 133 | arr = randomized_perturbation(arr, magnitude_frac=args.perturb_magnitude, seed=args.seed) 134 | 135 | # call the camera simulator if requested 136 | if args.sim_camera: 137 | arr = simulate_camera_pipeline(arr, 138 | bayer=not args.no_no_bayer, 139 | jpeg_cycles=args.jpeg_cycles, 140 | jpeg_quality_range=(args.jpeg_qmin, args.jpeg_qmax), 141 | vignette_strength=args.vignette_strength, 142 | chroma_aberr_strength=args.chroma_strength, 143 | iso_scale=args.iso_scale, 144 | read_noise_std=args.read_noise, 145 | hot_pixel_prob=args.hot_pixel_prob, 146 | banding_strength=args.banding_strength, 147 | motion_blur_kernel=args.motion_blur_kernel, 148 | seed=args.seed) 149 | 150 | # --- Auto white-balance (if enabled) --- 151 | if args.awb: 152 | if args.ref: 153 | try: 154 | ref_img_awb = Image.open(args.ref).convert('RGB') 155 | ref_arr_awb = np.array(ref_img_awb) 156 | arr = auto_white_balance_ref(arr, ref_arr_awb) 157 | except Exception as e: 158 | print(f"Warning: failed to load AWB reference '{args.ref}': {e}. Skipping AWB.") 159 | else: 160 | print("Applying AWB using grey-world assumption...") 161 | arr = auto_white_balance_ref(arr, None) 162 | 163 | # LUT application 164 | if args.lut: 165 | try: 166 | lut = load_lut(args.lut) 167 | arr_uint8 = np.clip(arr, 0, 255).astype(np.uint8) 168 | arr_lut = apply_lut(arr_uint8, lut, strength=args.lut_strength) 169 | arr = np.clip(arr_lut, 0, 255).astype(np.uint8) 170 | except Exception as e: 171 | print(f"Warning: failed to load/apply LUT '{args.lut}': {e}. Skipping LUT.") 172 | 173 | out_img = Image.fromarray(arr) 174 | 175 | # Generate fake EXIF data and save it with the image 176 | fake_exif_bytes = add_fake_exif() 177 | out_img.save(path_out, exif=fake_exif_bytes) 178 | 179 | 180 | def build_argparser(): 181 | p = argparse.ArgumentParser(description="Image postprocessing pipeline with camera simulation, LUT support, GLCM, and LBP normalization") 182 | p.add_argument('input', help='Input image path') 183 | p.add_argument('output', help='Output image path') 184 | 185 | # AWB Options 186 | p.add_argument('--awb', action='store_true', default=False, help='Enable automatic white balancing. Uses grey-world if --ref is not provided.') 187 | p.add_argument('--ref', help='Optional reference image for auto white-balance (only used if --awb is enabled)', default=None) 188 | 189 | p.add_argument('--noise-std', type=float, default=0.02, help='Gaussian noise std fraction of 255 (0-0.1)') 190 | p.add_argument('--clahe-clip', type=float, default=2.0, help='CLAHE clip limit') 191 | p.add_argument('--tile', type=int, default=8, help='CLAHE tile grid size') 192 | p.add_argument('--cutoff', type=float, default=0.25, help='Fourier cutoff (0..1)') 193 | p.add_argument('--fstrength', type=float, default=0.9, help='Fourier blend strength (0..1)') 194 | p.add_argument('--randomness', type=float, default=0.05, help='Randomness for Fourier mask modulation') 195 | p.add_argument('--seed', type=int, default=None, help='Random seed for reproducibility') 196 | 197 | # FFT-matching options 198 | p.add_argument('--fft-ref', help='Optional reference image for FFT spectral matching, GLCM, and LBP', default=None) 199 | p.add_argument('--fft-mode', choices=('auto','ref','model'), default='auto', help='FFT mode: auto picks ref if available') 200 | p.add_argument('--fft-alpha', type=float, default=1.0, help='Alpha for 1/f model (spectrum slope)') 201 | p.add_argument('--phase-perturb', type=float, default=0.08, help='Phase perturbation strength (radians)') 202 | p.add_argument('--radial-smooth', type=int, default=5, help='Radial smoothing (bins) for spectrum profiles') 203 | 204 | # GLCM normalization options 205 | p.add_argument('--glcm', action='store_true', default=False, help='Enable GLCM normalization using FFT reference if available') 206 | p.add_argument('--glcm-distances', type=int, nargs='+', default=[1], help='Distances for GLCM computation') 207 | p.add_argument('--glcm-angles', type=float, nargs='+', default=[0, np.pi/4, np.pi/2, 3*np.pi/4], help='Angles for GLCM computation (in radians)') 208 | p.add_argument('--glcm-levels', type=int, default=256, help='Number of gray levels for GLCM') 209 | p.add_argument('--glcm-strength', type=float, default=0.9, help='Strength of GLCM feature matching (0..1)') 210 | 211 | # LBP normalization options 212 | p.add_argument('--lbp', action='store_true', default=False, help='Enable LBP normalization using FFT reference if available') 213 | p.add_argument('--lbp-radius', type=int, default=3, help='Radius of LBP operator') 214 | p.add_argument('--lbp-n-points', type=int, default=24, help='Number of circularly symmetric neighbor set points for LBP') 215 | p.add_argument('--lbp-method', choices=('default', 'ror', 'uniform', 'var'), default='uniform', help='LBP method') 216 | p.add_argument('--lbp-strength', type=float, default=0.9, help='Strength of LBP histogram matching (0..1)') 217 | 218 | # Non-semantic attack options 219 | p.add_argument('--non-semantic', action='store_true', default=False, help='Apply non-semantic attack on the image') 220 | p.add_argument('--ns-iterations', type=int, default=500, help='Iterations for non-semantic attack') 221 | p.add_argument('--ns-learning-rate', type=float, default=3e-4, help='Learning rate for non-semantic attack') 222 | p.add_argument('--ns-t-lpips', type=float, default=4e-2, help='LPIPS threshold for non-semantic attack') 223 | p.add_argument('--ns-t-l2', type=float, default=3e-5, help='L2 threshold for non-semantic attack') 224 | p.add_argument('--ns-c-lpips', type=float, default=1e-2, help='LPIPS constant for non-semantic attack') 225 | p.add_argument('--ns-c-l2', type=float, default=0.6, help='L2 constant for non-semantic attack') 226 | p.add_argument('--ns-grad-clip', type=float, default=0.05, help='Gradient clipping value for non-semantic attack') 227 | 228 | # Camera-simulator options 229 | p.add_argument('--sim-camera', action='store_true', default=False, help='Enable camera-pipeline simulation (Bayer, CA, vignette, JPEG cycles)') 230 | p.add_argument('--no-no-bayer', dest='no_no_bayer', action='store_false', help='Disable Bayer/demosaic step (double negative kept for backward compat)') 231 | p.set_defaults(no_no_bayer=True) 232 | p.add_argument('--jpeg-cycles', type=int, default=1, help='Number of JPEG recompression cycles to apply') 233 | p.add_argument('--jpeg-qmin', type=int, default=88, help='Min JPEG quality for recompression') 234 | p.add_argument('--jpeg-qmax', type=int, default=96, help='Max JPEG quality for recompression') 235 | p.add_argument('--vignette-strength', type=float, default=0.35, help='Vignette strength (0..1)') 236 | p.add_argument('--chroma-strength', type=float, default=1.2, help='Chromatic aberration strength (pixels)') 237 | p.add_argument('--iso-scale', type=float, default=1.0, help='ISO/exposure scale for Poisson noise') 238 | p.add_argument('--read-noise', type=float, default=2.0, help='Read noise sigma for sensor noise') 239 | p.add_argument('--hot-pixel-prob', type=float, default=1e-6, help='Per-pixel probability of hot pixel') 240 | p.add_argument('--banding-strength', type=float, default=0.0, help='Horizontal banding amplitude (0..1)') 241 | p.add_argument('--motion-blur-kernel', type=int, default=1, help='Motion blur kernel size (1 = none)') 242 | 243 | # LUT options 244 | p.add_argument('--lut', type=str, default=None, help='Path to a 1D PNG (256x1) or .npy LUT, or a .cube 3D LUT') 245 | p.add_argument('--lut-strength', type=float, default=0.1, help='Strength to blend LUT (0.0 = no effect, 1.0 = full LUT)') 246 | 247 | # New positive flags to enable utils functions 248 | p.add_argument('--noise', action='store_true', default=False, help='Enable Gaussian noise addition') 249 | p.add_argument('--clahe', action='store_true', default=False, help='Enable CLAHE color correction') 250 | p.add_argument('--fft', action='store_true', default=False, help='Enable FFT spectral matching') 251 | p.add_argument('--perturb', action='store_true', default=False, help='Enable randomized perturbation') 252 | p.add_argument('--perturb-magnitude', type=float, default=0.008, help='Randomized perturb magnitude fraction (0..0.05)') 253 | 254 | # Blending options 255 | p.add_argument('--blend', action='store_true', default=False, help='Enable color') 256 | p.add_argument('--blend-tolerance', type=float, default=10.0, help='Color tolerance for blending (smaller = more colors)') 257 | p.add_argument('--blend-min-region', type=int, default=50, help='Minimum region size to retain (in pixels)') 258 | p.add_argument('--blend-max-samples', type=int, default=100000, help='Maximum pixels to sample for k-means (for speed)') 259 | p.add_argument('--blend-n-jobs', type=int, default=None, help='Number of worker threads for blending (default: os.cpu_count())') 260 | 261 | return p 262 | 263 | 264 | if __name__ == "__main__": 265 | args = build_argparser().parse_args() 266 | if not os.path.exists(args.input): 267 | print("Input not found:", args.input) 268 | raise SystemExit(2) 269 | process_image(args.input, args.output, args) 270 | print("Saved:", args.output) -------------------------------------------------------------------------------- /nodes.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from PIL import Image 3 | import numpy as np 4 | import os 5 | import tempfile 6 | from types import SimpleNamespace 7 | from typing import Tuple 8 | import json 9 | 10 | try: 11 | from .image_postprocess import process_image 12 | except Exception as e: 13 | process_image = None 14 | IMPORT_ERROR = str(e) 15 | else: 16 | IMPORT_ERROR = None 17 | 18 | from .nodes_utils import CameraOptionsNode, NSOptionsNode 19 | 20 | lut_extensions = ['png','npy','cube'] 21 | 22 | # ---------- Helper utilities (kept from original) ---------- 23 | 24 | def to_pil_from_any(inp): 25 | """Convert a torch tensor / numpy array of many shapes into a PIL RGB Image.""" 26 | if isinstance(inp, torch.Tensor): 27 | arr = inp.detach().cpu().numpy() 28 | else: 29 | arr = np.asarray(inp) 30 | if arr.ndim == 4 and arr.shape[0] == 1: 31 | arr = arr[0] 32 | if arr.ndim == 3 and arr.shape[0] in (1, 3): 33 | arr = np.transpose(arr, (1, 2, 0)) 34 | if arr.ndim == 2: 35 | arr = arr[:, :, None] 36 | if arr.ndim != 3: 37 | raise TypeError(f"Cannot convert array to HWC image, final ndim={arr.ndim}, shape={arr.shape}") 38 | if np.issubdtype(arr.dtype, np.floating): 39 | if arr.max() <= 1.0: 40 | arr = (arr * 255.0).clip(0, 255).astype(np.uint8) 41 | else: 42 | arr = np.clip(arr, 0, 255).astype(np.uint8) 43 | else: 44 | arr = arr.astype(np.uint8) 45 | if arr.shape[2] == 1: 46 | arr = np.repeat(arr, 3, axis=2) 47 | return Image.fromarray(arr) 48 | 49 | # utility parsers for list-like UI inputs 50 | 51 | def _parse_int_list(val): 52 | if isinstance(val, (list, tuple)): 53 | return [int(x) for x in val] 54 | if isinstance(val, (int, np.integer)): 55 | return [int(val)] 56 | s = str(val).strip() 57 | if s == "": 58 | return [] 59 | parts = [p for p in s.replace(',', ' ').split() if p != ""] 60 | return [int(p) for p in parts] 61 | 62 | 63 | def _parse_float_list(val): 64 | if isinstance(val, (list, tuple)): 65 | return [float(x) for x in val] 66 | if isinstance(val, (float, int, np.floating, np.integer)): 67 | return [float(val)] 68 | s = str(val).strip() 69 | if s == "": 70 | return [] 71 | parts = [p for p in s.replace(',', ' ').split() if p != ""] 72 | return [float(p) for p in parts] 73 | 74 | class NovaNodes: 75 | """ 76 | ComfyUI node: Full post-processing chain using process_image from image_postprocess. 77 | This version expects two optional JSON inputs: 78 | - Cam_Opt: JSON string produced by CameraOptionsNode 79 | - NS_Opt: JSON string produced by NSOptionsNode 80 | 81 | If those are empty, default values will be used (matching prior defaults). 82 | """ 83 | 84 | @classmethod 85 | def INPUT_TYPES(s): 86 | # Keep most of the core image-processing parameters here; camera/NS options have been moved out. 87 | return { 88 | "required": { 89 | "image": ("IMAGE",), 90 | 91 | # High-level toggles for using the external nodes 92 | "Cam_Opt": ("CAMERAOPT", ), 93 | "NS_Opt": ("NONSEMANTICOP", ), 94 | 95 | # Parameters (noise / clahe / fourier / etc.) 96 | "apply_noise_o": ("BOOLEAN", {"default": True}), 97 | "noise_std_frac": ("FLOAT", {"default": 0.02, "min": 0.0, "max": 0.1, "step": 0.001}), 98 | "apply_clahe_o": ("BOOLEAN", {"default": True}), 99 | "clahe_clip": ("FLOAT", {"default": 2.00, "min": 0.5, "max": 10.0, "step": 0.1}), 100 | "clahe_grid": ("INT", {"default": 8, "min": 2, "max": 32, "step": 1}), 101 | "fourier_cutoff": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 1.0, "step": 0.01}), 102 | "apply_fourier_o": ("BOOLEAN", {"default": True}), 103 | "fourier_strength": ("FLOAT", {"default": 0.90, "min": 0.0, "max": 1.0, "step": 0.01}), 104 | "fourier_randomness": ("FLOAT", {"default": 0.05, "min": 0.0, "max": 0.5, "step": 0.01}), 105 | "fourier_phase_perturb": ("FLOAT", {"default": 0.08, "min": 0.0, "max": 0.5, "step": 0.01}), 106 | "fourier_radial_smooth": ("INT", {"default": 5, "min": 0, "max": 50, "step": 1}), 107 | "fourier_mode": (["auto", "ref", "model"], {"default": "auto"}), 108 | "fourier_alpha": ("FLOAT", {"default": 1.00, "min": 0.1, "max": 4.0, "step": 0.1}), 109 | "perturb_mag_frac": ("FLOAT", {"default": 0.01, "min": 0.0, "max": 0.05, "step": 0.001}), 110 | "enable_awb": ("BOOLEAN", {"default": True}), 111 | 112 | 113 | "enable_lut": ("BOOLEAN", {"default": True}), 114 | "lut": ("STRING", {"default": "X://insert/path/here(.png/.npy/.cube)", "vhs_path_extensions": lut_extensions}), 115 | "lut_strength": ("FLOAT", {"default": 1.00, "min": 0.0, "max": 1.0, "step": 0.01}), 116 | "glcm": ("BOOLEAN", {"default": False}), 117 | "glcm_distances": ("STRING", {"default": "1"}), 118 | "glcm_angles": ("STRING", {"default": f"0,{np.pi/4},{np.pi/2},{3*np.pi/4}"}), 119 | "glcm_levels": ("INT", {"default": 256, "min": 2, "max": 65536, "step": 1}), 120 | "glcm_strength": ("FLOAT", {"default": 0.9, "min": 0.0, "max": 1.0, "step": 0.01}), 121 | "lbp": ("BOOLEAN", {"default": False}), 122 | "lbp_radius": ("INT", {"default": 3, "min": 1, "max": 50, "step": 1}), 123 | "lbp_n_points": ("INT", {"default": 24, "min": 1, "max": 512, "step": 1}), 124 | "lbp_method": (["default", "ror", "uniform", "var"], {"default": "uniform"}), 125 | "lbp_strength": ("FLOAT", {"default": 0.9, "min": 0.0, "max": 1.0, "step": 0.01}), 126 | 127 | # seed, exif 128 | "seed": ("INT", {"default": -1, "min": -1, "max": 2**31-1, "step": 1}), 129 | "apply_exif_o": ("BOOLEAN", {"default": True}), 130 | }, 131 | "optional": { 132 | "awb_ref_image": ("IMAGE",), 133 | "fft_ref_image": ("IMAGE",), 134 | } 135 | } 136 | 137 | RETURN_TYPES = ("IMAGE", "STRING") 138 | RETURN_NAMES = ("IMAGE", "EXIF") 139 | FUNCTION = "process" 140 | CATEGORY = "postprocessing" 141 | 142 | # default blocks for Camera and NS so the main node works even if user doesn't plug the helper nodes 143 | CAM_DEFAULTS = { 144 | "enable_bayer": True, 145 | "apply_jpeg_cycles_o": True, 146 | "jpeg_cycles": 1, 147 | "jpeg_quality": 88, 148 | "jpeg_qmax": 96, 149 | "apply_vignette_o": True, 150 | "vignette_strength": 0.35, 151 | "apply_chromatic_aberration_o": True, 152 | "ca_shift": 1.20, 153 | "iso_scale": 1.0, 154 | "read_noise": 2.0, 155 | "hot_pixel_prob": 1e-7, 156 | "apply_banding_o": True, 157 | "banding_strength": 0.0, 158 | "apply_motion_blur_o": True, 159 | "motion_blur_ksize": 1, 160 | } 161 | 162 | NS_DEFAULTS = { 163 | "non_semantic": False, 164 | "ns_iterations": 500, 165 | "ns_learning_rate": 3e-4, 166 | "ns_t_lpips": 4e-2, 167 | "ns_t_l2": 3e-5, 168 | "ns_c_lpips": 1e-2, 169 | "ns_c_l2": 0.6, 170 | "ns_grad_clip": 0.05, 171 | } 172 | 173 | def process(self, image, 174 | apply_noise_o=True, 175 | noise_std_frac=0.02, 176 | apply_clahe_o=True, 177 | clahe_clip=2.0, 178 | clahe_grid=8, 179 | fourier_cutoff=0.25, 180 | apply_fourier_o=True, 181 | fourier_strength=0.9, 182 | fourier_randomness=0.05, 183 | fourier_phase_perturb=0.08, 184 | fourier_radial_smooth=5, 185 | fourier_mode="auto", 186 | fourier_alpha=1.0, 187 | perturb_mag_frac=0.01, 188 | enable_awb=True, 189 | Cam_Opt="", 190 | NS_Opt="", 191 | enable_lut=True, 192 | lut="", 193 | lut_strength=1.0, 194 | glcm=False, 195 | glcm_distances="1", 196 | glcm_angles=f"0,{np.pi/4},{np.pi/2},{3*np.pi/4}", 197 | glcm_levels=256, 198 | glcm_strength=0.9, 199 | lbp=False, 200 | lbp_radius=3, 201 | lbp_n_points=24, 202 | lbp_method="uniform", 203 | lbp_strength=0.9, 204 | seed=-1, 205 | apply_exif_o=True, 206 | awb_ref_image=None, 207 | fft_ref_image=None 208 | ): 209 | 210 | if process_image is None: 211 | raise ImportError(f"Could not import process_image function: {IMPORT_ERROR}") 212 | 213 | # Parse Cam_Opt and NS_Opt JSON strings into dicts and merge with defaults 214 | cam_opts = dict(self.CAM_DEFAULTS) 215 | if isinstance(Cam_Opt, str) and Cam_Opt.strip() != "": 216 | try: 217 | loaded = json.loads(Cam_Opt) 218 | if isinstance(loaded, dict): 219 | cam_opts.update(loaded) 220 | except Exception: 221 | pass 222 | 223 | ns_opts = dict(self.NS_DEFAULTS) 224 | if isinstance(NS_Opt, str) and NS_Opt.strip() != "": 225 | try: 226 | loaded = json.loads(NS_Opt) 227 | if isinstance(loaded, dict): 228 | ns_opts.update(loaded) 229 | except Exception: 230 | pass 231 | 232 | tmp_files = [] 233 | 234 | try: 235 | # ---- Input image -> temporary input file ---- 236 | pil_img = to_pil_from_any(image[0]) 237 | with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_input: 238 | input_path = tmp_input.name 239 | pil_img.save(input_path) 240 | tmp_files.append(input_path) 241 | 242 | # ---- AWB reference image if present ---- 243 | awb_ref_path = None 244 | if awb_ref_image is not None: 245 | pil_ref_awb = to_pil_from_any(awb_ref_image[0]) 246 | with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_ref_awb: 247 | awb_ref_path = tmp_ref_awb.name 248 | pil_ref_awb.save(awb_ref_path) 249 | tmp_files.append(awb_ref_path) 250 | 251 | # ---- FFT reference image if present ---- 252 | fft_ref_path = None 253 | if fft_ref_image is not None: 254 | pil_ref_fft = to_pil_from_any(fft_ref_image[0]) 255 | with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_ref_fft: 256 | fft_ref_path = tmp_ref_fft.name 257 | pil_ref_fft.save(fft_ref_path) 258 | tmp_files.append(fft_ref_path) 259 | 260 | # ---- Output path ---- 261 | with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp_output: 262 | output_path = tmp_output.name 263 | tmp_files.append(output_path) 264 | 265 | # Parse list-like UI inputs into native lists 266 | parsed_glcm_distances = _parse_int_list(glcm_distances) 267 | parsed_glcm_angles = _parse_float_list(glcm_angles) 268 | 269 | # Prepare args for process_image with updated keys (matches build_argparser()) 270 | args = SimpleNamespace( 271 | # positional 272 | input=input_path, 273 | output=output_path, 274 | 275 | # AWB / refs 276 | awb=bool(enable_awb), 277 | ref=awb_ref_path, 278 | fft_ref=fft_ref_path, 279 | 280 | # basic corrections / noise / CLAHE 281 | noise_std=float(noise_std_frac), 282 | noise=bool(apply_noise_o), 283 | clahe=bool(apply_clahe_o), 284 | clahe_clip=float(clahe_clip), 285 | tile=int(clahe_grid), 286 | 287 | # Fourier / FFT matching 288 | fft=bool(apply_fourier_o), 289 | fstrength=float(fourier_strength) if apply_fourier_o else 0.0, 290 | randomness=float(fourier_randomness), 291 | seed=(None if int(seed) < 0 else int(seed)), 292 | fft_mode=str(fourier_mode), 293 | fft_alpha=float(fourier_alpha), 294 | phase_perturb=float(fourier_phase_perturb), 295 | radial_smooth=int(fourier_radial_smooth), 296 | cutoff=float(fourier_cutoff), 297 | 298 | # GLCM 299 | glcm=bool(glcm), 300 | glcm_distances=parsed_glcm_distances, 301 | glcm_angles=parsed_glcm_angles, 302 | glcm_levels=int(glcm_levels), 303 | glcm_strength=float(glcm_strength), 304 | 305 | # LBP 306 | lbp=bool(lbp), 307 | lbp_radius=int(lbp_radius), 308 | lbp_n_points=int(lbp_n_points), 309 | lbp_method=str(lbp_method), 310 | lbp_strength=float(lbp_strength), 311 | 312 | # Non-semantic attack (from ns_opts) 313 | non_semantic=bool(ns_opts.get("non_semantic", False)), 314 | ns_iterations=int(ns_opts.get("ns_iterations", 500)), 315 | ns_learning_rate=float(ns_opts.get("ns_learning_rate", 3e-4)), 316 | ns_t_lpips=float(ns_opts.get("ns_t_lpips", 4e-2)), 317 | ns_t_l2=float(ns_opts.get("ns_t_l2", 3e-5)), 318 | ns_c_lpips=float(ns_opts.get("ns_c_lpips", 1e-2)), 319 | ns_c_l2=float(ns_opts.get("ns_c_l2", 0.6)), 320 | ns_grad_clip=float(ns_opts.get("ns_grad_clip", 0.05)), 321 | 322 | # Camera simulator options (from cam_opts) 323 | sim_camera=True, 324 | no_no_bayer=not bool(cam_opts.get("enable_bayer", True)), 325 | jpeg_cycles=int(cam_opts.get("jpeg_cycles", 1)) if bool(cam_opts.get("apply_jpeg_cycles_o", True)) else 1, 326 | jpeg_qmin=int(cam_opts.get("jpeg_quality", 88)), 327 | jpeg_qmax=int(cam_opts.get("jpeg_qmax", 96)), 328 | vignette_strength=float(cam_opts.get("vignette_strength", 0.35)) if bool(cam_opts.get("apply_vignette_o", True)) else 0.0, 329 | chroma_strength=float(cam_opts.get("ca_shift", 1.20)) if bool(cam_opts.get("apply_chromatic_aberration_o", True)) else 0.0, 330 | iso_scale=float(cam_opts.get("iso_scale", 1.0)), 331 | read_noise=float(cam_opts.get("read_noise", 2.0)), 332 | hot_pixel_prob=float(cam_opts.get("hot_pixel_prob", 1e-7)), 333 | banding_strength=float(cam_opts.get("banding_strength", 0.0)) if bool(cam_opts.get("apply_banding_o", True)) else 0.0, 334 | motion_blur_kernel=int(cam_opts.get("motion_blur_ksize", 1)) if bool(cam_opts.get("apply_motion_blur_o", True)) else 1, 335 | 336 | # LUT 337 | lut=(lut if enable_lut and lut != "" else None), 338 | lut_strength=float(lut_strength), 339 | 340 | # utility flags (positive-style equivalents) 341 | perturb=(True if perturb_mag_frac > 0 else False), 342 | perturb_magnitude=float(perturb_mag_frac), 343 | blend=False 344 | ) 345 | 346 | # ---- Run the processing function ---- 347 | process_image(input_path, output_path, args) 348 | 349 | # ---- Load result (force RGB) ---- 350 | output_img = Image.open(output_path).convert("RGB") 351 | img_out = np.array(output_img) 352 | 353 | # ---- EXIF insertion (optional) ---- 354 | new_exif = "" 355 | if apply_exif_o: 356 | try: 357 | output_img_with_exif, new_exif = self._add_fake_exif(output_img) 358 | output_img = output_img_with_exif 359 | img_out = np.array(output_img.convert("RGB")) 360 | except Exception: 361 | new_exif = "" 362 | 363 | # ---- Convert to FOOLAI-style tensor: (1, H, W, C), float32 in [0,1] ---- 364 | img_float = img_out.astype(np.float32) / 255.0 365 | tensor_out = torch.from_numpy(img_float).to(dtype=torch.float32).unsqueeze(0) 366 | tensor_out = torch.clamp(tensor_out, 0.0, 1.0) 367 | 368 | return (tensor_out, new_exif) 369 | 370 | finally: 371 | for p in tmp_files: 372 | try: 373 | os.unlink(p) 374 | except Exception: 375 | pass 376 | 377 | def _add_fake_exif(self, img: Image.Image) -> Tuple[Image.Image, str]: 378 | """Insert random but realistic camera EXIF metadata.""" 379 | import random 380 | import io 381 | try: 382 | import piexif 383 | except Exception: 384 | raise 385 | 386 | exif_dict = { 387 | "0th": { 388 | piexif.ImageIFD.Make: random.choice(["Canon", "Nikon", "Sony", "Fujifilm", "Olympus", "Leica"]), 389 | piexif.ImageIFD.Model: random.choice([ 390 | "EOS 5D Mark III", "D850", "Alpha 7R IV", "X-T4", "OM-D E-M1 Mark III", "Q2" 391 | ]), 392 | piexif.ImageIFD.Software: "Adobe Lightroom", 393 | }, 394 | "Exif": { 395 | piexif.ExifIFD.FNumber: (random.randint(10, 22), 10), 396 | piexif.ExifIFD.ExposureTime: (1, random.randint(60, 4000)), 397 | piexif.ExifIFD.ISOSpeedRatings: random.choice([100, 200, 400, 800, 1600, 3200]), 398 | piexif.ExifIFD.FocalLength: (random.randint(24, 200), 1), 399 | }, 400 | } 401 | exif_bytes = piexif.dump(exif_dict) 402 | output = io.BytesIO() 403 | img.save(output, format="JPEG", exif=exif_bytes) 404 | output.seek(0) 405 | return (Image.open(output), str(exif_bytes)) 406 | 407 | 408 | # ------------- 409 | # Registration 410 | # ------------- 411 | NODE_CLASS_MAPPINGS = { 412 | "NovaNodes": NovaNodes, 413 | "CameraOptionsNode": CameraOptionsNode, 414 | "NSOptionsNode": NSOptionsNode, 415 | } 416 | NODE_DISPLAY_NAME_MAPPINGS = { 417 | "NovaNodes": "Image Postprocess (NOVA NODES)", 418 | "CameraOptionsNode": "Camera Options (NOVA)", 419 | "NSOptionsNode": "Non-semantic Options (NOVA)", 420 | } 421 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /ui_utils/main_window.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | MainWindow definition extracted from the original single-file GUI. 4 | All GUI wiring, widgets, and the MainWindow class live here. 5 | """ 6 | 7 | import sys 8 | import os 9 | from pathlib import Path 10 | from PyQt5.QtWidgets import ( 11 | QApplication, QMainWindow, QWidget, QLabel, QPushButton, QFileDialog, 12 | QHBoxLayout, QVBoxLayout, QFormLayout, QSlider, QSpinBox, QDoubleSpinBox, 13 | QProgressBar, QMessageBox, QLineEdit, QComboBox, QCheckBox, QToolButton, QScrollArea 14 | ) 15 | from PyQt5.QtCore import Qt 16 | from PyQt5.QtGui import QPixmap 17 | from .worker import Worker 18 | from .analysis_panel import AnalysisPanel 19 | from .collapsible_box import CollapsibleBox 20 | from utils import qpixmap_from_path 21 | from .theme import apply_dark_palette 22 | import numpy as np 23 | import configparser 24 | import math 25 | 26 | class MainWindow(QMainWindow): 27 | def __init__(self): 28 | super().__init__() 29 | 30 | # --- Load config.ini --- 31 | config = configparser.ConfigParser() 32 | config.read(os.path.join(os.path.dirname(__file__), "..", "config.ini")) 33 | 34 | def get(section, key, default, cast=str): 35 | try: 36 | val = config.get(section, key) 37 | return cast(val) 38 | except Exception: 39 | return default 40 | 41 | def getbool(section, key, default): 42 | try: 43 | return config.getboolean(section, key) 44 | except Exception: 45 | return default 46 | 47 | # --- Window --- 48 | self.setWindowTitle("Image Detection Bypass Utility V1.4 Alpha 1") 49 | self.setMinimumSize(1200, 760) 50 | 51 | central = QWidget() 52 | self.setCentralWidget(central) 53 | main_h = QHBoxLayout(central) 54 | 55 | # Left: previews & file selection 56 | left_v = QVBoxLayout() 57 | main_h.addLayout(left_v, 2) 58 | 59 | # Input/Output collapsible 60 | io_box = CollapsibleBox("Input / Output") 61 | left_v.addWidget(io_box) 62 | in_layout = QFormLayout() 63 | io_container = QWidget() 64 | io_container.setLayout(in_layout) 65 | io_box.content_layout.addWidget(io_container) 66 | 67 | self.input_line = QLineEdit() 68 | self.input_btn = QPushButton("Choose Input") 69 | self.input_btn.clicked.connect(self.choose_input) 70 | 71 | self.ref_line = QLineEdit() 72 | self.ref_btn = QPushButton("Choose AWB Reference (optional)") 73 | self.ref_btn.clicked.connect(self.choose_ref) 74 | 75 | self.fft_ref_line = QLineEdit() 76 | self.fft_ref_btn = QPushButton("Choose Reference (FFT, GLCM, LBP) (Optional)") 77 | self.fft_ref_btn.clicked.connect(self.choose_fft_ref) 78 | 79 | self.output_line = QLineEdit() 80 | self.output_btn = QPushButton("Choose Output") 81 | self.output_btn.clicked.connect(self.choose_output) 82 | 83 | in_layout.addRow(self.input_btn, self.input_line) 84 | in_layout.addRow(self.ref_btn, self.ref_line) 85 | in_layout.addRow(self.fft_ref_btn, self.fft_ref_line) 86 | in_layout.addRow(self.output_btn, self.output_line) 87 | 88 | # Previews 89 | self.preview_in = QLabel(alignment=Qt.AlignCenter) 90 | self.preview_in.setFixedSize(480, 300) 91 | self.preview_in.setStyleSheet("background:#121213; border:1px solid #2b2b2b; color:#ddd; border-radius:6px") 92 | self.preview_in.setText("Input preview") 93 | 94 | self.preview_out = QLabel(alignment=Qt.AlignCenter) 95 | self.preview_out.setFixedSize(480, 300) 96 | self.preview_out.setStyleSheet("background:#121213; border:1px solid #2b2b2b; color:#ddd; border-radius:6px") 97 | self.preview_out.setText("Output preview") 98 | 99 | left_v.addWidget(self.preview_in) 100 | left_v.addWidget(self.preview_out) 101 | 102 | # Actions 103 | actions_h = QHBoxLayout() 104 | self.run_btn = QPushButton("Run — Process Image") 105 | self.run_btn.clicked.connect(self.on_run) 106 | self.open_out_btn = QPushButton("Open Output Folder") 107 | self.open_out_btn.clicked.connect(self.open_output_folder) 108 | actions_h.addWidget(self.run_btn) 109 | actions_h.addWidget(self.open_out_btn) 110 | left_v.addLayout(actions_h) 111 | 112 | self.progress = QProgressBar() 113 | self.progress.setTextVisible(True) 114 | self.progress.setRange(0, 100) 115 | self.progress.setValue(0) 116 | left_v.addWidget(self.progress) 117 | 118 | # Right: controls + analysis panels (with scroll area) 119 | scroll_area = QScrollArea() 120 | scroll_area.setWidgetResizable(True) 121 | scroll_area.setStyleSheet("QScrollArea { border: none; }") 122 | main_h.addWidget(scroll_area, 3) 123 | 124 | scroll_widget = QWidget() 125 | right_v = QVBoxLayout(scroll_widget) 126 | scroll_area.setWidget(scroll_widget) 127 | 128 | # Auto Mode toggle 129 | self.auto_mode_chk = QCheckBox("Enable Auto Mode") 130 | self.auto_mode_chk.setChecked(getbool("General", "auto_mode", False)) 131 | self.auto_mode_chk.stateChanged.connect(self._on_auto_mode_toggled) 132 | right_v.addWidget(self.auto_mode_chk) 133 | 134 | # Auto Mode section collapsible 135 | self.auto_box = CollapsibleBox("Auto Mode") 136 | right_v.addWidget(self.auto_box) 137 | auto_layout = QFormLayout() 138 | auto_container = QWidget() 139 | auto_container.setLayout(auto_layout) 140 | self.auto_box.content_layout.addWidget(auto_container) 141 | 142 | strength_layout = QHBoxLayout() 143 | self.strength_slider = QSlider(Qt.Horizontal) 144 | self.strength_slider.setRange(0, 100) 145 | self.strength_slider.setValue(get("AutoMode", "strength", 25, int)) 146 | self.strength_slider.valueChanged.connect(self._update_strength_label) 147 | self.strength_label = QLabel(str(self.strength_slider.value())) 148 | self.strength_label.setFixedWidth(30) 149 | strength_layout.addWidget(self.strength_slider) 150 | strength_layout.addWidget(self.strength_label) 151 | auto_layout.addRow("Aberration Strength", strength_layout) 152 | 153 | # Blend system 154 | self.blend_box = CollapsibleBox("Blend Color") 155 | right_v.addWidget(self.blend_box) 156 | blend_layout = QFormLayout() 157 | blend_container = QWidget() 158 | blend_container.setLayout(blend_layout) 159 | self.blend_box.content_layout.addWidget(blend_container) 160 | 161 | self.blend_chk = QCheckBox("Enable Color Blending") 162 | self.blend_chk.setToolTip("Color blending makes clusters of similar colors be one color") 163 | self.blend_chk.setChecked(getbool("Blend", "enabled", False)) 164 | blend_layout.addRow(self.blend_chk) 165 | 166 | self.blend_tolerance = QSpinBox() 167 | self.blend_tolerance.setRange(1, 100) 168 | self.blend_tolerance.setValue(get("Blend", "tolerance", 10, int)) 169 | self.blend_tolerance.setToolTip("Color tolerance for blending (smaller = more colors)") 170 | blend_layout.addRow("Color Tolerance", self.blend_tolerance) 171 | 172 | self.blend_min_region = QSpinBox() 173 | self.blend_min_region.setRange(1, 1000) 174 | self.blend_min_region.setValue(get("Blend", "min_region", 50, int)) 175 | self.blend_min_region.setToolTip("Minimum region size to retain (in pixels)") 176 | blend_layout.addRow("Min Region Size", self.blend_min_region) 177 | 178 | self.blend_max_samples = QSpinBox() 179 | self.blend_max_samples.setRange(1000, 1000000) 180 | self.blend_max_samples.setValue(get("Blend", "max_samples", 100000, int)) 181 | self.blend_max_samples.setToolTip("Maximum pixels to sample for k-means (for speed)") 182 | blend_layout.addRow("Max Samples", self.blend_max_samples) 183 | 184 | self.blend_n_jobs = QSpinBox() 185 | self.blend_n_jobs.setRange(1, os.cpu_count() or 4) 186 | self.blend_n_jobs.setValue(get("Blend", "n_jobs", os.cpu_count() or 4, int)) 187 | self.blend_n_jobs.setToolTip("Number of worker threads for blending (default: os.cpu_count())") 188 | blend_layout.addRow("Worker Threads", self.blend_n_jobs) 189 | 190 | # AI Normalizer 191 | self.ai_norm_box = CollapsibleBox("AI Normalizer") 192 | right_v.addWidget(self.ai_norm_box) 193 | ai_layout = QFormLayout() 194 | ai_container = QWidget() 195 | ai_container.setLayout(ai_layout) 196 | self.ai_norm_box.content_layout.addWidget(ai_container) 197 | 198 | self.ns_chk = QCheckBox("Enable AI Normalizer (Torch Required)") 199 | self.ns_chk.setToolTip("Enable AI Normalizer. Requires PyTorch.") 200 | self.ns_chk.setChecked(getbool("AINormalizer", "enabled", False)) 201 | ai_layout.addRow(self.ns_chk) 202 | 203 | self.ns_iterations_spin = QSpinBox() 204 | self.ns_iterations_spin.setRange(1, 10000) 205 | self.ns_iterations_spin.setValue(get("AINormalizer", "iterations", 500, int)) 206 | self.ns_iterations_spin.setToolTip("Number of iterations for the AI Normalizer optimization.") 207 | ai_layout.addRow("Iterations", self.ns_iterations_spin) 208 | 209 | self.ns_lr_spin = QDoubleSpinBox() 210 | self.ns_lr_spin.setDecimals(6) 211 | self.ns_lr_spin.setRange(0.000001, 0.1) 212 | self.ns_lr_spin.setSingleStep(0.0001) 213 | self.ns_lr_spin.setValue(get("AINormalizer", "learning_rate", 0.0003, float)) 214 | self.ns_lr_spin.setToolTip("Learning rate for the AI Normalizer optimization.") 215 | ai_layout.addRow("Learning Rate", self.ns_lr_spin) 216 | 217 | self.ns_t_lpips_spin = QDoubleSpinBox() 218 | self.ns_t_lpips_spin.setDecimals(6) 219 | self.ns_t_lpips_spin.setRange(0.000001, 1.0) 220 | self.ns_t_lpips_spin.setSingleStep(0.0001) 221 | self.ns_t_lpips_spin.setValue(get("AINormalizer", "t_lpips", 0.04, float)) 222 | self.ns_t_lpips_spin.setToolTip("Temporally weighted LPIPS loss parameter.") 223 | ai_layout.addRow("T LPIPS", self.ns_t_lpips_spin) 224 | 225 | self.ns_t_l2_spin = QDoubleSpinBox() 226 | self.ns_t_l2_spin.setDecimals(6) 227 | self.ns_t_l2_spin.setRange(0.000001, 1.0) 228 | self.ns_t_l2_spin.setSingleStep(0.00001) 229 | self.ns_t_l2_spin.setValue(get("AINormalizer", "t_l2", 3e-05, float)) 230 | self.ns_t_l2_spin.setToolTip("Temporally weighted L2 loss parameter.") 231 | ai_layout.addRow("T L2", self.ns_t_l2_spin) 232 | 233 | self.ns_c_lpips_spin = QDoubleSpinBox() 234 | self.ns_c_lpips_spin.setDecimals(6) 235 | self.ns_c_lpips_spin.setRange(0.000001, 1.0) 236 | self.ns_c_lpips_spin.setSingleStep(0.0001) 237 | self.ns_c_lpips_spin.setValue(get("AINormalizer", "c_lpips", 0.01, float)) 238 | self.ns_c_lpips_spin.setToolTip("Content loss LPIPS weight.") 239 | ai_layout.addRow("C LPIPS", self.ns_c_lpips_spin) 240 | 241 | self.ns_c_l2_spin = QDoubleSpinBox() 242 | self.ns_c_l2_spin.setDecimals(6) 243 | self.ns_c_l2_spin.setRange(0.000001, 10.0) 244 | self.ns_c_l2_spin.setSingleStep(0.01) 245 | self.ns_c_l2_spin.setValue(get("AINormalizer", "c_l2", 0.6, float)) 246 | self.ns_c_l2_spin.setToolTip("Content loss L2 weight.") 247 | ai_layout.addRow("C L2", self.ns_c_l2_spin) 248 | 249 | self.ns_grad_clip_spin = QDoubleSpinBox() 250 | self.ns_grad_clip_spin.setDecimals(6) 251 | self.ns_grad_clip_spin.setRange(0.000001, 1.0) 252 | self.ns_grad_clip_spin.setSingleStep(0.0001) 253 | self.ns_grad_clip_spin.setValue(get("AINormalizer", "grad_clip", 0.05, float)) 254 | self.ns_grad_clip_spin.setToolTip("Gradient clipping threshold to stabilize training.") 255 | ai_layout.addRow("Gradient Clip", self.ns_grad_clip_spin) 256 | 257 | # Parameters (Manual Mode) collapsible 258 | self.params_box = CollapsibleBox("Parameters (Manual Mode)") 259 | right_v.addWidget(self.params_box) 260 | params_layout = QFormLayout() 261 | params_container = QWidget() 262 | params_container.setLayout(params_layout) 263 | self.params_box.content_layout.addWidget(params_container) 264 | 265 | # New optional flags for processing steps 266 | self.noise_enable_chk = QCheckBox("Enable Gaussian Noise") 267 | self.noise_enable_chk.setChecked(getbool("ManualParameters", "noise_enable", True)) 268 | params_layout.addRow(self.noise_enable_chk) 269 | 270 | self.clahe_enable_chk = QCheckBox("Enable CLAHE Color Correction") 271 | self.clahe_enable_chk.setChecked(getbool("ManualParameters", "clahe_enable", True)) 272 | params_layout.addRow(self.clahe_enable_chk) 273 | 274 | self.fft_enable_chk = QCheckBox("Enable FFT Spectral Matching") 275 | self.fft_enable_chk.setChecked(getbool("ManualParameters", "fft_enable", True)) 276 | params_layout.addRow(self.fft_enable_chk) 277 | 278 | self.perturb_enable_chk = QCheckBox("Enable Randomized Perturbation") 279 | self.perturb_enable_chk.setChecked(getbool("ManualParameters", "perturb_enable", True)) 280 | params_layout.addRow(self.perturb_enable_chk) 281 | 282 | # Noise-std 283 | self.noise_spin = QDoubleSpinBox() 284 | self.noise_spin.setRange(0.0, 0.1) 285 | self.noise_spin.setSingleStep(0.001) 286 | self.noise_spin.setValue(get("ManualParameters", "noise_std", 0.02, float)) 287 | self.noise_spin.setToolTip("Gaussian noise std fraction of 255") 288 | params_layout.addRow("Noise std (0-0.1)", self.noise_spin) 289 | 290 | # CLAHE-clip 291 | self.clahe_spin = QDoubleSpinBox() 292 | self.clahe_spin.setRange(0.1, 10.0) 293 | self.clahe_spin.setSingleStep(0.1) 294 | self.clahe_spin.setValue(get("ManualParameters", "clahe_clip", 2.0, float)) 295 | params_layout.addRow("CLAHE clip", self.clahe_spin) 296 | 297 | # Tile 298 | self.tile_spin = QSpinBox() 299 | self.tile_spin.setRange(1, 64) 300 | self.tile_spin.setValue(get("ManualParameters", "tile", 8, int)) 301 | params_layout.addRow("CLAHE tile", self.tile_spin) 302 | 303 | # Cutoff 304 | self.cutoff_spin = QDoubleSpinBox() 305 | self.cutoff_spin.setRange(0.01, 1.0) 306 | self.cutoff_spin.setSingleStep(0.01) 307 | self.cutoff_spin.setValue(get("ManualParameters", "cutoff", 0.25, float)) 308 | params_layout.addRow("Fourier cutoff (0-1)", self.cutoff_spin) 309 | 310 | # Fstrength 311 | self.fstrength_spin = QDoubleSpinBox() 312 | self.fstrength_spin.setRange(0.0, 1.0) 313 | self.fstrength_spin.setSingleStep(0.01) 314 | self.fstrength_spin.setValue(get("ManualParameters", "fstrength", 0.9, float)) 315 | params_layout.addRow("Fourier strength (0-1)", self.fstrength_spin) 316 | 317 | # Randomness 318 | self.randomness_spin = QDoubleSpinBox() 319 | self.randomness_spin.setRange(0.0, 1.0) 320 | self.randomness_spin.setSingleStep(0.01) 321 | self.randomness_spin.setValue(get("ManualParameters", "randomness", 0.05, float)) 322 | params_layout.addRow("Fourier randomness", self.randomness_spin) 323 | 324 | # Phase_perturb 325 | self.phase_perturb_spin = QDoubleSpinBox() 326 | self.phase_perturb_spin.setRange(0.0, 1.0) 327 | self.phase_perturb_spin.setSingleStep(0.001) 328 | self.phase_perturb_spin.setValue(get("ManualParameters", "phase_perturb", 0.08, float)) 329 | self.phase_perturb_spin.setToolTip("Phase perturbation std (radians)") 330 | params_layout.addRow("Phase perturb (rad)", self.phase_perturb_spin) 331 | 332 | # Radial_smooth 333 | self.radial_smooth_spin = QSpinBox() 334 | self.radial_smooth_spin.setRange(0, 50) 335 | self.radial_smooth_spin.setValue(get("ManualParameters", "radial_smooth", 5, int)) 336 | params_layout.addRow("Radial smooth (bins)", self.radial_smooth_spin) 337 | 338 | # FFT_mode 339 | self.fft_mode_combo = QComboBox() 340 | self.fft_mode_combo.addItems(["auto", "ref", "model"]) 341 | self.fft_mode_combo.setCurrentText(get("ManualParameters", "fft_mode", "auto")) 342 | params_layout.addRow("FFT mode", self.fft_mode_combo) 343 | 344 | # FFT_alpha 345 | self.fft_alpha_spin = QDoubleSpinBox() 346 | self.fft_alpha_spin.setRange(0.1, 4.0) 347 | self.fft_alpha_spin.setSingleStep(0.1) 348 | self.fft_alpha_spin.setValue(get("ManualParameters", "fft_alpha", 1.0, float)) 349 | self.fft_alpha_spin.setToolTip("Alpha exponent for 1/f model when using model mode") 350 | params_layout.addRow("FFT alpha (model)", self.fft_alpha_spin) 351 | 352 | # Perturb 353 | self.perturb_spin = QDoubleSpinBox() 354 | self.perturb_spin.setRange(0.0, 0.05) 355 | self.perturb_spin.setSingleStep(0.001) 356 | self.perturb_spin.setValue(get("ManualParameters", "perturb", 0.008, float)) 357 | params_layout.addRow("Pixel perturb", self.perturb_spin) 358 | 359 | # Seed 360 | self.seed_spin = QSpinBox() 361 | self.seed_spin.setRange(0, 2 ** 31 - 1) 362 | self.seed_spin.setValue(get("ManualParameters", "seed", 0, int)) 363 | params_layout.addRow("Seed (0=none)", self.seed_spin) 364 | 365 | # AWB checkbox 366 | self.awb_chk = QCheckBox("Enable auto white-balance (AWB)") 367 | self.awb_chk.setChecked(getbool("AWB", "enabled", False)) 368 | self.awb_chk.setToolTip("If checked, AWB is applied. If a reference image is chosen, it will be used; otherwise gray-world AWB is applied.") 369 | params_layout.addRow(self.awb_chk) 370 | 371 | # Camera simulator toggle 372 | self.sim_camera_chk = QCheckBox("Enable camera pipeline simulation") 373 | self.sim_camera_chk.setChecked(getbool("CameraSimulator", "enabled", False)) 374 | self.sim_camera_chk.stateChanged.connect(self._on_sim_camera_toggled) 375 | params_layout.addRow(self.sim_camera_chk) 376 | 377 | # LUT support UI 378 | self.lut_chk = QCheckBox("Enable LUT") 379 | self.lut_chk.setChecked(getbool("LUT", "enabled", False)) 380 | self.lut_chk.setToolTip("Enable applying a 1D/.npy/.cube LUT to the output image") 381 | self.lut_chk.stateChanged.connect(self._on_lut_toggled) 382 | params_layout.addRow(self.lut_chk) 383 | 384 | self.lut_line = QLineEdit(get("LUT", "file", "")) 385 | self.lut_btn = QPushButton("Choose LUT") 386 | self.lut_btn.clicked.connect(self.choose_lut) 387 | lut_box = QWidget() 388 | lut_box_layout = QHBoxLayout() 389 | lut_box_layout.setContentsMargins(0, 0, 0, 0) 390 | lut_box.setLayout(lut_box_layout) 391 | lut_box_layout.addWidget(self.lut_line) 392 | lut_box_layout.addWidget(self.lut_btn) 393 | self.lut_file_label = QLabel("LUT file (png/.npy/.cube)") 394 | params_layout.addRow(self.lut_file_label, lut_box) 395 | 396 | self.lut_strength_spin = QDoubleSpinBox() 397 | self.lut_strength_spin.setRange(0.0, 1.0) 398 | self.lut_strength_spin.setSingleStep(0.01) 399 | self.lut_strength_spin.setValue(get("LUT", "strength", 1.0, float)) 400 | self.lut_strength_spin.setToolTip("Blend strength for LUT (0.0 = no effect, 1.0 = full LUT)") 401 | self.lut_strength_label = QLabel("LUT strength") 402 | params_layout.addRow(self.lut_strength_label, self.lut_strength_spin) 403 | 404 | # Initially hide LUT controls and their labels 405 | self.lut_file_label.setVisible(False) 406 | lut_box.setVisible(False) 407 | self.lut_strength_label.setVisible(False) 408 | self.lut_strength_spin.setVisible(False) 409 | 410 | self._lut_controls = (self.lut_file_label, lut_box, self.lut_strength_label, self.lut_strength_spin) 411 | 412 | # Texture Normalization collapsible group 413 | self.texture_box = CollapsibleBox("Texture Normalization") 414 | right_v.addWidget(self.texture_box) 415 | texture_layout = QFormLayout() 416 | texture_container = QWidget() 417 | texture_container.setLayout(texture_layout) 418 | self.texture_box.content_layout.addWidget(texture_container) 419 | 420 | # GLCM checkbox 421 | self.glcm_chk = QCheckBox("Enable GLCM Normalization") 422 | self.glcm_chk.setChecked(getbool("TextureNormalization", "glcm_enabled", False)) 423 | self.glcm_chk.setToolTip("Enable GLCM normalization using FFT reference image") 424 | texture_layout.addRow(self.glcm_chk) 425 | 426 | # GLCM distances 427 | self.glcm_distances_line = QLineEdit(get("TextureNormalization", "glcm_distances", "1")) 428 | self.glcm_distances_line.setToolTip("Space-separated list of distances for GLCM computation (e.g., '1 2 3')") 429 | texture_layout.addRow("GLCM Distances", self.glcm_distances_line) 430 | 431 | # GLCM angles 432 | self.glcm_angles_line = QLineEdit(get("TextureNormalization", "glcm_angles", "0 0.785 1.571 2.356")) 433 | self.glcm_angles_line.setToolTip("Space-separated list of angles in radians for GLCM (e.g., '0 0.785 1.571 2.356')") 434 | texture_layout.addRow("GLCM Angles (rad)", self.glcm_angles_line) 435 | 436 | # GLCM levels 437 | self.glcm_levels_spin = QSpinBox() 438 | self.glcm_levels_spin.setRange(2, 256) 439 | self.glcm_levels_spin.setValue(get("TextureNormalization", "glcm_levels", 256, int)) 440 | self.glcm_levels_spin.setToolTip("Number of gray levels for GLCM") 441 | texture_layout.addRow("GLCM Levels", self.glcm_levels_spin) 442 | 443 | # GLCM strength 444 | self.glcm_strength_spin = QDoubleSpinBox() 445 | self.glcm_strength_spin.setRange(0.0, 1.0) 446 | self.glcm_strength_spin.setSingleStep(0.01) 447 | self.glcm_strength_spin.setValue(get("TextureNormalization", "glcm_strength", 0.9, float)) 448 | self.glcm_strength_spin.setToolTip("Strength of GLCM feature matching (0.0 = no effect, 1.0 = full effect)") 449 | texture_layout.addRow("GLCM Strength", self.glcm_strength_spin) 450 | 451 | # LBP checkbox 452 | self.lbp_chk = QCheckBox("Enable LBP Normalization") 453 | self.lbp_chk.setChecked(getbool("TextureNormalization", "lbp_enabled", False)) 454 | self.lbp_chk.setToolTip("Enable LBP normalization using FFT reference image") 455 | texture_layout.addRow(self.lbp_chk) 456 | 457 | # LBP radius 458 | self.lbp_radius_spin = QSpinBox() 459 | self.lbp_radius_spin.setRange(1, 10) 460 | self.lbp_radius_spin.setValue(get("TextureNormalization", "lbp_radius", 3, int)) 461 | self.lbp_radius_spin.setToolTip("Radius of LBP operator") 462 | texture_layout.addRow("LBP Radius", self.lbp_radius_spin) 463 | 464 | # LBP n_points 465 | self.lbp_n_points_spin = QSpinBox() 466 | self.lbp_n_points_spin.setRange(8, 64) 467 | self.lbp_n_points_spin.setValue(get("TextureNormalization", "lbp_n_points", 24, int)) 468 | self.lbp_n_points_spin.setToolTip("Number of circularly symmetric neighbor set points for LBP") 469 | texture_layout.addRow("LBP N Points", self.lbp_n_points_spin) 470 | 471 | # LBP method 472 | self.lbp_method_combo = QComboBox() 473 | self.lbp_method_combo.addItems(["default", "ror", "uniform", "var"]) 474 | self.lbp_method_combo.setCurrentText(get("TextureNormalization", "lbp_method", "uniform")) 475 | self.lbp_method_combo.setToolTip("LBP method: default, ror, uniform, or var") 476 | texture_layout.addRow("LBP Method", self.lbp_method_combo) 477 | 478 | # LBP strength 479 | self.lbp_strength_spin = QDoubleSpinBox() 480 | self.lbp_strength_spin.setRange(0.0, 1.0) 481 | self.lbp_strength_spin.setSingleStep(0.01) 482 | self.lbp_strength_spin.setValue(get("TextureNormalization", "lbp_strength", 0.9, float)) 483 | self.lbp_strength_spin.setToolTip("Strength of LBP histogram matching (0.0 = no effect, 1.0 = full effect)") 484 | texture_layout.addRow("LBP Strength", self.lbp_strength_spin) 485 | 486 | # Camera simulator collapsible group 487 | self.camera_box = CollapsibleBox("Camera simulator options") 488 | right_v.addWidget(self.camera_box) 489 | cam_layout = QFormLayout() 490 | cam_container = QWidget() 491 | cam_container.setLayout(cam_layout) 492 | self.camera_box.content_layout.addWidget(cam_container) 493 | 494 | # Enable bayer 495 | self.bayer_chk = QCheckBox("Enable Bayer / demosaic (RGGB)") 496 | self.bayer_chk.setChecked(getbool("CameraSimulator", "bayer", True)) 497 | cam_layout.addRow(self.bayer_chk) 498 | 499 | # JPEG cycles 500 | self.jpeg_cycles_spin = QSpinBox() 501 | self.jpeg_cycles_spin.setRange(0, 10) 502 | self.jpeg_cycles_spin.setValue(get("CameraSimulator", "jpeg_cycles", 1, int)) 503 | cam_layout.addRow("JPEG cycles", self.jpeg_cycles_spin) 504 | 505 | # JPEG quality min/max 506 | self.jpeg_qmin_spin = QSpinBox() 507 | self.jpeg_qmin_spin.setRange(1, 100) 508 | self.jpeg_qmin_spin.setValue(get("CameraSimulator", "jpeg_qmin", 88, int)) 509 | self.jpeg_qmax_spin = QSpinBox() 510 | self.jpeg_qmax_spin.setRange(1, 100) 511 | self.jpeg_qmax_spin.setValue(get("CameraSimulator", "jpeg_qmax", 96, int)) 512 | qbox = QHBoxLayout() 513 | qbox.addWidget(self.jpeg_qmin_spin) 514 | qbox.addWidget(QLabel("to")) 515 | qbox.addWidget(self.jpeg_qmax_spin) 516 | cam_layout.addRow("JPEG quality (min to max)", qbox) 517 | 518 | # Vignette strength 519 | self.vignette_spin = QDoubleSpinBox() 520 | self.vignette_spin.setRange(0.0, 1.0) 521 | self.vignette_spin.setSingleStep(0.01) 522 | self.vignette_spin.setValue(get("CameraSimulator", "vignette_strength", 0.35, float)) 523 | cam_layout.addRow("Vignette strength", self.vignette_spin) 524 | 525 | # Chromatic aberration strength 526 | self.chroma_spin = QDoubleSpinBox() 527 | self.chroma_spin.setRange(0.0, 10.0) 528 | self.chroma_spin.setSingleStep(0.1) 529 | self.chroma_spin.setValue(get("CameraSimulator", "chroma_strength", 1.2, float)) 530 | cam_layout.addRow("Chromatic aberration (px)", self.chroma_spin) 531 | 532 | # ISO scale 533 | self.iso_spin = QDoubleSpinBox() 534 | self.iso_spin.setRange(0.1, 16.0) 535 | self.iso_spin.setSingleStep(0.1) 536 | self.iso_spin.setValue(get("CameraSimulator", "iso_scale", 1.0, float)) 537 | cam_layout.addRow("ISO/exposure scale", self.iso_spin) 538 | 539 | # Read noise 540 | self.read_noise_spin = QDoubleSpinBox() 541 | self.read_noise_spin.setRange(0.0, 50.0) 542 | self.read_noise_spin.setSingleStep(0.1) 543 | self.read_noise_spin.setValue(get("CameraSimulator", "read_noise", 2.0, float)) 544 | cam_layout.addRow("Read noise (DN)", self.read_noise_spin) 545 | 546 | # Hot pixel prob 547 | self.hot_pixel_spin = QDoubleSpinBox() 548 | self.hot_pixel_spin.setDecimals(9) 549 | self.hot_pixel_spin.setRange(0.0, 1.0) 550 | self.hot_pixel_spin.setSingleStep(1e-6) 551 | self.hot_pixel_spin.setValue(get("CameraSimulator", "hot_pixel_prob", 1e-6, float)) 552 | cam_layout.addRow("Hot pixel prob", self.hot_pixel_spin) 553 | 554 | # Banding strength 555 | self.banding_spin = QDoubleSpinBox() 556 | self.banding_spin.setRange(0.0, 1.0) 557 | self.banding_spin.setSingleStep(0.01) 558 | self.banding_spin.setValue(get("CameraSimulator", "banding_strength", 0.0, float)) 559 | cam_layout.addRow("Banding strength", self.banding_spin) 560 | 561 | # Motion blur kernel 562 | self.motion_blur_spin = QSpinBox() 563 | self.motion_blur_spin.setRange(1, 51) 564 | self.motion_blur_spin.setValue(get("CameraSimulator", "motion_blur_kernel", 1, int)) 565 | cam_layout.addRow("Motion blur kernel", self.motion_blur_spin) 566 | 567 | self.camera_box.setVisible(getbool("CameraSimulator", "enabled", False)) 568 | self.params_box.setVisible(not getbool("General", "auto_mode", True)) 569 | self.texture_box.setVisible(not getbool("General", "auto_mode", True)) 570 | 571 | self.ref_hint = QLabel("AWB uses the 'AWB reference' chooser. FFT spectral matching uses the 'FFT Reference' chooser.") 572 | right_v.addWidget(self.ref_hint) 573 | 574 | self.analysis_input = AnalysisPanel(title="Input analysis") 575 | self.analysis_output = AnalysisPanel(title="Output analysis") 576 | right_v.addWidget(self.analysis_input) 577 | right_v.addWidget(self.analysis_output) 578 | 579 | right_v.addStretch(1) 580 | 581 | # Status bar 582 | self.status = QLabel("Ready") 583 | self.status.setStyleSheet("color:#bdbdbd;padding:6px") 584 | self.status.setAlignment(Qt.AlignLeft) 585 | self.status.setFixedHeight(28) 586 | self.status.setContentsMargins(6, 6, 6, 6) 587 | self.statusBar().addWidget(self.status) 588 | 589 | self.worker = None 590 | self._on_auto_mode_toggled(self.auto_mode_chk.checkState()) 591 | 592 | def _on_sim_camera_toggled(self, state): 593 | enabled = state == Qt.Checked 594 | self.camera_box.setVisible(enabled) 595 | 596 | def _on_auto_mode_toggled(self, state): 597 | is_auto = (state == Qt.Checked) 598 | self.auto_box.setVisible(is_auto) 599 | self.params_box.setVisible(not is_auto) 600 | self.texture_box.setVisible(not is_auto) 601 | self.camera_box.setVisible(not is_auto) 602 | self.blend_box.setVisible(not is_auto) 603 | 604 | def _update_strength_label(self, value): 605 | self.strength_label.setText(str(value)) 606 | 607 | def choose_input(self): 608 | path, _ = QFileDialog.getOpenFileName(self, "Choose input image", str(Path.home()), "Images (*.png *.jpg *.jpeg *.bmp *.tif)") 609 | if path: 610 | self.input_line.setText(path) 611 | self.load_preview(self.preview_in, path) 612 | self.analysis_input.update_from_path(path) 613 | out_suggest = str(Path(path).with_name(Path(path).stem + "_out" + Path(path).suffix)) 614 | if not self.output_line.text(): 615 | self.output_line.setText(out_suggest) 616 | 617 | def choose_ref(self): 618 | path, _ = QFileDialog.getOpenFileName(self, "Choose AWB reference image", str(Path.home()), "Images (*.png *.jpg *.jpeg *.bmp *.tif)") 619 | if path: 620 | self.ref_line.setText(path) 621 | 622 | def choose_fft_ref(self): 623 | path, _ = QFileDialog.getOpenFileName(self, "Choose FFT reference image", str(Path.home()), "Images (*.png *.jpg *.jpeg *.bmp *.tif)") 624 | if path: 625 | self.fft_ref_line.setText(path) 626 | 627 | def choose_output(self): 628 | path, _ = QFileDialog.getSaveFileName(self, "Choose output path", str(Path.home()), "JPEG (*.jpg *.jpeg);;PNG (*.png);;TIFF (*.tif)") 629 | if path: 630 | self.output_line.setText(path) 631 | 632 | def choose_lut(self): 633 | path, _ = QFileDialog.getOpenFileName(self, "Choose LUT file", str(Path.home()), "LUTs (*.png *.npy *.cube);;All files (*)") 634 | if path: 635 | self.lut_line.setText(path) 636 | 637 | def _on_lut_toggled(self, state): 638 | visible = (state == Qt.Checked) 639 | for w in self._lut_controls: 640 | w.setVisible(visible) 641 | 642 | def load_preview(self, widget: QLabel, path: str): 643 | if not path or not os.path.exists(path): 644 | widget.setText("No image") 645 | widget.setPixmap(QPixmap()) 646 | return 647 | pix = qpixmap_from_path(path, max_size=(widget.width(), widget.height())) 648 | widget.setPixmap(pix) 649 | 650 | def set_enabled_all(self, enabled: bool): 651 | for w in self.findChildren((QPushButton, QDoubleSpinBox, QSpinBox, QLineEdit, QComboBox, QCheckBox, QSlider, QToolButton)): 652 | w.setEnabled(enabled) 653 | 654 | def on_run(self): 655 | from types import SimpleNamespace 656 | inpath = self.input_line.text().strip() 657 | outpath = self.output_line.text().strip() 658 | if not inpath or not os.path.exists(inpath): 659 | QMessageBox.warning(self, "Missing input", "Please choose a valid input image.") 660 | return 661 | if not outpath: 662 | QMessageBox.warning(self, "Missing output", "Please choose an output path.") 663 | return 664 | 665 | awb_ref_val = self.ref_line.text() or None 666 | fft_ref_val = self.fft_ref_line.text() or None 667 | args = SimpleNamespace() 668 | 669 | if self.auto_mode_chk.isChecked(): 670 | strength = self.strength_slider.value() / 100.0 671 | args.noise_std = strength * 0.04 672 | args.clahe_clip = 1.0 + strength * 3.0 673 | args.cutoff = max(0.01, 0.4 - strength * 0.3) 674 | args.fstrength = strength * 0.95 675 | args.phase_perturb = strength * 0.1 676 | args.perturb = True 677 | args.perturb_magnitude = strength * 0.015 678 | args.jpeg_cycles = int(strength * 2) 679 | args.jpeg_qmin = max(1, int(95 - strength * 35)) 680 | args.jpeg_qmax = max(1, int(99 - strength * 25)) 681 | args.vignette_strength = strength * 0.6 682 | args.chroma_strength = strength * 2.0 683 | args.motion_blur_kernel = 1 + 2 * int(strength * 6) 684 | args.banding_strength = strength * 0.1 685 | args.tile = 8 686 | args.randomness = 0.05 687 | args.radial_smooth = 5 688 | args.fft_mode = "auto" 689 | args.fft_alpha = 1.0 690 | args.alpha = 1.0 691 | args.glcm = False 692 | args.glcm_distances = [1] 693 | args.glcm_angles = [0, np.pi/4, np.pi/2, 3*np.pi/4] 694 | args.glcm_levels = 256 695 | args.glcm_strength = 0.9 696 | args.lbp = False 697 | args.lbp_radius = 3 698 | args.lbp_n_points = 24 699 | args.lbp_method = "uniform" 700 | args.lbp_strength = 0.9 701 | seed_val = int(self.seed_spin.value()) 702 | args.seed = None if seed_val == 0 else seed_val 703 | args.sim_camera = True 704 | args.no_no_bayer = True 705 | args.iso_scale = 1.0 706 | args.read_noise = 2.0 707 | args.hot_pixel_prob = 1e-6 708 | args.clahe = True 709 | args.noise = True 710 | args.fft = True 711 | args.blend = True 712 | args.blend_tolerance = int(math.ceil(10*strength)) 713 | args.blend_min_region = int(math.ceil(-5.1111 / max(strength, 0.1) + 55.1111)) 714 | args.blend_max_samples = int(444444.4444 * min(max(strength, 0.1), 1.0) + 55555.5556) 715 | args.blend_n_jobs = os.cpu_count() or 4 716 | else: 717 | seed_val = int(self.seed_spin.value()) 718 | args.seed = None if seed_val == 0 else seed_val 719 | sim_camera = bool(self.sim_camera_chk.isChecked()) 720 | enable_bayer = bool(self.bayer_chk.isChecked()) 721 | args.noise_std = float(self.noise_spin.value()) 722 | args.clahe_clip = float(self.clahe_spin.value()) 723 | args.tile = int(self.tile_spin.value()) 724 | args.cutoff = float(self.cutoff_spin.value()) 725 | args.fstrength = float(self.fstrength_spin.value()) 726 | args.strength = float(self.fstrength_spin.value()) 727 | args.randomness = float(self.randomness_spin.value()) 728 | args.phase_perturb = float(self.phase_perturb_spin.value()) 729 | args.fft_mode = self.fft_mode_combo.currentText() 730 | args.fft_alpha = float(self.fft_alpha_spin.value()) 731 | args.alpha = float(self.fft_alpha_spin.value()) 732 | args.radial_smooth = int(self.radial_smooth_spin.value()) 733 | args.sim_camera = sim_camera 734 | args.no_no_bayer = bool(enable_bayer) 735 | args.jpeg_cycles = int(self.jpeg_cycles_spin.value()) 736 | args.jpeg_qmin = int(self.jpeg_qmin_spin.value()) 737 | args.jpeg_qmax = int(self.jpeg_qmax_spin.value()) 738 | args.vignette_strength = float(self.vignette_spin.value()) 739 | args.chroma_strength = float(self.chroma_spin.value()) 740 | args.iso_scale = float(self.iso_spin.value()) 741 | args.read_noise = float(self.read_noise_spin.value()) 742 | args.hot_pixel_prob = float(self.hot_pixel_spin.value()) 743 | args.banding_strength = float(self.banding_spin.value()) 744 | args.motion_blur_kernel = int(self.motion_blur_spin.value()) 745 | args.glcm = bool(self.glcm_chk.isChecked()) 746 | args.glcm_distances = [int(x) for x in self.glcm_distances_line.text().split()] 747 | args.glcm_angles = [float(x) for x in self.glcm_angles_line.text().split()] 748 | args.glcm_levels = int(self.glcm_levels_spin.value()) 749 | args.glcm_strength = float(self.glcm_strength_spin.value()) 750 | args.lbp = bool(self.lbp_chk.isChecked()) 751 | args.lbp_radius = int(self.lbp_radius_spin.value()) 752 | args.lbp_n_points = int(self.lbp_n_points_spin.value()) 753 | args.lbp_method = self.lbp_method_combo.currentText() 754 | args.lbp_strength = float(self.lbp_strength_spin.value()) 755 | # Set the new optional processing flags based on checkboxes 756 | args.noise = self.noise_enable_chk.isChecked() 757 | args.clahe = self.clahe_enable_chk.isChecked() 758 | args.fft = self.fft_enable_chk.isChecked() 759 | args.perturb = self.perturb_enable_chk.isChecked() 760 | args.perturb_magnitude = float(self.perturb_spin.value()) 761 | args.blend = bool(self.blend_chk.isChecked()) 762 | args.blend_tolerance = int(self.blend_tolerance.value()) 763 | args.blend_min_region = int(self.blend_min_region.value()) 764 | args.blend_max_samples = int(self.blend_max_samples.value()) 765 | args.blend_n_jobs = int(self.blend_n_jobs.value()) 766 | 767 | # AI Normalizer 768 | args.non_semantic = bool(self.ns_chk.isChecked()) 769 | if args.non_semantic: 770 | try: 771 | import torch 772 | except ImportError: 773 | QMessageBox.warning(self, "Missing Dependency", "Torch (PyTorch) is required for AI Normalizer but is not installed.") 774 | self.set_enabled_all(True) 775 | return 776 | args.ns_iterations = int(self.ns_iterations_spin.value()) 777 | args.ns_learning_rate = float(self.ns_lr_spin.value()) 778 | args.ns_t_lpips = float(self.ns_t_lpips_spin.value()) 779 | args.ns_t_l2 = float(self.ns_t_l2_spin.value()) 780 | args.ns_c_lpips = float(self.ns_c_lpips_spin.value()) 781 | args.ns_c_l2 = float(self.ns_c_l2_spin.value()) 782 | args.ns_grad_clip = float(self.ns_grad_clip_spin.value()) 783 | 784 | # AWB handling 785 | if self.awb_chk.isChecked(): 786 | args.awb = True 787 | args.ref = awb_ref_val 788 | else: 789 | args.awb = False 790 | args.ref = None 791 | 792 | # FFT spectral matching reference 793 | args.fft_ref = fft_ref_val 794 | 795 | # LUT handling 796 | if self.lut_chk.isChecked(): 797 | lut_path = self.lut_line.text().strip() 798 | args.lut = lut_path if lut_path else None 799 | args.lut_strength = float(self.lut_strength_spin.value()) 800 | else: 801 | args.lut = None 802 | args.lut_strength = 1.0 803 | 804 | self.worker = Worker(inpath, outpath, args) 805 | self.worker.finished.connect(self.on_finished) 806 | self.worker.error.connect(self.on_error) 807 | self.worker.started.connect(lambda: self.on_worker_started()) 808 | self.worker.start() 809 | 810 | self.progress.setRange(0, 0) 811 | self.status.setText("Processing...") 812 | self.set_enabled_all(False) 813 | 814 | def on_worker_started(self): 815 | pass 816 | 817 | def on_finished(self, outpath): 818 | self.progress.setRange(0, 100) 819 | self.progress.setValue(100) 820 | self.status.setText("Done — saved to: " + outpath) 821 | self.load_preview(self.preview_out, outpath) 822 | self.analysis_output.update_from_path(outpath) 823 | self.set_enabled_all(True) 824 | 825 | def on_error(self, msg, traceback_text): 826 | from PyQt5.QtWidgets import QDialog, QTextEdit 827 | self.progress.setRange(0, 100) 828 | self.progress.setValue(0) 829 | self.status.setText("Error") 830 | 831 | dialog = QDialog(self) 832 | dialog.setWindowTitle("Processing Error") 833 | dialog.setMinimumSize(700, 480) 834 | layout = QVBoxLayout(dialog) 835 | 836 | error_label = QLabel(f"Error: {msg}") 837 | error_label.setWordWrap(True) 838 | layout.addWidget(error_label) 839 | 840 | traceback_edit = QTextEdit() 841 | traceback_edit.setReadOnly(True) 842 | traceback_edit.setText(traceback_text) 843 | traceback_edit.setStyleSheet("font-family: monospace; font-size: 12px;") 844 | layout.addWidget(traceback_edit) 845 | 846 | ok_button = QPushButton("OK") 847 | ok_button.clicked.connect(dialog.accept) 848 | layout.addWidget(ok_button) 849 | 850 | dialog.exec_() 851 | self.set_enabled_all(True) 852 | 853 | def open_output_folder(self): 854 | out = self.output_line.text().strip() 855 | if not out: 856 | QMessageBox.information(self, "No output", "No output path set yet.") 857 | return 858 | folder = os.path.dirname(os.path.abspath(out)) 859 | if not os.path.exists(folder): 860 | QMessageBox.warning(self, "Not found", "Output folder does not exist: " + folder) 861 | return 862 | if sys.platform.startswith('darwin'): 863 | os.system(f'open "{folder}"') 864 | elif os.name == 'nt': 865 | os.startfile(folder) --------------------------------------------------------------------------------