-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathImageSmartCrop.py
61 lines (53 loc) · 2 KB
/
ImageSmartCrop.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
from .SmartCrop import SmartCrop
from PIL import Image, ImageDraw
import torch
import numpy as np
# Tensor to PIL
def tensor2pil(image):
return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))
# Convert PIL to Tensor
def pil2tensor(image):
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
class ImageSmartCrop:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"width": ("INT", {
"default": 1024,
"min": 0, #Minimum value
"max": 2048, #Maximum value
"step": 1, #Slider's step
"display": "number" # Cosmetic only: display as "number" or "slider"
}),
"height": ("INT", {
"default": 1024,
"min": 0, #Minimum value
"max": 2048, #Maximum value
"step": 1, #Slider's step
"display": "number" # Cosmetic only: display as "number" or "slider"
}),
},
}
CATEGORY = "👽 ComfyLab/📐 SmartCrop 智能裁剪"
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("image",)
FUNCTION = "imageSmartCrop"
def imageSmartCrop(self, image, width, height):
cropper = SmartCrop()
image = tensor2pil(image)
result = cropper.crop(image, width, height)
box = (
result['top_crop']['x'],
result['top_crop']['y'],
result['top_crop']['width'] + result['top_crop']['x'],
result['top_crop']['height'] + result['top_crop']['y']
)
cropped_image = image.crop(box)
cropped_image.thumbnail((width, height), Image.Resampling.LANCZOS)
# cropped_image.save(options.outputfile, 'JPEG', quality=90)
image_tensor = pil2tensor(cropped_image)
return (image_tensor,)