yum-archive/Tooner
A toon shader for Unity's BIRP.
git clone https://git.yummers.dev/yum-archive/Tooner
9b52e08
master
1#!/usr/bin/env python3 2 3import numpy as np 4import cv2 5import argparse 6import os 7 8def compute_sdf(img, scale_factor): 9 # Convert to binary image if not already 10 _, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) 11 12 # Compute distance transform for both foreground and background 13 dist_transform_fg = cv2.distanceTransform(binary, cv2.DIST_L2, 5) 14 dist_transform_bg = cv2.distanceTransform(255 - binary, cv2.DIST_L2, 5) 15 16 # Combine the distance fields and scale by factor 17 sdf = (dist_transform_fg - dist_transform_bg) / scale_factor 18 19 # Normalize values to [0, 255] range 20 sdf_min = np.min(sdf) 21 sdf_max = np.max(sdf) 22 sdf = ((sdf - sdf_min) * 255 / (sdf_max - sdf_min)) 23 24 return sdf.astype(np.uint8) 25 26def main(): 27 parser = argparse.ArgumentParser(description='Generate SDF from black and white image') 28 parser.add_argument('input_images', nargs='+', help='Path to input image(s)') 29 parser.add_argument('--scale', type=float, default=1.0, 30 help='Scale factor for distance (in texels)') 31 args = parser.parse_args() 32 33 # Process each input image 34 for input_path in args.input_images: 35 # Get input and output paths 36 filename, ext = os.path.splitext(input_path) 37 output_path = f"{filename}-sdf{ext}" 38 39 # Read input image 40 img = cv2.imread(input_path, cv2.IMREAD_GRAYSCALE) 41 if img is None: 42 print(f"Error: Could not read image {input_path}") 43 continue 44 45 # Compute SDF with scale factor 46 sdf = compute_sdf(img, args.scale) 47 48 # Save result 49 cv2.imwrite(output_path, sdf) 50 print(f"SDF generated and saved to {output_path}") 51 52if __name__ == "__main__": 53 main()