# By WASasquatch (Discord: WAS#0263) import torch import numpy as np from PIL import Image, ImageFilter class fDOF: def __init__(self): pass @classmethod def INPUT_TYPES(cls): return { "required": { "image": ("IMAGE",), "depth": ("IMAGE",), "mode": (["mock","gaussian","box"],), "radius": ("INT", {"default": 8, "min": 1, "max": 128, "step": 1}), "samples": ("INT", {"default": 1, "min": 1, "max": 3, "step": 1}), }, } RETURN_TYPES = ("IMAGE",) FUNCTION = "fdof_composite" CATEGORY = "WAS" def fdof_composite(self, image, depth, radius, samples, mode): if 'opencv-python' not in self.packages(): print("Installing CV2...") subprocess.check_call([sys.executable, '-m', 'pip', '-q', 'install', 'opencv-python']) import cv2 as cv #Convert tensor to a PIL Image i = 255. * image.cpu().numpy().squeeze() img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)) d = 255. * depth.cpu().numpy().squeeze() depth_img = Image.fromarray(np.clip(d, 0, 255).astype(np.uint8)) #Apply Fake Depth of Field fdof_image = self.portraitBlur(img, depth_img, radius, samples, mode) return ( torch.from_numpy(np.array(fdof_image).astype(np.float32) / 255.0).unsqueeze(0), ) def medianFilter(self, img, diameter, sigmaColor, sigmaSpace): import cv2 as cv diameter = int(diameter); sigmaColor = int(sigmaColor); sigmaSpace = int(sigmaSpace) img = img.convert('RGB') img = cv.cvtColor(np.array(img), cv.COLOR_RGB2BGR) img = cv.bilateralFilter(img, diameter, sigmaColor, sigmaSpace) img = cv.cvtColor(np.array(img), cv.COLOR_BGR2RGB) return Image.fromarray(img).convert('RGB') def portraitBlur(self, img, mask, radius=5, samples=1, mode = 'mock'): mask = mask.resize(img.size).convert('L') if mode == 'mock': bimg = self.medianFilter(img, radius, (radius * 1500), 75) elif mode == 'gaussian': bimg = img.filter(ImageFilter.GaussianBlur(radius = radius)) elif mode == 'box': bimg = img.filter(ImageFilter.BoxBlur(radius)) bimg.convert(img.mode) rimg = None if samples > 1: for i in range(samples): if i == 0: rimg = Image.composite(img, bimg, mask) else: rimg = Image.composite(rimg, bimg, mask) else: rimg = Image.composite(img, bimg, mask).convert('RGB') return rimg def packages(self): import sys, subprocess return [r.decode().split('==')[0] for r in subprocess.check_output([sys.executable, '-m', 'pip', 'freeze']).split()] NODE_CLASS_MAPPINGS = { "fDOF": fDOF }