4/07/2024

comfyui image resize simple custom node code

 refer to code for your scratch 

:

# from .imagetransfer import ImageTransfer
# __all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']

from PIL import Image
import torch
from torchvision.transforms.functional import to_pil_image, to_tensor

class ImageTransfer:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
},
}

RETURN_TYPES = ("IMAGE",)
FUNCTION = "transfer"
CATEGORY = "Utility"

def transfer(self, image):
# Ensure we're not tracking gradients for this operation
print(f"Type of the image tensor: {image.dtype}")
print(f"Dimensions of the image tensor: {image.shape}")

with torch.no_grad():
# Check if image tensor is in the expected format [1, H, W, C]
if image.dim() == 4 and image.shape[-1] in [1, 3]:
# Permute the tensor to match [C, H, W] format expected by to_pil_image
image_permuted = image.squeeze(0).permute(2, 0, 1)
# Convert the PyTorch tensor to a PIL Image
image_pil = to_pil_image(image_permuted)
# Resize the PIL Image
resized_image_pil = image_pil.resize((256, 256), Image.LANCZOS)
# Convert the PIL Image back to a PyTorch tensor
resized_image_tensor = to_tensor(resized_image_pil)
# Permute dimensions back to [1, H, W, C] and add the batch dimension
resized_image_tensor = resized_image_tensor.permute(1, 2, 0).unsqueeze(0)
print(f"Type of the resized image tensor: {resized_image_tensor.dtype}")
print(f"Dimensions of the resized image tensor: {resized_image_tensor.shape}")

return (resized_image_tensor,)
else:
raise ValueError("Image tensor format not recognized. Expected format: [1, H, W, C].")

NODE_CLASS_MAPPINGS = {
"ImageTransfer": ImageTransfer
}

NODE_DISPLAY_NAME_MAPPINGS = {
"ImageTransfer": "Image Transfer"
}


No comments:

Post a Comment