import torch
import numpy as np
from torch import nn
from nodes import *
class SharpNoiseBlurMaps:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"sharp_quantile": ("INT", {"default":80, "min":50, "max":100, "step":1}),
"noise_quantile": ("INT", {"default":95, "min":50, "max":100, "step":1}),
"blur_quantile": ("INT", {"default":90, "min":50, "max":100, "step":1}),
},
}
RETURN_TYPES = ("IMAGE", "IMAGE", "IMAGE")
FUNCTION = "compute_maps"
CATEGORY = "image_processing"
def compute_maps(self, image, sharp_quantile, noise_quantile, blur_quantile):
image = image[0] # Assuming batch size 1
h, w, c = image.shape
# Convert to grayscale
gray = 0.299 * image[..., 0] + 0.587 * image[..., 1] + 0.114 * image[..., 2]
gray = gray.unsqueeze(-1) # Shape (H, W, 1)
# Reshape for convolution operations
gray_tensor = gray.permute(2, 0, 1).unsqueeze(0).float() # (1, 1, H, W)
# Sharpness Map (Laplacian Variance)
laplace_kernel = torch.tensor([
[0.0, 1.0, 0.0],
[1.0, -4.0, 1.0],
[0.0, 1.0, 0.0]
]).view(1, 1, 3, 3).float()
conv_laplace = nn.functional.conv2d(
gray_tensor, laplace_kernel, padding=1
)
lap_var = torch.abs(conv_laplace).squeeze().permute(1, 2, 0).float()
# Noise Map (Local Standard Deviation)
kernel_size = 5
padding = kernel_size // 2
gray_unfolded = nn.functional.unfold(
gray_tensor, kernel_size=(kernel_size, kernel_size), padding=padding
)
mean = gray_unfolded.mean(dim=1, keepdim=True)
var = (gray_unfolded ** 2).mean(dim=1, keepdim=True) - mean ** 2
sigma = torch.sqrt(var).view(
1, 1, gray_tensor.shape[2], gray_tensor.shape[3]
)
sigma = sigma.permute(0, 2, 3, 1).squeeze(-1).float()
# Blur-Loss Map (Gaussian Blur Difference)
sigma_gauss = 1.0
blurred = nn.functional.gaussian_blur(
gray_tensor, kernel_size=(5,5), sigma=(sigma_gauss,)
)
blur_loss = torch.abs(gray_tensor - blurred).squeeze().permute(1, 2, 0).float()
# Compute thresholds using quantiles
sharp_th = torch.quantile(lap_var.view(-1), sharp_quantile / 100.0)
noise_th = torch.quantile(sigma.view(-1), noise_quantile / 100.0)
blur_th = torch.quantile(blur_loss.view(-1), blur_quantile / 100.0)
# Create binary maps (1.0 where above threshold, 0.0 otherwise)
sharp_map = (lap_var >= sharp_th).float()
noise_map = (sigma >= noise_th).float()
blur_map = (blur_loss >= blur_th).float()
# Convert to 3-channel RGB format for ComfyUI compatibility
def to_rgb(tensor):
return tensor.unsqueeze(-1).expand(-1, -1, 3).unsqueeze(0)
return (
to_rgb(sharp_map),
to_rgb(noise_map),
to_rgb(blur_map)
)
NODE_CLASS_MAPPINGS = {
"SharpNoiseBlurMaps": SharpNoiseBlurMaps
}
NODE_DISPLAY_NAME_MAPPINGS = {
"SharpNoiseBlurMaps": "Sharp/Noise/Blur Maps"
}