-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathresize_image.py
62 lines (55 loc) · 2.41 KB
/
resize_image.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import numpy as np
import torch
from PIL import Image
class ResizeImage:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE", {}),
"width": ("INT", {"default": 256}),
"height": ("INT", {"default": 256}),
},
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
}
FUNCTION = "resize_image"
RETURN_TYPES = ("IMAGE",)
OUTPUT_NODE = True
CATEGORY = "Bjornulf"
def resize_image(self, image, width=256, height=256, prompt=None, extra_pnginfo=None):
# Ensure the input image is on CPU and convert to numpy array
image_np = image.cpu().numpy()
# Check if the image is in the format [batch, height, width, channel]
if image_np.ndim == 4:
# If so, we'll process each image in the batch
resized_images = []
for img in image_np:
# Convert to PIL Image
pil_img = Image.fromarray((img * 255).astype(np.uint8))
# Resize
resized_pil = pil_img.resize((width, height), Image.LANCZOS)
# Convert back to numpy and normalize
resized_np = np.array(resized_pil).astype(np.float32) / 255.0
resized_images.append(resized_np)
# Stack the resized images back into a batch
resized_batch = np.stack(resized_images)
# Convert to torch tensor
resized_tensor = torch.from_numpy(resized_batch)
else:
# If it's a single image, process it directly
# Convert to PIL Image
pil_img = Image.fromarray((image_np * 255).astype(np.uint8))
# Resize
resized_pil = pil_img.resize((width, height), Image.LANCZOS)
# Convert back to numpy and normalize
resized_np = np.array(resized_pil).astype(np.float32) / 255.0
# Add batch dimension if it was originally present
if image.dim() == 4:
resized_np = np.expand_dims(resized_np, axis=0)
# Convert to torch tensor
resized_tensor = torch.from_numpy(resized_np)
# Update metadata if needed
if extra_pnginfo is not None:
extra_pnginfo["resized_width"] = width
extra_pnginfo["resized_height"] = height
return (resized_tensor, prompt, extra_pnginfo)