赞
踩
ImageResize
from .utils import max_, min_
from nodes import MAX_RESOLUTION
import comfy.utils
import torch
import torch.nn.functional as F
import torchvision.transforms.v2 as T
import warnings
warnings.filterwarnings('ignore', module="torchvision")
import math
import os
import numpy as np
这部分代码导入了处理图像所需的各种库和模块。torch
和 torchvision
用于图像的变换处理,numpy
用于数组操作,而 comfy.utils
可能包含一些方便的自定义工具函数。
ImageResize
class ImageResize: @classmethod def INPUT_TYPES(s): return { "required": { "image": ("IMAGE",), "width": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8, }), "height": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8, }), "interpolation": (["nearest", "bilinear", "bicubic", "area", "nearest-exact", "lanczos"],), "method": (["stretch", "keep proportion", "fill / crop", "pad"],), "condition": (["always", "downscale if bigger", "upscale if smaller", "if bigger area", "if smaller area"],), "multiple_of": ("INT", { "default": 0, "min": 0, "max": 512, "step": 1, }), } } RETURN_TYPES = ("IMAGE", "INT", "INT",) RETURN_NAMES = ("IMAGE", "width", "height",) FUNCTION = "execute"
此类定义了如何接受输入并执行图像大小调整。它包括多种调整大小的方法、插值方式、以及何时执行大小调整的条件。
execute
def execute(self, image, width, height, method="stretch", interpolation="nearest", condition="always", multiple_of=0, keep_proportion=False):
_, oh, ow, _ = image.shape
x = y = x2 = y2 = 0
pad_left = pad_right = pad_top = pad_bottom = 0
该方法是类的主要功能实现部分,用于调整传入图像的大小。根据提供的方法、宽度、高度、插值方式和其他参数进行操作。
if keep_proportion:
method = "keep proportion"
if multiple_of > 1:
width = width - (width % multiple_of)
height = height - (height % multiple_of)
如果指定保持图像的比例或确保宽度和高度是某个数的倍数,此处进行相应调整。
if method == 'keep proportion' or method == 'pad':
# 代码省略,详细计算调整后的新宽度和高度
对于保持比例或填充方法,计算调整后的新尺寸,确保图像比例不变或者按需填充空白。
elif method.startswith('fill'): width = width if width > 0 else ow height = height if height > 0 else oh ratio = max(width / ow, height / oh) new_width = round(ow*ratio) new_height = round(oh*ratio) x = (new_width - width) // 2 y = (new_height - height) // 2 x2 = x + width y2 = y + height if x2 > new_width: x -= (x2 - new_width) if x < 0: x = 0 if y2 > new_height: y -= (y2 - new_height) if y < 0: y = 0 width = new_width height = new_height else: width = width if width > 0 else ow height = height if height > 0 else oh # 代码省略,处理填充或裁剪的情况
处理填充或裁剪图像的情况,确保图像符合指定的尺寸。
if "always" in condition \
or ("downscale if bigger" == condition and (oh > height or ow > width)) or ("upscale if smaller" == condition and (oh < height or ow < width)) \
or ("bigger area" in condition and (oh * ow > height * width)) or ("smaller area" in condition and (oh * ow < height * width)):
outputs = image.permute(0,3,1,2)
# 根据选择的插值方式调整图像大小
在满足指定条件的情况下,
调整图像的大小。这部分代码检查是否需要调整图像大小,并执行实际的调整大小操作。
return(outputs, outputs.shape[2], outputs.shape[1],)
函数返回调整后的图像以及其宽度和高度。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。