wyysf commited on
Commit
0f8544d
1 Parent(s): b0a1e82

Upload utils.py

Browse files
Files changed (1) hide show
  1. apps/utils.py +174 -0
apps/utils.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Optional, Tuple, List
2
+ from dataclasses import dataclass
3
+ import os
4
+ import sys
5
+ proj_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
6
+ sys.path.append(os.path.join(proj_dir))
7
+ import time
8
+ import cv2
9
+ import gradio as gr
10
+ import numpy as np
11
+ import torch
12
+ import PIL
13
+ from PIL import Image
14
+ import rembg
15
+ from rembg import remove
16
+ rembg_session = rembg.new_session()
17
+ from segment_anything import sam_model_registry, SamPredictor
18
+
19
+ import craftsman
20
+ from craftsman.systems.base import BaseSystem
21
+ from craftsman.utils.config import ExperimentConfig, load_config
22
+
23
+ parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
24
+
25
+ def check_input_image(input_image):
26
+ if input_image is None:
27
+ raise gr.Error("No image uploaded!")
28
+
29
+ def load_model(
30
+ ckpt_path: str,
31
+ config_path: str,
32
+ device = "cuda"
33
+ ):
34
+ cfg: ExperimentConfig
35
+ cfg = load_config(config_path)
36
+
37
+ if 'pretrained_model_name_or_path' not in cfg.system.condition_model or cfg.system.condition_model.pretrained_model_name_or_path is None:
38
+ cfg.system.condition_model.config_path = config_path.replace("config.yaml", "clip_config.json")
39
+
40
+ system: BaseSystem = craftsman.find(cfg.system_type)(
41
+ cfg.system,
42
+ )
43
+
44
+ print(f"Restoring states from the checkpoint path at {ckpt_path} with config {cfg}")
45
+ system.load_state_dict(torch.load(ckpt_path, map_location=torch.device('cpu'))['state_dict'])
46
+ system = system.to(device).eval()
47
+
48
+ return system
49
+
50
+ class RMBG(object):
51
+ def __init__(self, device):
52
+ sam = sam_model_registry["vit_h"](checkpoint=f"{parent_dir}/ckpts/SAM/sam_vit_h_4b8939.pth").to(device)
53
+ self.predictor = SamPredictor(sam)
54
+
55
+ def rmbg_sam(self, input_image):
56
+ def _sam_segment(predictor, input_image, *bbox_coords):
57
+ bbox = np.array(bbox_coords)
58
+ image = np.asarray(input_image)
59
+
60
+ start_time = time.time()
61
+ predictor.set_image(image)
62
+
63
+ masks_bbox, scores_bbox, logits_bbox = predictor.predict(box=bbox, multimask_output=True)
64
+
65
+ print(f"SAM Time: {time.time() - start_time:.3f}s")
66
+ out_image = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)
67
+ out_image[:, :, :3] = image
68
+ out_image_bbox = out_image.copy()
69
+ out_image_bbox[:, :, 3] = masks_bbox[-1].astype(np.uint8) * 255
70
+ torch.cuda.empty_cache()
71
+ return Image.fromarray(out_image_bbox, mode='RGBA')
72
+
73
+ RES = 1024
74
+ input_image.thumbnail([RES, RES], Image.Resampling.LANCZOS)
75
+
76
+ image_rem = input_image.convert('RGBA')
77
+ image_nobg = remove(image_rem, alpha_matting=True)
78
+ arr = np.asarray(image_nobg)[:, :, -1]
79
+ x_nonzero = np.nonzero(arr.sum(axis=0))
80
+ y_nonzero = np.nonzero(arr.sum(axis=1))
81
+ x_min = int(x_nonzero[0].min())
82
+ y_min = int(y_nonzero[0].min())
83
+ x_max = int(x_nonzero[0].max())
84
+ y_max = int(y_nonzero[0].max())
85
+ return _sam_segment(self.predictor, input_image.convert('RGB'), x_min, y_min, x_max, y_max)
86
+
87
+ def rmbg_rembg(self, input_image):
88
+ def _rembg_remove(
89
+ image: PIL.Image.Image,
90
+ rembg_session = None,
91
+ force: bool = False,
92
+ **rembg_kwargs,
93
+ ) -> PIL.Image.Image:
94
+ do_remove = True
95
+ if image.mode == "RGBA" and image.getextrema()[3][0] < 255:
96
+ # explain why current do not rm bg
97
+ print("alhpa channl not enpty, skip remove background, using alpha channel as mask")
98
+ background = Image.new("RGBA", image.size, (0, 0, 0, 0))
99
+ image = Image.alpha_composite(background, image)
100
+ do_remove = False
101
+ do_remove = do_remove or force
102
+ if do_remove:
103
+ image = rembg.remove(image, session=rembg_session, **rembg_kwargs)
104
+ return image
105
+ return _rembg_remove(input_image, rembg_session, force_remove=True)
106
+
107
+ def run(self, rm_type, image, foreground_ratio, background_choice, backgroud_color):
108
+ # image = cv2.resize(np.array(image), (crop_size, crop_size))
109
+ # image = Image.fromarray(image)
110
+
111
+ if background_choice == "Alpha as mask":
112
+ background = Image.new("RGBA", image.size, (backgroud_color[0], backgroud_color[1], backgroud_color[2], 0))
113
+ return Image.alpha_composite(background, image)
114
+ elif "Remove" in background_choice:
115
+ if rm_type.upper() == "SAM":
116
+ image = self.rmbg_sam(image)
117
+ elif rm_type.upper() == "REMBG":
118
+ image = self.rmbg_rembg(image)
119
+ else:
120
+ return -1
121
+
122
+ image = do_resize_content(image, foreground_ratio)
123
+ image = expand_to_square(image)
124
+ image = add_background(image, backgroud_color)
125
+ return image.convert("RGB")
126
+
127
+ elif "Original" in background_choice:
128
+ return image
129
+ else:
130
+ return -1
131
+
132
+ def do_resize_content(original_image: Image, scale_rate):
133
+ # resize image content wile retain the original image size
134
+ if scale_rate != 1:
135
+ # Calculate the new size after rescaling
136
+ new_size = tuple(int(dim * scale_rate) for dim in original_image.size)
137
+ # Resize the image while maintaining the aspect ratio
138
+ resized_image = original_image.resize(new_size)
139
+ # Create a new image with the original size and black background
140
+ padded_image = Image.new("RGBA", original_image.size, (0, 0, 0, 0))
141
+ paste_position = ((original_image.width - resized_image.width) // 2, (original_image.height - resized_image.height) // 2)
142
+ padded_image.paste(resized_image, paste_position)
143
+ return padded_image
144
+ else:
145
+ return original_image
146
+
147
+ def expand2square(pil_img, background_color):
148
+ width, height = pil_img.size
149
+ if width == height:
150
+ return pil_img
151
+ elif width > height:
152
+ result = Image.new(pil_img.mode, (width, width), background_color)
153
+ result.paste(pil_img, (0, (width - height) // 2))
154
+ return result
155
+ else:
156
+ result = Image.new(pil_img.mode, (height, height), background_color)
157
+ result.paste(pil_img, ((height - width) // 2, 0))
158
+ return result
159
+
160
+ def expand_to_square(image, bg_color=(0, 0, 0, 0)):
161
+ # expand image to 1:1
162
+ width, height = image.size
163
+ if width == height:
164
+ return image
165
+ new_size = (max(width, height), max(width, height))
166
+ new_image = Image.new("RGBA", new_size, bg_color)
167
+ paste_position = ((new_size[0] - width) // 2, (new_size[1] - height) // 2)
168
+ new_image.paste(image, paste_position)
169
+ return new_image
170
+
171
+ def add_background(image, bg_color=(255, 255, 255)):
172
+ # given an RGBA image, alpha channel is used as mask to add background color
173
+ background = Image.new("RGBA", image.size, bg_color)
174
+ return Image.alpha_composite(background, image)