liuyizhang commited on
Commit
4de87d2
1 Parent(s): 9546498

delete files

Browse files
automatic_label_demo.py DELETED
@@ -1,315 +0,0 @@
1
- import argparse
2
- import os
3
- import copy
4
-
5
- import numpy as np
6
- import json
7
- import torch
8
- import torchvision
9
- from PIL import Image, ImageDraw, ImageFont
10
-
11
- # Grounding DINO
12
- import GroundingDINO.groundingdino.datasets.transforms as T
13
- from GroundingDINO.groundingdino.models import build_model
14
- from GroundingDINO.groundingdino.util import box_ops
15
- from GroundingDINO.groundingdino.util.slconfig import SLConfig
16
- from GroundingDINO.groundingdino.util.utils import clean_state_dict, get_phrases_from_posmap
17
-
18
- # segment anything
19
- from segment_anything import build_sam, SamPredictor
20
- import cv2
21
- import numpy as np
22
- import matplotlib.pyplot as plt
23
-
24
- # BLIP
25
- from transformers import BlipProcessor, BlipForConditionalGeneration
26
-
27
- # ChatGPT
28
- import openai
29
-
30
-
31
- def load_image(image_path):
32
- # load image
33
- image_pil = Image.open(image_path).convert("RGB") # load image
34
-
35
- transform = T.Compose(
36
- [
37
- T.RandomResize([800], max_size=1333),
38
- T.ToTensor(),
39
- T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
40
- ]
41
- )
42
- image, _ = transform(image_pil, None) # 3, h, w
43
- return image_pil, image
44
-
45
-
46
- def generate_caption(raw_image, device):
47
- # unconditional image captioning
48
- if device == "cuda":
49
- inputs = processor(raw_image, return_tensors="pt").to("cuda", torch.float16)
50
- else:
51
- inputs = processor(raw_image, return_tensors="pt")
52
- out = blip_model.generate(**inputs)
53
- caption = processor.decode(out[0], skip_special_tokens=True)
54
- return caption
55
-
56
-
57
- def generate_tags(caption, split=',', max_tokens=100, model="gpt-3.5-turbo"):
58
- prompt = [
59
- {
60
- 'role': 'system',
61
- 'content': 'Extract the unique nouns in the caption. Remove all the adjectives. ' + \
62
- f'List the nouns in singular form. Split them by "{split} ". ' + \
63
- f'Caption: {caption}.'
64
- }
65
- ]
66
- response = openai.ChatCompletion.create(model=model, messages=prompt, temperature=0.6, max_tokens=max_tokens)
67
- reply = response['choices'][0]['message']['content']
68
- # sometimes return with "noun: xxx, xxx, xxx"
69
- tags = reply.split(':')[-1].strip()
70
- return tags
71
-
72
-
73
- def check_caption(caption, pred_phrases, max_tokens=100, model="gpt-3.5-turbo"):
74
- object_list = [obj.split('(')[0] for obj in pred_phrases]
75
- object_num = []
76
- for obj in set(object_list):
77
- object_num.append(f'{object_list.count(obj)} {obj}')
78
- object_num = ', '.join(object_num)
79
- print(f"Correct object number: {object_num}")
80
-
81
- prompt = [
82
- {
83
- 'role': 'system',
84
- 'content': 'Revise the number in the caption if it is wrong. ' + \
85
- f'Caption: {caption}. ' + \
86
- f'True object number: {object_num}. ' + \
87
- 'Only give the revised caption: '
88
- }
89
- ]
90
- response = openai.ChatCompletion.create(model=model, messages=prompt, temperature=0.6, max_tokens=max_tokens)
91
- reply = response['choices'][0]['message']['content']
92
- # sometimes return with "Caption: xxx, xxx, xxx"
93
- caption = reply.split(':')[-1].strip()
94
- return caption
95
-
96
-
97
- def load_model(model_config_path, model_checkpoint_path, device):
98
- args = SLConfig.fromfile(model_config_path)
99
- args.device = device
100
- model = build_model(args)
101
- checkpoint = torch.load(model_checkpoint_path, map_location="cpu")
102
- load_res = model.load_state_dict(clean_state_dict(checkpoint["model"]), strict=False)
103
- print(load_res)
104
- _ = model.eval()
105
- return model
106
-
107
-
108
- def get_grounding_output(model, image, caption, box_threshold, text_threshold,device="cpu"):
109
- caption = caption.lower()
110
- caption = caption.strip()
111
- if not caption.endswith("."):
112
- caption = caption + "."
113
- model = model.to(device)
114
- image = image.to(device)
115
- with torch.no_grad():
116
- outputs = model(image[None], captions=[caption])
117
- logits = outputs["pred_logits"].cpu().sigmoid()[0] # (nq, 256)
118
- boxes = outputs["pred_boxes"].cpu()[0] # (nq, 4)
119
- logits.shape[0]
120
-
121
- # filter output
122
- logits_filt = logits.clone()
123
- boxes_filt = boxes.clone()
124
- filt_mask = logits_filt.max(dim=1)[0] > box_threshold
125
- logits_filt = logits_filt[filt_mask] # num_filt, 256
126
- boxes_filt = boxes_filt[filt_mask] # num_filt, 4
127
- logits_filt.shape[0]
128
-
129
- # get phrase
130
- tokenlizer = model.tokenizer
131
- tokenized = tokenlizer(caption)
132
- # build pred
133
- pred_phrases = []
134
- scores = []
135
- for logit, box in zip(logits_filt, boxes_filt):
136
- pred_phrase = get_phrases_from_posmap(logit > text_threshold, tokenized, tokenlizer)
137
- pred_phrases.append(pred_phrase + f"({str(logit.max().item())[:4]})")
138
- scores.append(logit.max().item())
139
-
140
- return boxes_filt, torch.Tensor(scores), pred_phrases
141
-
142
-
143
- def show_mask(mask, ax, random_color=False):
144
- if random_color:
145
- color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
146
- else:
147
- color = np.array([30/255, 144/255, 255/255, 0.6])
148
- h, w = mask.shape[-2:]
149
- mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
150
- ax.imshow(mask_image)
151
-
152
-
153
- def show_box(box, ax, label):
154
- x0, y0 = box[0], box[1]
155
- w, h = box[2] - box[0], box[3] - box[1]
156
- ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2))
157
- ax.text(x0, y0, label)
158
-
159
-
160
- def save_mask_data(output_dir, caption, mask_list, box_list, label_list):
161
- value = 0 # 0 for background
162
-
163
- mask_img = torch.zeros(mask_list.shape[-2:])
164
- for idx, mask in enumerate(mask_list):
165
- mask_img[mask.cpu().numpy()[0] == True] = value + idx + 1
166
- plt.figure(figsize=(10, 10))
167
- plt.imshow(mask_img.numpy())
168
- plt.axis('off')
169
- plt.savefig(os.path.join(output_dir, 'mask.jpg'), bbox_inches="tight", dpi=300, pad_inches=0.0)
170
-
171
- json_data = {
172
- 'caption': caption,
173
- 'mask':[{
174
- 'value': value,
175
- 'label': 'background'
176
- }]
177
- }
178
- for label, box in zip(label_list, box_list):
179
- value += 1
180
- name, logit = label.split('(')
181
- logit = logit[:-1] # the last is ')'
182
- json_data['mask'].append({
183
- 'value': value,
184
- 'label': name,
185
- 'logit': float(logit),
186
- 'box': box.numpy().tolist(),
187
- })
188
- with open(os.path.join(output_dir, 'label.json'), 'w') as f:
189
- json.dump(json_data, f)
190
-
191
-
192
- if __name__ == "__main__":
193
-
194
- parser = argparse.ArgumentParser("Grounded-Segment-Anything Demo", add_help=True)
195
- parser.add_argument("--config", type=str, required=True, help="path to config file")
196
- parser.add_argument(
197
- "--grounded_checkpoint", type=str, required=True, help="path to checkpoint file"
198
- )
199
- parser.add_argument(
200
- "--sam_checkpoint", type=str, required=True, help="path to checkpoint file"
201
- )
202
- parser.add_argument("--input_image", type=str, required=True, help="path to image file")
203
- parser.add_argument("--split", default=",", type=str, help="split for text prompt")
204
- parser.add_argument("--openai_key", type=str, required=True, help="key for chatgpt")
205
- parser.add_argument("--openai_proxy", default=None, type=str, help="proxy for chatgpt")
206
- parser.add_argument(
207
- "--output_dir", "-o", type=str, default="outputs", required=True, help="output directory"
208
- )
209
-
210
- parser.add_argument("--box_threshold", type=float, default=0.25, help="box threshold")
211
- parser.add_argument("--text_threshold", type=float, default=0.2, help="text threshold")
212
- parser.add_argument("--iou_threshold", type=float, default=0.5, help="iou threshold")
213
-
214
- parser.add_argument("--device", type=str, default="cpu", help="running on cpu only!, default=False")
215
- args = parser.parse_args()
216
-
217
- # cfg
218
- config_file = args.config # change the path of the model config file
219
- grounded_checkpoint = args.grounded_checkpoint # change the path of the model
220
- sam_checkpoint = args.sam_checkpoint
221
- image_path = args.input_image
222
- split = args.split
223
- openai_key = args.openai_key
224
- openai_proxy = args.openai_proxy
225
- output_dir = args.output_dir
226
- box_threshold = args.box_threshold
227
- text_threshold = args.text_threshold
228
- iou_threshold = args.iou_threshold
229
- device = args.device
230
-
231
- openai.api_key = openai_key
232
- if openai_proxy:
233
- openai.proxy = {"http": openai_proxy, "https": openai_proxy}
234
-
235
- # make dir
236
- os.makedirs(output_dir, exist_ok=True)
237
- # load image
238
- image_pil, image = load_image(image_path)
239
- # load model
240
- model = load_model(config_file, grounded_checkpoint, device=device)
241
-
242
- # visualize raw image
243
- image_pil.save(os.path.join(output_dir, "raw_image.jpg"))
244
-
245
- # generate caption and tags
246
- # use Tag2Text can generate better captions
247
- # https://huggingface.co/spaces/xinyu1205/Tag2Text
248
- # but there are some bugs...
249
- processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
250
- if device == "cuda":
251
- blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-large", torch_dtype=torch.float16).to("cuda")
252
- else:
253
- blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-large")
254
- caption = generate_caption(image_pil, device=device)
255
- # Currently ", " is better for detecting single tags
256
- # while ". " is a little worse in some case
257
- text_prompt = generate_tags(caption, split=split)
258
- print(f"Caption: {caption}")
259
- print(f"Tags: {text_prompt}")
260
-
261
- # run grounding dino model
262
- boxes_filt, scores, pred_phrases = get_grounding_output(
263
- model, image, text_prompt, box_threshold, text_threshold, device=device
264
- )
265
-
266
- # initialize SAM
267
- sam = build_sam(checkpoint=sam_checkpoint)
268
- sam.to(device=device)
269
- predictor = SamPredictor(sam)
270
- image = cv2.imread(image_path)
271
- image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
272
- predictor.set_image(image)
273
-
274
- size = image_pil.size
275
- H, W = size[1], size[0]
276
- for i in range(boxes_filt.size(0)):
277
- boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])
278
- boxes_filt[i][:2] -= boxes_filt[i][2:] / 2
279
- boxes_filt[i][2:] += boxes_filt[i][:2]
280
-
281
- boxes_filt = boxes_filt.cpu()
282
- # use NMS to handle overlapped boxes
283
- print(f"Before NMS: {boxes_filt.shape[0]} boxes")
284
- nms_idx = torchvision.ops.nms(boxes_filt, scores, iou_threshold).numpy().tolist()
285
- boxes_filt = boxes_filt[nms_idx]
286
- pred_phrases = [pred_phrases[idx] for idx in nms_idx]
287
- print(f"After NMS: {boxes_filt.shape[0]} boxes")
288
- caption = check_caption(caption, pred_phrases)
289
- print(f"Revise caption with number: {caption}")
290
-
291
- transformed_boxes = predictor.transform.apply_boxes_torch(boxes_filt, image.shape[:2]).to(device)
292
-
293
- masks, _, _ = predictor.predict_torch(
294
- point_coords = None,
295
- point_labels = None,
296
- boxes = transformed_boxes,
297
- multimask_output = False,
298
- )
299
-
300
- # draw output image
301
- plt.figure(figsize=(10, 10))
302
- plt.imshow(image)
303
- for mask in masks:
304
- show_mask(mask.cpu().numpy(), plt.gca(), random_color=True)
305
- for box, label in zip(boxes_filt, pred_phrases):
306
- show_box(box.numpy(), plt.gca(), label)
307
-
308
- plt.title(caption)
309
- plt.axis('off')
310
- plt.savefig(
311
- os.path.join(output_dir, "automatic_label_output.jpg"),
312
- bbox_inches="tight", dpi=300, pad_inches=0.0
313
- )
314
-
315
- save_mask_data(output_dir, caption, masks, boxes_filt, pred_phrases)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
grounded_sam.ipynb DELETED
The diff for this file is too large to render. See raw diff
 
grounding_dino_demo.py DELETED
@@ -1,171 +0,0 @@
1
- import argparse
2
- import os
3
-
4
- import numpy as np
5
- import torch
6
- from PIL import Image, ImageDraw, ImageFont
7
-
8
- import GroundingDINO.groundingdino.datasets.transforms as T
9
- from GroundingDINO.groundingdino.models import build_model
10
- from GroundingDINO.groundingdino.util import box_ops
11
- from GroundingDINO.groundingdino.util.slconfig import SLConfig
12
- from GroundingDINO.groundingdino.util.utils import clean_state_dict, get_phrases_from_posmap
13
-
14
-
15
- def plot_boxes_to_image(image_pil, tgt):
16
- H, W = tgt["size"]
17
- boxes = tgt["boxes"]
18
- labels = tgt["labels"]
19
- assert len(boxes) == len(labels), "boxes and labels must have same length"
20
-
21
- draw = ImageDraw.Draw(image_pil)
22
- mask = Image.new("L", image_pil.size, 0)
23
- mask_draw = ImageDraw.Draw(mask)
24
-
25
- # draw boxes and masks
26
- for box, label in zip(boxes, labels):
27
- # from 0..1 to 0..W, 0..H
28
- box = box * torch.Tensor([W, H, W, H])
29
- # from xywh to xyxy
30
- box[:2] -= box[2:] / 2
31
- box[2:] += box[:2]
32
- # random color
33
- color = tuple(np.random.randint(0, 255, size=3).tolist())
34
- # draw
35
- x0, y0, x1, y1 = box
36
- x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)
37
-
38
- draw.rectangle([x0, y0, x1, y1], outline=color, width=6)
39
- # draw.text((x0, y0), str(label), fill=color)
40
-
41
- font = ImageFont.load_default()
42
- if hasattr(font, "getbbox"):
43
- bbox = draw.textbbox((x0, y0), str(label), font)
44
- else:
45
- w, h = draw.textsize(str(label), font)
46
- bbox = (x0, y0, w + x0, y0 + h)
47
- # bbox = draw.textbbox((x0, y0), str(label))
48
- draw.rectangle(bbox, fill=color)
49
- draw.text((x0, y0), str(label), fill="white")
50
-
51
- mask_draw.rectangle([x0, y0, x1, y1], fill=255, width=6)
52
-
53
- return image_pil, mask
54
-
55
-
56
- def load_image(image_path):
57
- # load image
58
- image_pil = Image.open(image_path).convert("RGB") # load image
59
-
60
- transform = T.Compose(
61
- [
62
- T.RandomResize([800], max_size=1333),
63
- T.ToTensor(),
64
- T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
65
- ]
66
- )
67
- image, _ = transform(image_pil, None) # 3, h, w
68
- return image_pil, image
69
-
70
-
71
- def load_model(model_config_path, model_checkpoint_path, device="cpu"):
72
- args = SLConfig.fromfile(model_config_path)
73
- args.device = device
74
- model = build_model(args)
75
- checkpoint = torch.load(model_checkpoint_path, map_location="cpu")
76
- load_res = model.load_state_dict(clean_state_dict(checkpoint["model"]), strict=False)
77
- print(load_res)
78
- _ = model.eval()
79
- return model
80
-
81
-
82
- def get_grounding_output(model, image, caption, box_threshold, text_threshold, with_logits=True, device="cpu"):
83
- caption = caption.lower()
84
- caption = caption.strip()
85
- if not caption.endswith("."):
86
- caption = caption + "."
87
- model = model.to(device)
88
- image = image.to(device)
89
- with torch.no_grad():
90
- outputs = model(image[None], captions=[caption])
91
- logits = outputs["pred_logits"].cpu().sigmoid()[0] # (nq, 256)
92
- boxes = outputs["pred_boxes"].cpu()[0] # (nq, 4)
93
- logits.shape[0]
94
-
95
- # filter output
96
- logits_filt = logits.clone()
97
- boxes_filt = boxes.clone()
98
- filt_mask = logits_filt.max(dim=1)[0] > box_threshold
99
- logits_filt = logits_filt[filt_mask] # num_filt, 256
100
- boxes_filt = boxes_filt[filt_mask] # num_filt, 4
101
- logits_filt.shape[0]
102
-
103
- # get phrase
104
- tokenlizer = model.tokenizer
105
- tokenized = tokenlizer(caption)
106
- # build pred
107
- pred_phrases = []
108
- for logit, box in zip(logits_filt, boxes_filt):
109
- pred_phrase = get_phrases_from_posmap(logit > text_threshold, tokenized, tokenlizer)
110
- if with_logits:
111
- pred_phrases.append(pred_phrase + f"({str(logit.max().item())[:4]})")
112
- else:
113
- pred_phrases.append(pred_phrase)
114
-
115
- return boxes_filt, pred_phrases
116
-
117
-
118
- if __name__ == "__main__":
119
-
120
- parser = argparse.ArgumentParser("Grounding DINO example", add_help=True)
121
- parser.add_argument("--config", type=str, required=True, help="path to config file")
122
- parser.add_argument(
123
- "--grounded_checkpoint", type=str, required=True, help="path to checkpoint file"
124
- )
125
- parser.add_argument("--input_image", type=str, required=True, help="path to image file")
126
- parser.add_argument("--text_prompt", type=str, required=True, help="text prompt")
127
- parser.add_argument(
128
- "--output_dir", "-o", type=str, default="outputs", required=True, help="output directory"
129
- )
130
-
131
- parser.add_argument("--box_threshold", type=float, default=0.3, help="box threshold")
132
- parser.add_argument("--text_threshold", type=float, default=0.25, help="text threshold")
133
-
134
- parser.add_argument("--device", type=str, default="cpu", help="running on cpu only!, default=False")
135
- args = parser.parse_args()
136
-
137
- # cfg
138
- config_file = args.config # change the path of the model config file
139
- grounded_checkpoint = args.grounded_checkpoint # change the path of the model
140
- image_path = args.input_image
141
- text_prompt = args.text_prompt
142
- output_dir = args.output_dir
143
- box_threshold = args.box_threshold
144
- text_threshold = args.box_threshold
145
- device = args.device
146
-
147
- # make dir
148
- os.makedirs(output_dir, exist_ok=True)
149
- # load image
150
- image_pil, image = load_image(image_path)
151
- # load model
152
- model = load_model(config_file, grounded_checkpoint, device=device)
153
-
154
- # visualize raw image
155
- # image_pil.save(os.path.join(output_dir, "raw_image.jpg"))
156
-
157
- # run model
158
- boxes_filt, pred_phrases = get_grounding_output(
159
- model, image, text_prompt, box_threshold, text_threshold, device=device
160
- )
161
-
162
- # visualize pred
163
- size = image_pil.size
164
- pred_dict = {
165
- "boxes": boxes_filt,
166
- "size": [size[1], size[0]], # H,W
167
- "labels": pred_phrases,
168
- }
169
- # import ipdb; ipdb.set_trace()
170
- image_with_box = plot_boxes_to_image(image_pil, pred_dict)[0]
171
- image_with_box.save(os.path.join(output_dir, "grounding_dino_output.jpg"))