Upload TTP_tile_preprocessor.py
Browse filesupdate the comfyui custom_node for image preprocess. can simulate the webui pre-processor effect for controlnet image adjustment
- TTP_tile_preprocessor.py +70 -0
TTP_tile_preprocessor.py
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
from PIL import Image
|
5 |
+
|
6 |
+
NODE_NAME = 'TTPlanet_Tile_Preprocessor'
|
7 |
+
|
8 |
+
# 图像转换函数
|
9 |
+
def pil2tensor(image: Image) -> torch.Tensor:
|
10 |
+
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
|
11 |
+
|
12 |
+
def tensor2pil(t_image: torch.Tensor) -> Image:
|
13 |
+
return Image.fromarray(np.clip(255.0 * t_image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))
|
14 |
+
|
15 |
+
class TTPlanet_Tile_Preprocessor:
|
16 |
+
def __init__(self):
|
17 |
+
pass
|
18 |
+
|
19 |
+
@classmethod
|
20 |
+
def INPUT_TYPES(cls):
|
21 |
+
return {
|
22 |
+
"required": {
|
23 |
+
"image": ("IMAGE",), # 输入的tensor图像
|
24 |
+
"scale_factor": ("FLOAT", {"default": 2.0, "min": 1.0, "max": 8.0, "step": 0.1}), # 缩放因子
|
25 |
+
},
|
26 |
+
"optional": {}
|
27 |
+
}
|
28 |
+
|
29 |
+
RETURN_TYPES = ("IMAGE",)
|
30 |
+
RETURN_NAMES = ("image_output",)
|
31 |
+
FUNCTION = 'process_image'
|
32 |
+
CATEGORY = 'TTP_TILE'
|
33 |
+
|
34 |
+
def process_image(self, image, scale_factor):
|
35 |
+
ret_images = []
|
36 |
+
|
37 |
+
for i in image:
|
38 |
+
# Convert tensor to PIL for processing
|
39 |
+
_canvas = tensor2pil(torch.unsqueeze(i, 0)).convert('RGB')
|
40 |
+
|
41 |
+
# Convert PIL to OpenCV format
|
42 |
+
img_np = np.array(_canvas)[:, :, ::-1]
|
43 |
+
|
44 |
+
# 获取原始尺寸
|
45 |
+
height, width = img_np.shape[:2]
|
46 |
+
|
47 |
+
# 计算新尺寸
|
48 |
+
new_width = int(width / scale_factor)
|
49 |
+
new_height = int(height / scale_factor)
|
50 |
+
|
51 |
+
# 1. 使用cv2.INTER_AREA方法缩小图像
|
52 |
+
resized_down = cv2.resize(img_np, (new_width, new_height), interpolation=cv2.INTER_AREA)
|
53 |
+
|
54 |
+
# 2. 使用linear方法放大回原尺寸
|
55 |
+
resized_img = cv2.resize(resized_down, (width, height), interpolation=cv2.INTER_CUBIC)
|
56 |
+
|
57 |
+
# Convert OpenCV back to PIL and then to tensor
|
58 |
+
pil_img = Image.fromarray(resized_img[:, :, ::-1])
|
59 |
+
tensor_img = pil2tensor(pil_img)
|
60 |
+
ret_images.append(tensor_img)
|
61 |
+
|
62 |
+
return (torch.cat(ret_images, dim=0),)
|
63 |
+
|
64 |
+
NODE_CLASS_MAPPINGS = {
|
65 |
+
"Image Processing: TTPlanet_Tile_Preprocessor": TTPlanet_Tile_Preprocessor
|
66 |
+
}
|
67 |
+
|
68 |
+
NODE_DISPLAY_NAME_MAPPINGS = {
|
69 |
+
"Image Processing: TTPlanet_Tile_Preprocessor": "TTPlanet Tile Preprocessor"
|
70 |
+
}
|