152 lines
5.5 KiB
Python
152 lines
5.5 KiB
Python
"""Generic image utilities for ComfyUI."""
|
|
|
|
import os
|
|
import re
|
|
import time
|
|
import uuid
|
|
from collections import OrderedDict
|
|
from pathlib import Path
|
|
|
|
from PIL import Image
|
|
|
|
import folder_paths
|
|
|
|
|
|
_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif", ".tif", ".tiff"}
|
|
_SERVE_TOKENS = OrderedDict()
|
|
|
|
|
|
def resolve_serve_token(token):
|
|
return _SERVE_TOKENS.get(str(token or ""))
|
|
|
|
|
|
def _folder_is_image(name):
|
|
return Path(str(name)).suffix.lower() in _IMAGE_EXTENSIONS
|
|
|
|
|
|
def _list_folder_image_files(real_folder, recursive=False):
|
|
root = Path(real_folder)
|
|
paths = root.rglob("*") if recursive else root.glob("*")
|
|
return sorted(str(path.relative_to(root)).replace(os.sep, "/") for path in paths if path.is_file() and _folder_is_image(path.name))
|
|
|
|
|
|
def _next_counter_for_relative_path(base_directory, relative_template):
|
|
template = str(relative_template).replace("%counter%", "*")
|
|
parent = Path(base_directory) / Path(template).parent
|
|
stem = Path(template).name
|
|
if not parent.exists():
|
|
return 1
|
|
pattern = re.compile(re.escape(stem).replace(r"\*", r"(\d+)") + r"(?:\.[^.]+)?$")
|
|
highest = 0
|
|
for path in parent.iterdir():
|
|
match = pattern.match(path.name)
|
|
if match:
|
|
highest = max(highest, int(match.group(1)))
|
|
return highest + 1
|
|
|
|
|
|
def _image_to_pil(image):
|
|
array = image.detach().cpu().numpy() if hasattr(image, "detach") else image.cpu().numpy()
|
|
array = (array[..., :3].clip(0, 1) * 255).astype("uint8")
|
|
return Image.fromarray(array)
|
|
|
|
|
|
class DumasImageCompareNode:
|
|
@classmethod
|
|
def INPUT_TYPES(cls):
|
|
return {"optional": {"image1": ("IMAGE",), "image2": ("IMAGE",)}}
|
|
|
|
RETURN_TYPES = ("IMAGE",)
|
|
RETURN_NAMES = ("result",)
|
|
FUNCTION = "compare_images"
|
|
CATEGORY = "Dumas/Image"
|
|
OUTPUT_NODE = True
|
|
|
|
def compare_images(self, image1=None, image2=None):
|
|
images = []
|
|
for slot, image in enumerate((image1, image2), 1):
|
|
if image is None:
|
|
continue
|
|
path = Path(folder_paths.get_temp_directory()) / f"dumas_compare_{slot}.png"
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
_image_to_pil(image[0]).save(path)
|
|
images.append({"filename": path.name, "subfolder": "", "type": "temp", "slot": slot})
|
|
return {"ui": {"images": images}, "result": (image2 or image1,)}
|
|
|
|
|
|
class DumasSaveImageNode:
|
|
@classmethod
|
|
def INPUT_TYPES(cls):
|
|
return {
|
|
"required": {
|
|
"images": ("IMAGE",),
|
|
"folder": ("STRING", {"default": ""}),
|
|
"pattern": ("STRING", {"default": "image_%counter%"}),
|
|
"format": (["png", "jpg", "webp"], {"default": "png"}),
|
|
"quality": ("INT", {"default": 95, "min": 1, "max": 100}),
|
|
"embed_workflow": ("BOOLEAN", {"default": True}),
|
|
"save_on_run": ("BOOLEAN", {"default": True}),
|
|
},
|
|
"optional": {"name": ("STRING", {"default": ""}), "name_2": ("STRING", {"default": ""})},
|
|
}
|
|
|
|
RETURN_TYPES = ()
|
|
FUNCTION = "save_images"
|
|
CATEGORY = "Dumas/Image"
|
|
OUTPUT_NODE = True
|
|
|
|
def save_images(self, images, folder, pattern, format, quality, embed_workflow, save_on_run, name="", name_2="", **_kwargs):
|
|
del embed_workflow, save_on_run
|
|
base = Path(folder or folder_paths.get_output_directory())
|
|
base.mkdir(parents=True, exist_ok=True)
|
|
for index, image in enumerate(images):
|
|
width, height = int(image.shape[2]), int(image.shape[1])
|
|
stem = pattern.replace("%input%", _safe_token(name)).replace("%input2%", _safe_token(name_2))
|
|
stem = stem.replace("%width%", str(width)).replace("%height%", str(height)).replace("%batch_num%", str(index))
|
|
stem = re.sub(r"%counter%", f"{index + 1:03d}", stem)
|
|
path = base / f"{stem}.{format}"
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
options = {"quality": quality} if format in {"jpg", "webp"} else {}
|
|
_image_to_pil(image).save(path, **options)
|
|
return {"ui": {"images": []}}
|
|
|
|
|
|
def _safe_token(value):
|
|
return re.sub(r"[^A-Za-z0-9_.-]+", "_", Path(str(value or "")).stem).strip("._")
|
|
|
|
|
|
class DumasLoadImagesFolderNode:
|
|
@classmethod
|
|
def INPUT_TYPES(cls):
|
|
return {"required": {"folder": ("STRING", {"default": ""})}}
|
|
|
|
RETURN_TYPES = ("IMAGE", "MASK", "INT", "INT", "STRING", "INT", "INT")
|
|
RETURN_NAMES = ("image", "mask", "width", "height", "filename", "index", "total")
|
|
FUNCTION = "load"
|
|
CATEGORY = "Dumas/Image"
|
|
|
|
def load(self, folder):
|
|
files = sorted(path for path in Path(folder).iterdir() if path.suffix.lower() in _IMAGE_EXTENSIONS) if folder and Path(folder).is_dir() else []
|
|
if not files:
|
|
raise ValueError("No image files found in the selected folder.")
|
|
image = Image.open(files[0]).convert("RGB")
|
|
import torch
|
|
import numpy as np
|
|
tensor = torch.from_numpy(np.asarray(image).astype("float32") / 255.0)[None, ...]
|
|
height, width = image.height, image.width
|
|
mask = torch.zeros((1, height, width), dtype=torch.float32)
|
|
return tensor, mask, width, height, files[0].name, 0, len(files)
|
|
|
|
|
|
NODE_CLASS_MAPPINGS = {
|
|
"DumasImageCompare": DumasImageCompareNode,
|
|
"DumasSaveImage": DumasSaveImageNode,
|
|
"DumasLoadImagesFolder": DumasLoadImagesFolderNode,
|
|
}
|
|
|
|
NODE_DISPLAY_NAME_MAPPINGS = {
|
|
"DumasImageCompare": "Dumas Image Compare",
|
|
"DumasSaveImage": "Save Image Dumas",
|
|
"DumasLoadImagesFolder": "Load Images from Folder Dumas",
|
|
}
|