""" Tạo training pairs cho super-resolution: - Lấy ảnh 4K gốc làm target (ground truth) - Downscale xuống 2K và 1K làm input - Thêm degradation (noise, blur, compression) cho realistic """ import argparse import random from pathlib import Path from concurrent.futures import ProcessPoolExecutor, as_completed import cv2 import numpy as np from tqdm import tqdm INPUT_DIR = Path("/home/adminuser/chungcat/data/raw/4k") OUTPUT_BASE = Path("/home/adminuser/chungcat/data/processed") def add_degradation(img, level="light"): if level == "none": return img if random.random() < 0.3: ksize = random.choice([3, 5]) img = cv2.GaussianBlur(img, (ksize, ksize), 0) if random.random() < 0.3: noise = np.random.normal(0, random.uniform(1, 5), img.shape).astype(np.float32) img = np.clip(img.astype(np.float32) + noise, 0, 255).astype(np.uint8) if random.random() < 0.3: quality = random.randint(70, 95) _, encoded = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, quality]) img = cv2.imdecode(encoded, cv2.IMREAD_COLOR) return img def process_image(img_path, output_dirs, target_sizes, degradation="light"): try: img = cv2.imread(str(img_path), cv2.IMREAD_COLOR) if img is None: return None h, w = img.shape[:2] if w < 3840 or h < 2160: return None stem = img_path.stem # Crop to 4096x4096 or keep aspect ratio # For training, use random crops crop_size_4k = 4096 crop_size_2k = 2048 crop_size_1k = 1024 if h >= crop_size_4k and w >= crop_size_4k: y = random.randint(0, h - crop_size_4k) x = random.randint(0, w - crop_size_4k) crop_4k = img[y:y+crop_size_4k, x:x+crop_size_4k] else: crop_4k = cv2.resize(img, (crop_size_4k, crop_size_4k), interpolation=cv2.INTER_LANCZOS4) # Downscale to 2K crop_2k = cv2.resize(crop_4k, (crop_size_2k, crop_size_2k), interpolation=cv2.INTER_AREA) # Downscale to 1K crop_1k = cv2.resize(crop_4k, (crop_size_1k, crop_size_1k), interpolation=cv2.INTER_AREA) # Add degradation to inputs crop_2k_degraded = add_degradation(crop_2k, degradation) crop_1k_degraded = add_degradation(crop_1k, degradation) # Save cv2.imwrite(str(output_dirs["4k"] / f"{stem}.png"), crop_4k) cv2.imwrite(str(output_dirs["2k"] / f"{stem}.png"), crop_2k_degraded) cv2.imwrite(str(output_dirs["1k"] / f"{stem}.png"), crop_1k_degraded) return stem except Exception as e: print(f"Error processing {img_path}: {e}") return None def main(): parser = argparse.ArgumentParser(description="Create SR training pairs from 4K images") parser.add_argument("--input-dir", type=Path, default=INPUT_DIR) parser.add_argument("--output-dir", type=Path, default=OUTPUT_BASE / "sr_pairs") parser.add_argument("--degradation", choices=["none", "light", "heavy"], default="light") parser.add_argument("--workers", type=int, default=16) parser.add_argument("--max-images", type=int, default=None) args = parser.parse_args() output_dirs = { "4k": args.output_dir / "4k_target", "2k": args.output_dir / "2k_input", "1k": args.output_dir / "1k_input", } for d in output_dirs.values(): d.mkdir(parents=True, exist_ok=True) images = list(args.input_dir.glob("*.jpg")) + list(args.input_dir.glob("*.png")) if args.max_images: images = images[:args.max_images] print(f"Processing {len(images)} images...") processed = 0 with ProcessPoolExecutor(max_workers=args.workers) as executor: futures = [ executor.submit(process_image, img, output_dirs, None, args.degradation) for img in images ] for future in tqdm(as_completed(futures), total=len(futures)): result = future.result() if result: processed += 1 print(f"Done! Processed {processed}/{len(images)} images") if __name__ == "__main__": main()