wyysf commited on
Commit
b146788
·
verified ·
1 Parent(s): 3734a92

Upload utils.py

Browse files
Files changed (1) hide show
  1. apps/utils.py +83 -134
apps/utils.py CHANGED
@@ -22,11 +22,13 @@ 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 load_model(
26
  ckpt_path: str,
27
  config_path: str,
28
- scheluder_name: str = None,
29
- scheluder_dict : dict = None,
30
  device = "cuda"
31
  ):
32
  cfg: ExperimentConfig
@@ -35,14 +37,6 @@ def load_model(
35
  if 'pretrained_model_name_or_path' not in cfg.system.condition_model or cfg.system.condition_model.pretrained_model_name_or_path is None:
36
  cfg.system.condition_model.config_path = config_path.replace("config.yaml", "clip_config.json")
37
 
38
- # cfg.system.denoise_scheduler= {
39
- # 'num_train_timesteps': 1000,
40
- # 'beta_start': 0.00085,
41
- # 'beta_end': 0.012,
42
- # 'beta_schedule': 'scaled_linear',
43
- # 'steps_offset': 1
44
- # }
45
-
46
  system: BaseSystem = craftsman.find(cfg.system_type)(
47
  cfg.system,
48
  )
@@ -53,93 +47,103 @@ def load_model(
53
 
54
  return system
55
 
56
- def rmbg_sam(iamge, foreground_ratio):
57
- return iamge
58
-
59
- def rmbg_rembg(iamge, foreground_ratio):
60
- return iamge
61
-
62
  class RMBG(object):
63
  def __init__(self, device):
64
- sam_checkpoint = f"{parent_dir}/ckpts/SAM/sam_vit_h_4b8939.pth"
65
- model_type = "vit_h"
66
- sam = sam_model_registry[model_type](checkpoint=sam_checkpoint).to(device)
67
  self.predictor = SamPredictor(sam)
68
 
69
- def rmbg_sam(self, input_image, crop_size, foreground_ratio, segment=True, rescale=True):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  RES = 1024
71
  input_image.thumbnail([RES, RES], Image.Resampling.LANCZOS)
72
 
73
- if segment:
74
- image_rem = input_image.convert('RGBA')
75
- image_nobg = remove(image_rem, alpha_matting=True)
76
- arr = np.asarray(image_nobg)[:, :, -1]
77
- x_nonzero = np.nonzero(arr.sum(axis=0))
78
- y_nonzero = np.nonzero(arr.sum(axis=1))
79
- x_min = int(x_nonzero[0].min())
80
- y_min = int(y_nonzero[0].min())
81
- x_max = int(x_nonzero[0].max())
82
- y_max = int(y_nonzero[0].max())
83
- input_image = sam_segment(self.predictor, input_image.convert('RGB'), x_min, y_min, x_max, y_max)
84
- # Rescale and recenter
85
- if rescale:
86
- image_arr = np.array(input_image)
87
- in_w, in_h = image_arr.shape[:2]
88
- out_res = min(RES, max(in_w, in_h))
89
- ret, mask = cv2.threshold(np.array(input_image.split()[-1]), 0, 255, cv2.THRESH_BINARY)
90
- x, y, w, h = cv2.boundingRect(mask)
91
- max_size = max(w, h)
92
- side_len = int(max_size / foreground_ratio)
93
- padded_image = np.zeros((side_len, side_len, 4), dtype=np.uint8)
94
- center = side_len // 2
95
- padded_image[center - h // 2 : center - h // 2 + h, center - w // 2 : center - w // 2 + w] = image_arr[y : y + h, x : x + w]
96
- rgba = Image.fromarray(padded_image).resize((out_res, out_res), Image.LANCZOS)
97
-
98
- rgba_arr = np.array(rgba) / 255.0
99
- rgb = rgba_arr[..., :3] * rgba_arr[..., -1:] + (1 - rgba_arr[..., -1:])
100
- input_image = Image.fromarray((rgb * 255).astype(np.uint8))
101
- else:
102
- input_image = expand2square(input_image, (127, 127, 127, 0))
103
- return input_image
104
-
105
 
106
- def rmbg_rembg(self, image, crop_size, foreground_ratio, background_choice, backgroud_color):
107
- print(background_choice)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  if background_choice == "Alpha as mask":
109
- background = Image.new("RGBA", image.size, (0, 0, 0, 0))
110
- image = Image.alpha_composite(background, image)
111
- else:
112
- image = remove_background(image, rembg_session, force_remove=True)
113
- image = do_resize_content(image, foreground_ratio)
114
- image = expand_to_square(image)
115
- image = add_background(image, backgroud_color)
116
- return image.convert("RGB")
117
-
118
- def run(self, rm_type, image, crop_size, foreground_ratio, background_choice, backgroud_color):
119
- if "Remove" in background_choice:
120
  if rm_type.upper() == "SAM":
121
- return self.rmbg_sam(image, crop_size, foreground_ratio, background_choice, backgroud_color)
122
  elif rm_type.upper() == "REMBG":
123
- return self.rmbg_rembg(image, crop_size, foreground_ratio, background_choice, backgroud_color)
124
  else:
125
  return -1
 
 
 
 
 
 
126
  elif "Original" in background_choice:
127
  return image
128
  else:
129
  return -1
130
 
131
-
132
- def save_image(tensor):
133
- ndarr = tensor.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy()
134
- # pdb.set_trace()
135
- im = Image.fromarray(ndarr)
136
- return ndarr
137
-
138
- def prepare_data(single_image, crop_size):
139
- from apps.third_party.Wonder3D.mvdiffusion.data.single_image_dataset import SingleImageDataset
140
- dataset = SingleImageDataset(root_dir='', num_views=6, img_wh=[256, 256], bg_color='white', crop_size=crop_size, single_image=single_image)
141
- return dataset[0]
142
-
 
 
 
143
  def expand2square(pil_img, background_color):
144
  width, height = pil_img.size
145
  if width == height:
@@ -153,24 +157,6 @@ def expand2square(pil_img, background_color):
153
  result.paste(pil_img, ((height - width) // 2, 0))
154
  return result
155
 
156
-
157
- def sam_segment(predictor, input_image, *bbox_coords):
158
- bbox = np.array(bbox_coords)
159
- image = np.asarray(input_image)
160
-
161
- start_time = time.time()
162
- predictor.set_image(image)
163
-
164
- masks_bbox, scores_bbox, logits_bbox = predictor.predict(box=bbox, multimask_output=True)
165
-
166
- print(f"SAM Time: {time.time() - start_time:.3f}s")
167
- out_image = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)
168
- out_image[:, :, :3] = image
169
- out_image_bbox = out_image.copy()
170
- out_image_bbox[:, :, 3] = masks_bbox[-1].astype(np.uint8) * 255
171
- torch.cuda.empty_cache()
172
- return Image.fromarray(out_image_bbox, mode='RGBA')
173
-
174
  def expand_to_square(image, bg_color=(0, 0, 0, 0)):
175
  # expand image to 1:1
176
  width, height = image.size
@@ -182,43 +168,6 @@ def expand_to_square(image, bg_color=(0, 0, 0, 0)):
182
  new_image.paste(image, paste_position)
183
  return new_image
184
 
185
- def check_input_image(input_image):
186
- if input_image is None:
187
- raise gr.Error("No image uploaded!")
188
-
189
- def remove_background(
190
- image: PIL.Image.Image,
191
- rembg_session = None,
192
- force: bool = False,
193
- **rembg_kwargs,
194
- ) -> PIL.Image.Image:
195
- do_remove = True
196
- if image.mode == "RGBA" and image.getextrema()[3][0] < 255:
197
- # explain why current do not rm bg
198
- print("alhpa channl not enpty, skip remove background, using alpha channel as mask")
199
- background = Image.new("RGBA", image.size, (0, 0, 0, 0))
200
- image = Image.alpha_composite(background, image)
201
- do_remove = False
202
- do_remove = do_remove or force
203
- if do_remove:
204
- image = rembg.remove(image, session=rembg_session, **rembg_kwargs)
205
- return image
206
-
207
- def do_resize_content(original_image: Image, scale_rate):
208
- # resize image content wile retain the original image size
209
- if scale_rate != 1:
210
- # Calculate the new size after rescaling
211
- new_size = tuple(int(dim * scale_rate) for dim in original_image.size)
212
- # Resize the image while maintaining the aspect ratio
213
- resized_image = original_image.resize(new_size)
214
- # Create a new image with the original size and black background
215
- padded_image = Image.new("RGBA", original_image.size, (0, 0, 0, 0))
216
- paste_position = ((original_image.width - resized_image.width) // 2, (original_image.height - resized_image.height) // 2)
217
- padded_image.paste(resized_image, paste_position)
218
- return padded_image
219
- else:
220
- return original_image
221
-
222
  def add_background(image, bg_color=(255, 255, 255)):
223
  # given an RGBA image, alpha channel is used as mask to add background color
224
  background = Image.new("RGBA", image.size, bg_color)
 
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
 
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
  )
 
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:
 
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
 
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)