forked from 2toinf/IVM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIVM.py
186 lines (164 loc) · 7.67 KB
/
IVM.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import cv2
from model.IVM import IVM
import torchvision.transforms.functional as TF
import torch
from PIL import Image
import numpy as np
from torch.nn import functional as F
import os
import gdown
import accelerate
import torch.nn as nn
from typing import Type, Tuple
def _download(url: str, name: str,root: str):
os.makedirs(root, exist_ok=True)
download_target = os.path.join(root, name)
if os.path.exists(download_target) and not os.path.isfile(download_target):
raise RuntimeError(f"{download_target} exists and is not a regular file")
if os.path.isfile(download_target):
return download_target
gdown.download(url, download_target, quiet=False)
return download_target
def load(ckpt_path, low_gpu_memory = False):
url = "https://drive.google.com/uc?export=download&id=1OyVci6rAwnb2sJPxhObgK7AvlLYDLLHw"
model_path = _download(url, "sam_vit_h_4b8939.pth", os.path.expanduser(f"~/.cache/IVM/Sam"))
model = DeployModel_IVM(
ckpt_path = ckpt_path,
sam_ckpt=model_path,
offload_languageencoder=low_gpu_memory
)
return model
class DeployModel_IVM(nn.Module):
def __init__(self,
ckpt_path,
sam_ckpt,
offload_languageencoder = True
):
super().__init__()
self.model = IVM(
sam_model=sam_ckpt
)
ckpt = torch.load(ckpt_path, map_location="cpu")
print(ckpt.keys())
print(self.model.load_state_dict(ckpt, strict=False))
self.model = self.model.half()
if offload_languageencoder:
self.model.prompt_encoder = accelerate.cpu_offload(self.model.prompt_encoder , 'cuda')
else:
self.model.prompt_encoder = self.model.prompt_encoder.cuda()
self.model.image_encoder = self.model.image_encoder.cuda()
self.model.pixel_mean = self.model.pixel_mean.cuda()
self.model.pixel_std = self.model.pixel_std.cuda()
self.model.mask_decoder = self.model.mask_decoder.cuda()
@torch.no_grad()
def forward_batch(
self,
image, # list of PIL.Image
instruction, # list of instruction
blur_kernel_size = 201,
range_threshold = 0.5,
boxes_threshold = 0.5,
dilate_kernel_rate = 0.05,
min_reserved_ratio = 0.2,
fill_color=(255, 255, 255)
):
ori_sizes = [img.size for img in image]
ori_images = [np.asarray(img).astype(np.float32) for img in image]
masks = self.model.generate_batch([img.resize((1024, 1024)) for img in image], instruction)
soft = []
blur_image = []
highlight_image = []
cropped_blur_img = []
cropped_highlight_img = []
rgba = []
for mask, ori_image, ori_size in zip(masks, ori_images, ori_sizes):
mask = torch.sigmoid(F.interpolate(
mask.unsqueeze(0),
(ori_size[1], ori_size[0]),
mode="bilinear",
align_corners=False,
)[0, 0, :, :]).detach().cpu().numpy().astype(np.float32)[:,:,np.newaxis]
dilate_kernel_size = int(ori_size[0] * dilate_kernel_rate) * 2 + 1
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(dilate_kernel_size,dilate_kernel_size)) #ksize=7x7,
mask = cv2.dilate(mask,kernel,iterations=1).astype(np.float32)
mask = cv2.GaussianBlur(mask, (dilate_kernel_size, dilate_kernel_size), 0)[:,:,np.newaxis]
if mask.max() - mask.min() > range_threshold:
mask = (mask - mask.min()) / (mask.max() - mask.min()) * (1 - min_reserved_ratio)
else:
mask = np.ones_like(mask) * (1 - min_reserved_ratio)
if len(ori_image.shape) < 3:
ori_image = ori_image[:,:,np.newaxis].repeat(3,-1)
soft.append(mask)
rgba.append(np.concatenate((ori_image, mask * 255), axis=-1))
blur_image.append(mask * ori_image + (1-mask) * cv2.GaussianBlur(ori_image, (blur_kernel_size, blur_kernel_size), 0))
highlight_image.append(ori_image * (mask + min_reserved_ratio) + torch.tensor(fill_color, dtype=torch.uint8).repeat(ori_size[1], ori_size[0], 1).numpy() * (1 - min_reserved_ratio - mask))
try:
y_indices, x_indices = np.where(mask[:,:,0] > boxes_threshold)
x_min, x_max = x_indices.min(), x_indices.max()
y_min, y_max = y_indices.min(), y_indices.max()
cropped_blur_img.append(blur_image[-1][y_min:y_max+1, x_min:x_max+1])
cropped_highlight_img.append(highlight_image[-1][y_min:y_max+1, x_min:x_max+1])
except:
cropped_blur_img.append(blur_image[-1])
cropped_highlight_img.append(highlight_image[-1])
return {
'soft': soft,
'bbox': (x_min, y_min, x_max, y_max),
'blur_image': blur_image,
'highlight_image': highlight_image,
'cropped_blur_img': cropped_blur_img,
'cropped_highlight_img': cropped_highlight_img,
'rgba_image': rgba
}
@torch.no_grad()
def forward(
self,
image: Image,
instruction: str,
blur_kernel_size = 401,
boxes_threshold = 0.5,
range_threshold = 0.5,
dilate_kernel_rate = 0.05,
min_reserved_ratio = 0.1,
fill_color=(255, 255, 255)):
ori_size = image.size
ori_image = np.asarray(image).astype(np.float32)
mask = self.model.generate([image.resize((1024, 1024))], [instruction])
mask = torch.sigmoid(F.interpolate(
mask.unsqueeze(0),
(ori_size[1], ori_size[0]),
mode="bilinear",
align_corners=False,
)[0, 0, :, :]).detach().cpu().numpy().astype(np.float32)[:,:,np.newaxis]
dilate_kernel_size = int(ori_size[0] * dilate_kernel_rate) * 2 + 1
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(dilate_kernel_size,dilate_kernel_size)) #ksize=7x7,
mask = cv2.dilate(mask,kernel,iterations=1).astype(np.float32)
mask = cv2.GaussianBlur(mask, (dilate_kernel_size, dilate_kernel_size), 0)[:,:,np.newaxis]
if mask.max() - mask.min() > range_threshold:
mask = (mask - mask.min()) / (mask.max() - mask.min()) * (1 - min_reserved_ratio)
else:
mask = np.ones_like(mask) * (1 - min_reserved_ratio)
if len(ori_image.shape) < 3:
ori_image = ori_image[:,:,np.newaxis].repeat(3,-1)
soft = mask
rgba = np.concatenate((ori_image, mask * 255), axis=-1)
blur_image = mask * ori_image + (1-mask) * cv2.GaussianBlur(ori_image, (blur_kernel_size, blur_kernel_size), 0)
highlight_image = ori_image * (mask + min_reserved_ratio) + torch.tensor(fill_color, dtype=torch.uint8).repeat(ori_size[1], ori_size[0], 1).numpy() * (1 - min_reserved_ratio - mask)
try:
y_indices, x_indices = np.where(mask[:,:,0] > boxes_threshold)
x_min, x_max = x_indices.min(), x_indices.max()
y_min, y_max = y_indices.min(), y_indices.max()
cropped_blur_img = blur_image[-1][y_min:y_max+1, x_min:x_max+1]
cropped_highlight_img = highlight_image[-1][y_min:y_max+1, x_min:x_max+1]
except:
cropped_blur_img = blur_image[-1]
cropped_highlight_img = highlight_image[-1]
return {
'soft': soft,
'bbox': (x_min, y_min, x_max, y_max),
'blur_image': blur_image,
'highlight_image': highlight_image,
'cropped_blur_img': cropped_blur_img,
'cropped_highlight_img': cropped_highlight_img,
'rgba_image': rgba
}