File size: 2,937 Bytes
37d34c5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# 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
}
|