Spaces:
Sleeping
Sleeping
Upload 37 files
Browse files- .gitattributes +2 -0
- assets/framework.jpg +0 -0
- assets/image.jpg +0 -0
- assets/results.jpg +0 -0
- configs/Base-RegionSpot.yaml +36 -0
- configs/eval.yaml +21 -0
- configs/objects365_bb.yaml +18 -0
- configs/objects365_bl.yaml +18 -0
- configs/objects365_bl_336.yaml +19 -0
- configs/objects365_v3det_openimages_bb.yaml +19 -0
- configs/objects365_v3det_openimages_bl.yaml +19 -0
- configs/objects365_v3det_openimages_bl_336.yaml +20 -0
- demo.py +67 -0
- flagged/input_img/0fce6cef302bd30bbf85/000000052891.jpg +0 -0
- flagged/log.csv +2 -0
- flagged/output/440681fbd96cfcf67ac5/image.png +0 -0
- images/000000030494.jpg +0 -0
- images/000000052891.jpg +0 -0
- images/20231108222434.jpg +0 -0
- images/20231108222549.jpg +0 -0
- images/20231108223144.jpg +0 -0
- images/dog.jpg +0 -0
- images/fish.jpeg +0 -0
- images/groceries.jpg +0 -0
- images/images/truck.jpg +0 -0
- images/pic1.jpg +0 -0
- images/pic2.png +3 -0
- images/pic3.png +3 -0
- images/pic4.png +0 -0
- images/pic5.png +0 -0
- images/truck.jpg +0 -0
- images/truck2.png +0 -0
- tools/re_save_ckpt.py +22 -0
- train_net.py +297 -0
- utils/__pycache__/tools.cpython-38.pyc +0 -0
- utils/__pycache__/tools_gradio.cpython-38.pyc +0 -0
- utils/tools.py +442 -0
- utils/tools_gradio.py +203 -0
.gitattributes
CHANGED
@@ -34,3 +34,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
regionspot/data/__pycache__/v3det_categories.cpython-38.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
regionspot/data/__pycache__/v3det_categories.cpython-38.pyc filter=lfs diff=lfs merge=lfs -text
|
37 |
+
images/pic2.png filter=lfs diff=lfs merge=lfs -text
|
38 |
+
images/pic3.png filter=lfs diff=lfs merge=lfs -text
|
assets/framework.jpg
ADDED
assets/image.jpg
ADDED
assets/results.jpg
ADDED
configs/Base-RegionSpot.yaml
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MODEL:
|
2 |
+
META_ARCHITECTURE: "RegionSpot"
|
3 |
+
PIXEL_MEAN: [123.675, 116.280, 103.530]
|
4 |
+
PIXEL_STD: [58.395, 57.120, 57.375]
|
5 |
+
|
6 |
+
SOLVER:
|
7 |
+
IMS_PER_BATCH: 16
|
8 |
+
BASE_LR: 0.000025
|
9 |
+
CHECKPOINT_PERIOD: 50000
|
10 |
+
STEPS: (210000, 250000)
|
11 |
+
MAX_ITER: 270000
|
12 |
+
WARMUP_FACTOR: 0.01
|
13 |
+
WARMUP_ITERS: 1000
|
14 |
+
WEIGHT_DECAY: 0.0001
|
15 |
+
OPTIMIZER: "ADAMW"
|
16 |
+
BACKBONE_MULTIPLIER: 1.0 # keep same with BASE_LR.
|
17 |
+
CLIP_GRADIENTS:
|
18 |
+
ENABLED: True
|
19 |
+
CLIP_TYPE: "full_model"
|
20 |
+
CLIP_VALUE: 1.0
|
21 |
+
NORM_TYPE: 2.0
|
22 |
+
SEED: 40244023
|
23 |
+
INPUT:
|
24 |
+
MIN_SIZE_TRAIN: (480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800)
|
25 |
+
CROP:
|
26 |
+
ENABLED: False
|
27 |
+
TYPE: "absolute_range"
|
28 |
+
SIZE: (384, 600)
|
29 |
+
FORMAT: "RGB"
|
30 |
+
TEST:
|
31 |
+
EVAL_PERIOD: 733000000
|
32 |
+
DATALOADER:
|
33 |
+
FILTER_EMPTY_ANNOTATIONS: False
|
34 |
+
NUM_WORKERS: 4
|
35 |
+
VERSION: 2
|
36 |
+
|
configs/eval.yaml
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
_BASE_: "Base-RegionSpot.yaml"
|
2 |
+
MODEL:
|
3 |
+
CLIP_TYPE: CLIP_400M_Large
|
4 |
+
TRAINING: False
|
5 |
+
BOX_TYPE: 'PRED_BOX'
|
6 |
+
MASK_ON: True
|
7 |
+
DATASETS: # LVIS
|
8 |
+
TRAIN: ("lvis_v1_train",)
|
9 |
+
TEST: ("lvis_v1_val",)
|
10 |
+
DATALOADER:
|
11 |
+
SAMPLER_TRAIN: "RepeatFactorTrainingSampler"
|
12 |
+
REPEAT_THRESHOLD: 0.001
|
13 |
+
INPUT:
|
14 |
+
CROP:
|
15 |
+
ENABLED: True
|
16 |
+
FORMAT: "RGB"
|
17 |
+
TEST: # LVIS
|
18 |
+
EVAL_PERIOD: 0 # disable eval during train since long time
|
19 |
+
|
20 |
+
OUTPUT_DIR: './output/eval'
|
21 |
+
|
configs/objects365_bb.yaml
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
_BASE_: "Base-RegionSpot.yaml"
|
2 |
+
MODEL:
|
3 |
+
CLIP_TYPE: CLIP_400M
|
4 |
+
DATALOADER:
|
5 |
+
SAMPLER_TRAIN: "MultiDatasetSampler"
|
6 |
+
DATASETS:
|
7 |
+
TRAIN: ("objects365_train",)
|
8 |
+
TEST: ()
|
9 |
+
TEST:
|
10 |
+
EVAL_PERIOD: 0
|
11 |
+
SOLVER:
|
12 |
+
STEPS: (350000, 420000)
|
13 |
+
MAX_ITER: 450000
|
14 |
+
INPUT:
|
15 |
+
CROP:
|
16 |
+
ENABLED: True
|
17 |
+
FORMAT: "RGB"
|
18 |
+
OUTPUT_DIR: './output/regionspot_obj365_bb'
|
configs/objects365_bl.yaml
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
_BASE_: "Base-RegionSpot.yaml"
|
2 |
+
MODEL:
|
3 |
+
CLIP_TYPE: CLIP_400M_Large
|
4 |
+
DATALOADER:
|
5 |
+
SAMPLER_TRAIN: "MultiDatasetSampler"
|
6 |
+
DATASETS:
|
7 |
+
TRAIN: ("objects365_train",)
|
8 |
+
TEST: ()
|
9 |
+
TEST:
|
10 |
+
EVAL_PERIOD: 0
|
11 |
+
SOLVER:
|
12 |
+
STEPS: (350000, 420000)
|
13 |
+
MAX_ITER: 450000
|
14 |
+
INPUT:
|
15 |
+
CROP:
|
16 |
+
ENABLED: True
|
17 |
+
FORMAT: "RGB"
|
18 |
+
OUTPUT_DIR: './output/regionspot_obj365_bl'
|
configs/objects365_bl_336.yaml
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
_BASE_: "Base-RegionSpot.yaml"
|
2 |
+
MODEL:
|
3 |
+
CLIP_TYPE: CLIP_400M_Large_336
|
4 |
+
CLIP_INPUT_SIZE: 336
|
5 |
+
DATALOADER:
|
6 |
+
SAMPLER_TRAIN: "MultiDatasetSampler"
|
7 |
+
DATASETS:
|
8 |
+
TRAIN: ("objects365_train",)
|
9 |
+
TEST: ()
|
10 |
+
TEST:
|
11 |
+
EVAL_PERIOD: 0
|
12 |
+
SOLVER:
|
13 |
+
STEPS: (350000, 420000)
|
14 |
+
MAX_ITER: 450000
|
15 |
+
INPUT:
|
16 |
+
CROP:
|
17 |
+
ENABLED: True
|
18 |
+
FORMAT: "RGB"
|
19 |
+
OUTPUT_DIR: './output/regionspot_obj365_bl_336'
|
configs/objects365_v3det_openimages_bb.yaml
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
_BASE_: "Base-RegionSpot.yaml"
|
2 |
+
MODEL:
|
3 |
+
WEIGHTS: "./output/regionspot_obj365_bb/model_final.pth"
|
4 |
+
CLIP_TYPE: CLIP_400M
|
5 |
+
DATALOADER:
|
6 |
+
SAMPLER_TRAIN: "MultiDatasetSampler"
|
7 |
+
DATASETS:
|
8 |
+
TRAIN: ("objects365_train", "v3det_train","openimages_train",)
|
9 |
+
TEST: ()
|
10 |
+
TEST:
|
11 |
+
EVAL_PERIOD: 0
|
12 |
+
SOLVER:
|
13 |
+
STEPS: (350000, 420000)
|
14 |
+
MAX_ITER: 450000
|
15 |
+
INPUT:
|
16 |
+
CROP:
|
17 |
+
ENABLED: True
|
18 |
+
FORMAT: "RGB"
|
19 |
+
OUTPUT_DIR: './output/regionspot_alldata_bb'
|
configs/objects365_v3det_openimages_bl.yaml
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
_BASE_: "Base-RegionSpot.yaml"
|
2 |
+
MODEL:
|
3 |
+
WEIGHTS: "./output/regionspot_obj365_bl/model_final.pth"
|
4 |
+
CLIP_TYPE: CLIP_400M_Large
|
5 |
+
DATALOADER:
|
6 |
+
SAMPLER_TRAIN: "MultiDatasetSampler"
|
7 |
+
DATASETS:
|
8 |
+
TRAIN: ("objects365_train", "v3det_train","openimages_train",)
|
9 |
+
TEST: ()
|
10 |
+
TEST:
|
11 |
+
EVAL_PERIOD: 0
|
12 |
+
SOLVER:
|
13 |
+
STEPS: (350000, 420000)
|
14 |
+
MAX_ITER: 450000
|
15 |
+
INPUT:
|
16 |
+
CROP:
|
17 |
+
ENABLED: True
|
18 |
+
FORMAT: "RGB"
|
19 |
+
OUTPUT_DIR: './output/regionspot_alldata_bl'
|
configs/objects365_v3det_openimages_bl_336.yaml
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
_BASE_: "Base-RegionSpot.yaml"
|
2 |
+
MODEL:
|
3 |
+
WEIGHTS: "./output/regionspot_obj365_bl_336/model_final.pth"
|
4 |
+
CLIP_TYPE: CLIP_400M_Large_336
|
5 |
+
CLIP_INPUT_SIZE: 336
|
6 |
+
DATALOADER:
|
7 |
+
SAMPLER_TRAIN: "MultiDatasetSampler"
|
8 |
+
DATASETS:
|
9 |
+
TRAIN: ("objects365_train", "v3det_train","openimages_train",)
|
10 |
+
TEST: ()
|
11 |
+
TEST:
|
12 |
+
EVAL_PERIOD: 0
|
13 |
+
SOLVER:
|
14 |
+
STEPS: (350000, 420000)
|
15 |
+
MAX_ITER: 450000
|
16 |
+
INPUT:
|
17 |
+
CROP:
|
18 |
+
ENABLED: True
|
19 |
+
FORMAT: "RGB"
|
20 |
+
OUTPUT_DIR: './output/regionspot_alldata_bl_336'
|
demo.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import cv2
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
from regionspot.modeling.regionspot import build_regionspot_model
|
5 |
+
from regionspot import RegionSpot_Predictor
|
6 |
+
# Function to show masks on an image
|
7 |
+
def show_mask(mask, ax, random_color=False):
|
8 |
+
if random_color:
|
9 |
+
color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
|
10 |
+
else:
|
11 |
+
color = np.array([30/255, 144/255, 255/255, 0.6])
|
12 |
+
h, w = mask.shape[-2:]
|
13 |
+
mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
|
14 |
+
ax.imshow(mask_image)
|
15 |
+
|
16 |
+
# Function to show points on an image
|
17 |
+
def show_points(coords, labels, ax, marker_size=375):
|
18 |
+
pos_points = coords[labels == 1]
|
19 |
+
neg_points = coords[labels == 0]
|
20 |
+
ax.scatter(pos_points[:, 0], pos_points[:, 1], color='green', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)
|
21 |
+
ax.scatter(neg_points[:, 0], neg_points[:, 1], color='red', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)
|
22 |
+
|
23 |
+
# Function to show bounding boxes on an image
|
24 |
+
def show_box(box, ax):
|
25 |
+
x0, y0 = box[0], box[1]
|
26 |
+
w, h = box[2] - x0, box[3] - y0
|
27 |
+
ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor='none', lw=2))
|
28 |
+
|
29 |
+
# Read image and set up model
|
30 |
+
image = cv2.imread('assets/image.jpg')
|
31 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert image to RGB format
|
32 |
+
# Multiple boxes
|
33 |
+
box_prompt = np.array([[64, 926, 804, 1978], [1237, 490, 1615, 771.], [1510, 64, 1670, 167]])
|
34 |
+
ckpt_path = '/path/to/model_weights.pth'
|
35 |
+
clip_type = 'CLIP_400M_Large_336'
|
36 |
+
clip_input_size = 336
|
37 |
+
custom_vocabulary = ["Smoothie bowl", "Banana", "Strawberry", "Chia seeds", "Shredded coconut", "Wooden spoons", "Grapefruit", "Goji berries", "Flaxseeds seeds"]
|
38 |
+
|
39 |
+
# Build and initialize the model
|
40 |
+
model, msg = build_regionspot_model(is_training=False, image_size=clip_input_size, clip_type=clip_type, pretrain_ckpt=ckpt_path, custom_vocabulary=custom_vocabulary)
|
41 |
+
|
42 |
+
# Create predictor and set image
|
43 |
+
predictor = RegionSpot_Predictor(model.cuda())
|
44 |
+
predictor.set_image(image, clip_input_size=clip_input_size)
|
45 |
+
|
46 |
+
# Prediction based on box prompt
|
47 |
+
masks, mask_iou_score, class_score, class_index = predictor.predict(
|
48 |
+
point_coords=None,
|
49 |
+
point_labels=None,
|
50 |
+
box=box_prompt,
|
51 |
+
multimask_output=False,
|
52 |
+
)
|
53 |
+
# Extract class name and display image with masks and box
|
54 |
+
fig, ax = plt.subplots(figsize=(10, 10))
|
55 |
+
ax.imshow(image)
|
56 |
+
for idx in range(len(box_prompt)):
|
57 |
+
show_mask(masks[idx], ax)
|
58 |
+
show_box(box_prompt[idx], ax) # Assuming box_prompt contains all your boxes
|
59 |
+
# You might want to modify the text display for multiple classes as well
|
60 |
+
class_name = custom_vocabulary[int(class_index[idx])]
|
61 |
+
ax.text(box_prompt[idx][0], box_prompt[idx][1] - 10, class_name, color='white', fontsize=14, bbox=dict(facecolor='green', edgecolor='green', alpha=0.6))
|
62 |
+
|
63 |
+
ax.axis('off')
|
64 |
+
plt.show()
|
65 |
+
fig.savefig('result.png')
|
66 |
+
plt.close(fig)
|
67 |
+
|
flagged/input_img/0fce6cef302bd30bbf85/000000052891.jpg
ADDED
flagged/log.csv
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
input_img,output,flag,username,timestamp
|
2 |
+
"{""path"":""flagged\\input_img\\0fce6cef302bd30bbf85\\000000052891.jpg"",""url"":""http://127.0.0.1:7862/file=C:\\Users\\10051\\AppData\\Local\\Temp\\gradio\\f11efb7c9dd110c5865f9afd384282cda8ca1f25\\000000052891.jpg"",""size"":153377,""orig_name"":""000000052891.jpg"",""mime_type"":""""}","{""path"":""flagged\\output\\440681fbd96cfcf67ac5\\image.png"",""url"":null,""size"":null,""orig_name"":null,""mime_type"":null}",,,2023-11-10 12:08:05.538914
|
flagged/output/440681fbd96cfcf67ac5/image.png
ADDED
images/000000030494.jpg
ADDED
images/000000052891.jpg
ADDED
images/20231108222434.jpg
ADDED
images/20231108222549.jpg
ADDED
images/20231108223144.jpg
ADDED
images/dog.jpg
ADDED
images/fish.jpeg
ADDED
images/groceries.jpg
ADDED
images/images/truck.jpg
ADDED
images/pic1.jpg
ADDED
images/pic2.png
ADDED
Git LFS Details
|
images/pic3.png
ADDED
Git LFS Details
|
images/pic4.png
ADDED
images/pic5.png
ADDED
images/truck.jpg
ADDED
images/truck2.png
ADDED
tools/re_save_ckpt.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
pretrain_ckpt = './pretrained_model/model_final.pth'
|
4 |
+
checkpoint = torch.load(pretrain_ckpt, map_location='cpu')
|
5 |
+
|
6 |
+
# Remove specific keys from the top-level dictionary
|
7 |
+
top_level_keys_to_remove = ['trainer', 'iteration']
|
8 |
+
for key in top_level_keys_to_remove:
|
9 |
+
if key in checkpoint:
|
10 |
+
del checkpoint[key]
|
11 |
+
|
12 |
+
# Remove keys that start with 'clip_model' and 'sam' from the checkpoint's 'model' dictionary
|
13 |
+
model_keys_to_remove = ['model.clip_model', 'model.sam']
|
14 |
+
for key in list(checkpoint['model'].keys()): # Use list to copy keys
|
15 |
+
if any(key.startswith(to_remove) for to_remove in model_keys_to_remove):
|
16 |
+
print(key)
|
17 |
+
del checkpoint['model'][key]
|
18 |
+
|
19 |
+
# Save the modified checkpoint back to a file
|
20 |
+
modified_ckpt_path = './pretrained_model/model_final_modified.pth'
|
21 |
+
torch.save(checkpoint, modified_ckpt_path)
|
22 |
+
print(checkpoint['model'].keys())
|
train_net.py
ADDED
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
3 |
+
|
4 |
+
This script is a simplified version of the training script in detectron2/tools.
|
5 |
+
"""
|
6 |
+
import os
|
7 |
+
import itertools
|
8 |
+
import weakref
|
9 |
+
from typing import Any, Dict, List, Set
|
10 |
+
import logging
|
11 |
+
from collections import OrderedDict
|
12 |
+
|
13 |
+
import torch
|
14 |
+
from fvcore.nn.precise_bn import get_bn_modules
|
15 |
+
|
16 |
+
import detectron2.utils.comm as comm
|
17 |
+
from detectron2.utils.logger import setup_logger
|
18 |
+
from detectron2.checkpoint import DetectionCheckpointer
|
19 |
+
from detectron2.config import get_cfg
|
20 |
+
from detectron2.data import build_detection_train_loader
|
21 |
+
from regionspot import build_custom_train_loader
|
22 |
+
|
23 |
+
from detectron2.engine import DefaultTrainer, default_argument_parser, default_setup, launch, create_ddp_model, \
|
24 |
+
AMPTrainer, SimpleTrainer, hooks
|
25 |
+
from detectron2.evaluation import COCOEvaluator, LVISEvaluator, verify_results
|
26 |
+
from detectron2.solver.build import maybe_add_gradient_clipping
|
27 |
+
from detectron2.modeling import build_model
|
28 |
+
from regionspot.data import objects365
|
29 |
+
from regionspot.data import openimages
|
30 |
+
from regionspot.data import v3det
|
31 |
+
|
32 |
+
|
33 |
+
from regionspot import RegionSpotDatasetMapper, add_regionspot_config, RegionSpotWithTTA
|
34 |
+
from regionspot.util.model_ema import add_model_ema_configs, may_build_model_ema, may_get_ema_checkpointer, EMAHook, \
|
35 |
+
apply_model_ema_and_restore, EMADetectionCheckpointer
|
36 |
+
|
37 |
+
|
38 |
+
class Trainer(DefaultTrainer):
|
39 |
+
""" Extension of the Trainer class adapted to RegionSpot. """
|
40 |
+
|
41 |
+
def __init__(self, cfg):
|
42 |
+
"""
|
43 |
+
Args:
|
44 |
+
cfg (CfgNode):
|
45 |
+
"""
|
46 |
+
super(DefaultTrainer, self).__init__() # call grandfather's `__init__` while avoid father's `__init()`
|
47 |
+
logger = logging.getLogger("detectron2")
|
48 |
+
if not logger.isEnabledFor(logging.INFO): # setup_logger is not called for d2
|
49 |
+
setup_logger()
|
50 |
+
cfg = DefaultTrainer.auto_scale_workers(cfg, comm.get_world_size())
|
51 |
+
# Assume these objects must be constructed in this order.
|
52 |
+
model = self.build_model(cfg)
|
53 |
+
optimizer = self.build_optimizer(cfg, model)
|
54 |
+
data_loader = self.build_train_loader(cfg)
|
55 |
+
|
56 |
+
model = create_ddp_model(model, broadcast_buffers=False)
|
57 |
+
self._trainer = (AMPTrainer if cfg.SOLVER.AMP.ENABLED else SimpleTrainer)(
|
58 |
+
model, data_loader, optimizer
|
59 |
+
)
|
60 |
+
|
61 |
+
self.scheduler = self.build_lr_scheduler(cfg, optimizer)
|
62 |
+
|
63 |
+
########## EMA ############
|
64 |
+
kwargs = {
|
65 |
+
'trainer': weakref.proxy(self),
|
66 |
+
}
|
67 |
+
kwargs.update(may_get_ema_checkpointer(cfg, model))
|
68 |
+
self.checkpointer = DetectionCheckpointer(
|
69 |
+
# Assume you want to save checkpoints together with logs/statistics
|
70 |
+
model,
|
71 |
+
cfg.OUTPUT_DIR,
|
72 |
+
**kwargs,
|
73 |
+
# trainer=weakref.proxy(self),
|
74 |
+
)
|
75 |
+
self.start_iter = 0
|
76 |
+
self.max_iter = cfg.SOLVER.MAX_ITER
|
77 |
+
self.cfg = cfg
|
78 |
+
|
79 |
+
self.register_hooks(self.build_hooks())
|
80 |
+
|
81 |
+
@classmethod
|
82 |
+
def build_model(cls, cfg):
|
83 |
+
"""
|
84 |
+
Returns:
|
85 |
+
torch.nn.Module:
|
86 |
+
|
87 |
+
It now calls :func:`detectron2.modeling.build_model`.
|
88 |
+
Overwrite it if you'd like a different model.
|
89 |
+
"""
|
90 |
+
model = build_model(cfg)
|
91 |
+
logger = logging.getLogger(__name__)
|
92 |
+
logger.info("Model:\n{}".format(model))
|
93 |
+
# setup EMA
|
94 |
+
may_build_model_ema(cfg, model)
|
95 |
+
return model
|
96 |
+
|
97 |
+
@classmethod
|
98 |
+
def build_evaluator(cls, cfg, dataset_name, output_folder=None):
|
99 |
+
"""
|
100 |
+
Create evaluator(s) for a given dataset.
|
101 |
+
This uses the special metadata "evaluator_type" associated with each builtin dataset.
|
102 |
+
For your own dataset, you can simply create an evaluator manually in your
|
103 |
+
script and do not have to worry about the hacky if-else logic here.
|
104 |
+
"""
|
105 |
+
if output_folder is None:
|
106 |
+
output_folder = os.path.join(cfg.OUTPUT_DIR, "inference")
|
107 |
+
if 'lvis' in dataset_name:
|
108 |
+
return LVISEvaluator(dataset_name, cfg, True, output_folder)
|
109 |
+
else:
|
110 |
+
return COCOEvaluator(dataset_name, cfg, True, output_folder)
|
111 |
+
|
112 |
+
@classmethod
|
113 |
+
def build_train_loader(cls, cfg):
|
114 |
+
mapper = RegionSpotDatasetMapper(cfg, is_train=True)
|
115 |
+
if cfg.DATALOADER.SAMPLER_TRAIN in ['TrainingSampler', 'RepeatFactorTrainingSampler']:
|
116 |
+
data_loader = build_detection_train_loader(cfg, mapper=mapper)
|
117 |
+
else:
|
118 |
+
data_loader = build_custom_train_loader(cfg, mapper=mapper)
|
119 |
+
return data_loader
|
120 |
+
@classmethod
|
121 |
+
def build_optimizer(cls, cfg, model):
|
122 |
+
params: List[Dict[str, Any]] = []
|
123 |
+
memo: Set[torch.nn.parameter.Parameter] = set()
|
124 |
+
for key, value in model.named_parameters(recurse=True):
|
125 |
+
if not value.requires_grad:
|
126 |
+
continue
|
127 |
+
# Avoid duplicating parameters
|
128 |
+
if value in memo:
|
129 |
+
continue
|
130 |
+
memo.add(value)
|
131 |
+
lr = cfg.SOLVER.BASE_LR
|
132 |
+
weight_decay = cfg.SOLVER.WEIGHT_DECAY
|
133 |
+
if "backbone" in key:
|
134 |
+
lr = lr * cfg.SOLVER.BACKBONE_MULTIPLIER
|
135 |
+
params += [{"params": [value], "lr": lr, "weight_decay": weight_decay}]
|
136 |
+
|
137 |
+
def maybe_add_full_model_gradient_clipping(optim): # optim: the optimizer class
|
138 |
+
# detectron2 doesn't have full model gradient clipping now
|
139 |
+
clip_norm_val = cfg.SOLVER.CLIP_GRADIENTS.CLIP_VALUE
|
140 |
+
enable = (
|
141 |
+
cfg.SOLVER.CLIP_GRADIENTS.ENABLED
|
142 |
+
and cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == "full_model"
|
143 |
+
and clip_norm_val > 0.0
|
144 |
+
)
|
145 |
+
|
146 |
+
class FullModelGradientClippingOptimizer(optim):
|
147 |
+
def step(self, closure=None):
|
148 |
+
all_params = itertools.chain(*[x["params"] for x in self.param_groups])
|
149 |
+
torch.nn.utils.clip_grad_norm_(all_params, clip_norm_val)
|
150 |
+
super().step(closure=closure)
|
151 |
+
|
152 |
+
return FullModelGradientClippingOptimizer if enable else optim
|
153 |
+
|
154 |
+
optimizer_type = cfg.SOLVER.OPTIMIZER
|
155 |
+
if optimizer_type == "SGD":
|
156 |
+
optimizer = maybe_add_full_model_gradient_clipping(torch.optim.SGD)(
|
157 |
+
params, cfg.SOLVER.BASE_LR, momentum=cfg.SOLVER.MOMENTUM
|
158 |
+
)
|
159 |
+
elif optimizer_type == "ADAMW":
|
160 |
+
optimizer = maybe_add_full_model_gradient_clipping(torch.optim.AdamW)(
|
161 |
+
params, cfg.SOLVER.BASE_LR
|
162 |
+
)
|
163 |
+
else:
|
164 |
+
raise NotImplementedError(f"no optimizer type {optimizer_type}")
|
165 |
+
if not cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == "full_model":
|
166 |
+
optimizer = maybe_add_gradient_clipping(cfg, optimizer)
|
167 |
+
return optimizer
|
168 |
+
|
169 |
+
@classmethod
|
170 |
+
def ema_test(cls, cfg, model, evaluators=None):
|
171 |
+
# model with ema weights
|
172 |
+
logger = logging.getLogger("detectron2.trainer")
|
173 |
+
if cfg.MODEL_EMA.ENABLED:
|
174 |
+
logger.info("Run evaluation with EMA.")
|
175 |
+
with apply_model_ema_and_restore(model):
|
176 |
+
results = cls.test(cfg, model, evaluators=evaluators)
|
177 |
+
else:
|
178 |
+
results = cls.test(cfg, model, evaluators=evaluators)
|
179 |
+
return results
|
180 |
+
|
181 |
+
@classmethod
|
182 |
+
def test_with_TTA(cls, cfg, model):
|
183 |
+
logger = logging.getLogger("detectron2.trainer")
|
184 |
+
logger.info("Running inference with test-time augmentation ...")
|
185 |
+
model = RegionSpotWithTTA(cfg, model)
|
186 |
+
evaluators = [
|
187 |
+
cls.build_evaluator(
|
188 |
+
cfg, name, output_folder=os.path.join(cfg.OUTPUT_DIR, "inference_TTA")
|
189 |
+
)
|
190 |
+
for name in cfg.DATASETS.TEST
|
191 |
+
]
|
192 |
+
if cfg.MODEL_EMA.ENABLED:
|
193 |
+
cls.ema_test(cfg, model, evaluators)
|
194 |
+
else:
|
195 |
+
res = cls.test(cfg, model, evaluators)
|
196 |
+
res = OrderedDict({k + "_TTA": v for k, v in res.items()})
|
197 |
+
return res
|
198 |
+
|
199 |
+
def build_hooks(self):
|
200 |
+
"""
|
201 |
+
Build a list of default hooks, including timing, evaluation,
|
202 |
+
checkpointing, lr scheduling, precise BN, writing events.
|
203 |
+
|
204 |
+
Returns:
|
205 |
+
list[HookBase]:
|
206 |
+
"""
|
207 |
+
cfg = self.cfg.clone()
|
208 |
+
cfg.defrost()
|
209 |
+
cfg.DATALOADER.NUM_WORKERS = 0 # save some memory and time for PreciseBN
|
210 |
+
|
211 |
+
ret = [
|
212 |
+
hooks.IterationTimer(),
|
213 |
+
EMAHook(self.cfg, self.model) if cfg.MODEL_EMA.ENABLED else None, # EMA hook
|
214 |
+
hooks.LRScheduler(),
|
215 |
+
hooks.PreciseBN(
|
216 |
+
# Run at the same freq as (but before) evaluation.
|
217 |
+
cfg.TEST.EVAL_PERIOD,
|
218 |
+
self.model,
|
219 |
+
# Build a new data loader to not affect training
|
220 |
+
self.build_train_loader(cfg),
|
221 |
+
cfg.TEST.PRECISE_BN.NUM_ITER,
|
222 |
+
)
|
223 |
+
if cfg.TEST.PRECISE_BN.ENABLED and get_bn_modules(self.model)
|
224 |
+
else None,
|
225 |
+
]
|
226 |
+
|
227 |
+
# Do PreciseBN before checkpointer, because it updates the model and need to
|
228 |
+
# be saved by checkpointer.
|
229 |
+
# This is not always the best: if checkpointing has a different frequency,
|
230 |
+
# some checkpoints may have more precise statistics than others.
|
231 |
+
if comm.is_main_process():
|
232 |
+
ret.append(hooks.PeriodicCheckpointer(self.checkpointer, cfg.SOLVER.CHECKPOINT_PERIOD))
|
233 |
+
|
234 |
+
def test_and_save_results():
|
235 |
+
self._last_eval_results = self.test(self.cfg, self.model)
|
236 |
+
return self._last_eval_results
|
237 |
+
|
238 |
+
# Do evaluation after checkpointer, because then if it fails,
|
239 |
+
# we can use the saved checkpoint to debug.
|
240 |
+
ret.append(hooks.EvalHook(cfg.TEST.EVAL_PERIOD, test_and_save_results))
|
241 |
+
|
242 |
+
if comm.is_main_process():
|
243 |
+
# Here the default print/log frequency of each writer is used.
|
244 |
+
# run writers in the end, so that evaluation metrics are written
|
245 |
+
ret.append(hooks.PeriodicWriter(self.build_writers(), period=20))
|
246 |
+
return ret
|
247 |
+
|
248 |
+
|
249 |
+
def setup(args):
|
250 |
+
"""
|
251 |
+
Create configs and perform basic setups.
|
252 |
+
"""
|
253 |
+
cfg = get_cfg()
|
254 |
+
add_regionspot_config(cfg)
|
255 |
+
add_model_ema_configs(cfg)
|
256 |
+
cfg.merge_from_file(args.config_file)
|
257 |
+
cfg.merge_from_list(args.opts)
|
258 |
+
cfg.freeze()
|
259 |
+
default_setup(cfg, args)
|
260 |
+
return cfg
|
261 |
+
|
262 |
+
|
263 |
+
def main(args):
|
264 |
+
cfg = setup(args)
|
265 |
+
|
266 |
+
if args.eval_only:
|
267 |
+
model = Trainer.build_model(cfg)
|
268 |
+
kwargs = may_get_ema_checkpointer(cfg, model)
|
269 |
+
if cfg.MODEL_EMA.ENABLED:
|
270 |
+
EMADetectionCheckpointer(model, save_dir=cfg.OUTPUT_DIR, **kwargs).resume_or_load(cfg.MODEL.WEIGHTS,
|
271 |
+
resume=args.resume)
|
272 |
+
else:
|
273 |
+
DetectionCheckpointer(model, save_dir=cfg.OUTPUT_DIR, **kwargs).resume_or_load(cfg.MODEL.WEIGHTS,
|
274 |
+
resume=args.resume)
|
275 |
+
res = Trainer.ema_test(cfg, model)
|
276 |
+
if cfg.TEST.AUG.ENABLED:
|
277 |
+
res.update(Trainer.test_with_TTA(cfg, model))
|
278 |
+
if comm.is_main_process():
|
279 |
+
verify_results(cfg, res)
|
280 |
+
return res
|
281 |
+
|
282 |
+
trainer = Trainer(cfg)
|
283 |
+
trainer.resume_or_load(resume=args.resume)
|
284 |
+
return trainer.train()
|
285 |
+
|
286 |
+
|
287 |
+
if __name__ == "__main__":
|
288 |
+
args = default_argument_parser().parse_args()
|
289 |
+
print("Command Line Args:", args)
|
290 |
+
launch(
|
291 |
+
main,
|
292 |
+
args.num_gpus,
|
293 |
+
num_machines=args.num_machines,
|
294 |
+
machine_rank=args.machine_rank,
|
295 |
+
dist_url=args.dist_url,
|
296 |
+
args=(args,),
|
297 |
+
)
|
utils/__pycache__/tools.cpython-38.pyc
ADDED
Binary file (12.7 kB). View file
|
|
utils/__pycache__/tools_gradio.cpython-38.pyc
ADDED
Binary file (4.76 kB). View file
|
|
utils/tools.py
ADDED
@@ -0,0 +1,442 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from PIL import Image
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
import cv2
|
5 |
+
import torch
|
6 |
+
import os
|
7 |
+
import sys
|
8 |
+
import clip
|
9 |
+
|
10 |
+
|
11 |
+
def convert_box_xywh_to_xyxy(box):
|
12 |
+
if len(box) == 4:
|
13 |
+
return [box[0], box[1], box[0] + box[2], box[1] + box[3]]
|
14 |
+
else:
|
15 |
+
result = []
|
16 |
+
for b in box:
|
17 |
+
b = convert_box_xywh_to_xyxy(b)
|
18 |
+
result.append(b)
|
19 |
+
return result
|
20 |
+
|
21 |
+
|
22 |
+
def segment_image(image, bbox):
|
23 |
+
image_array = np.array(image)
|
24 |
+
segmented_image_array = np.zeros_like(image_array)
|
25 |
+
x1, y1, x2, y2 = bbox
|
26 |
+
segmented_image_array[y1:y2, x1:x2] = image_array[y1:y2, x1:x2]
|
27 |
+
segmented_image = Image.fromarray(segmented_image_array)
|
28 |
+
black_image = Image.new("RGB", image.size, (255, 255, 255))
|
29 |
+
# transparency_mask = np.zeros_like((), dtype=np.uint8)
|
30 |
+
transparency_mask = np.zeros(
|
31 |
+
(image_array.shape[0], image_array.shape[1]), dtype=np.uint8
|
32 |
+
)
|
33 |
+
transparency_mask[y1:y2, x1:x2] = 255
|
34 |
+
transparency_mask_image = Image.fromarray(transparency_mask, mode="L")
|
35 |
+
black_image.paste(segmented_image, mask=transparency_mask_image)
|
36 |
+
return black_image
|
37 |
+
|
38 |
+
|
39 |
+
def format_results(result, filter=0):
|
40 |
+
annotations = []
|
41 |
+
n = len(result.masks.data)
|
42 |
+
for i in range(n):
|
43 |
+
annotation = {}
|
44 |
+
mask = result.masks.data[i] == 1.0
|
45 |
+
|
46 |
+
if torch.sum(mask) < filter:
|
47 |
+
continue
|
48 |
+
annotation["id"] = i
|
49 |
+
annotation["segmentation"] = mask.cpu().numpy()
|
50 |
+
annotation["bbox"] = result.boxes.data[i]
|
51 |
+
annotation["score"] = result.boxes.conf[i]
|
52 |
+
annotation["area"] = annotation["segmentation"].sum()
|
53 |
+
annotations.append(annotation)
|
54 |
+
return annotations
|
55 |
+
|
56 |
+
|
57 |
+
def filter_masks(annotations): # filter the overlap mask
|
58 |
+
annotations.sort(key=lambda x: x["area"], reverse=True)
|
59 |
+
to_remove = set()
|
60 |
+
for i in range(0, len(annotations)):
|
61 |
+
a = annotations[i]
|
62 |
+
for j in range(i + 1, len(annotations)):
|
63 |
+
b = annotations[j]
|
64 |
+
if i != j and j not in to_remove:
|
65 |
+
# check if
|
66 |
+
if b["area"] < a["area"]:
|
67 |
+
if (a["segmentation"] & b["segmentation"]).sum() / b[
|
68 |
+
"segmentation"
|
69 |
+
].sum() > 0.8:
|
70 |
+
to_remove.add(j)
|
71 |
+
|
72 |
+
return [a for i, a in enumerate(annotations) if i not in to_remove], to_remove
|
73 |
+
|
74 |
+
|
75 |
+
def get_bbox_from_mask(mask):
|
76 |
+
mask = mask.astype(np.uint8)
|
77 |
+
contours, hierarchy = cv2.findContours(
|
78 |
+
mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
|
79 |
+
)
|
80 |
+
x1, y1, w, h = cv2.boundingRect(contours[0])
|
81 |
+
x2, y2 = x1 + w, y1 + h
|
82 |
+
if len(contours) > 1:
|
83 |
+
for b in contours:
|
84 |
+
x_t, y_t, w_t, h_t = cv2.boundingRect(b)
|
85 |
+
# 将多个bbox合并成一个
|
86 |
+
x1 = min(x1, x_t)
|
87 |
+
y1 = min(y1, y_t)
|
88 |
+
x2 = max(x2, x_t + w_t)
|
89 |
+
y2 = max(y2, y_t + h_t)
|
90 |
+
h = y2 - y1
|
91 |
+
w = x2 - x1
|
92 |
+
return [x1, y1, x2, y2]
|
93 |
+
|
94 |
+
|
95 |
+
def fast_process(
|
96 |
+
annotations, args, mask_random_color, bbox=None, points=None, edges=False
|
97 |
+
):
|
98 |
+
if isinstance(annotations[0], dict):
|
99 |
+
annotations = [annotation["segmentation"] for annotation in annotations]
|
100 |
+
result_name = os.path.basename(args.img_path)
|
101 |
+
image = cv2.imread(args.img_path)
|
102 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
103 |
+
original_h = image.shape[0]
|
104 |
+
original_w = image.shape[1]
|
105 |
+
if sys.platform == "darwin":
|
106 |
+
plt.switch_backend("TkAgg")
|
107 |
+
plt.figure(figsize=(original_w/100, original_h/100))
|
108 |
+
# Add subplot with no margin.
|
109 |
+
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
|
110 |
+
plt.margins(0, 0)
|
111 |
+
plt.gca().xaxis.set_major_locator(plt.NullLocator())
|
112 |
+
plt.gca().yaxis.set_major_locator(plt.NullLocator())
|
113 |
+
plt.imshow(image)
|
114 |
+
if args.better_quality == True:
|
115 |
+
if isinstance(annotations[0], torch.Tensor):
|
116 |
+
annotations = np.array(annotations.cpu())
|
117 |
+
for i, mask in enumerate(annotations):
|
118 |
+
mask = cv2.morphologyEx(
|
119 |
+
mask.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8)
|
120 |
+
)
|
121 |
+
annotations[i] = cv2.morphologyEx(
|
122 |
+
mask.astype(np.uint8), cv2.MORPH_OPEN, np.ones((8, 8), np.uint8)
|
123 |
+
)
|
124 |
+
if args.device == "cpu":
|
125 |
+
annotations = np.array(annotations)
|
126 |
+
fast_show_mask(
|
127 |
+
annotations,
|
128 |
+
plt.gca(),
|
129 |
+
random_color=mask_random_color,
|
130 |
+
bbox=bbox,
|
131 |
+
points=points,
|
132 |
+
point_label=args.point_label,
|
133 |
+
retinamask=args.retina,
|
134 |
+
target_height=original_h,
|
135 |
+
target_width=original_w,
|
136 |
+
)
|
137 |
+
else:
|
138 |
+
if isinstance(annotations[0], np.ndarray):
|
139 |
+
annotations = torch.from_numpy(annotations)
|
140 |
+
fast_show_mask_gpu(
|
141 |
+
annotations,
|
142 |
+
plt.gca(),
|
143 |
+
random_color=args.randomcolor,
|
144 |
+
bbox=bbox,
|
145 |
+
points=points,
|
146 |
+
point_label=args.point_label,
|
147 |
+
retinamask=args.retina,
|
148 |
+
target_height=original_h,
|
149 |
+
target_width=original_w,
|
150 |
+
)
|
151 |
+
if isinstance(annotations, torch.Tensor):
|
152 |
+
annotations = annotations.cpu().numpy()
|
153 |
+
if args.withContours == True:
|
154 |
+
contour_all = []
|
155 |
+
temp = np.zeros((original_h, original_w, 1))
|
156 |
+
for i, mask in enumerate(annotations):
|
157 |
+
if type(mask) == dict:
|
158 |
+
mask = mask["segmentation"]
|
159 |
+
annotation = mask.astype(np.uint8)
|
160 |
+
if args.retina == False:
|
161 |
+
annotation = cv2.resize(
|
162 |
+
annotation,
|
163 |
+
(original_w, original_h),
|
164 |
+
interpolation=cv2.INTER_NEAREST,
|
165 |
+
)
|
166 |
+
contours, hierarchy = cv2.findContours(
|
167 |
+
annotation, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
|
168 |
+
)
|
169 |
+
for contour in contours:
|
170 |
+
contour_all.append(contour)
|
171 |
+
cv2.drawContours(temp, contour_all, -1, (255, 255, 255), 2)
|
172 |
+
color = np.array([0 / 255, 0 / 255, 255 / 255, 0.8])
|
173 |
+
contour_mask = temp / 255 * color.reshape(1, 1, -1)
|
174 |
+
plt.imshow(contour_mask)
|
175 |
+
|
176 |
+
save_path = args.output
|
177 |
+
if not os.path.exists(save_path):
|
178 |
+
os.makedirs(save_path)
|
179 |
+
plt.axis("off")
|
180 |
+
fig = plt.gcf()
|
181 |
+
plt.draw()
|
182 |
+
|
183 |
+
try:
|
184 |
+
buf = fig.canvas.tostring_rgb()
|
185 |
+
except AttributeError:
|
186 |
+
fig.canvas.draw()
|
187 |
+
buf = fig.canvas.tostring_rgb()
|
188 |
+
|
189 |
+
cols, rows = fig.canvas.get_width_height()
|
190 |
+
img_array = np.fromstring(buf, dtype=np.uint8).reshape(rows, cols, 3)
|
191 |
+
cv2.imwrite(os.path.join(save_path, result_name), cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR))
|
192 |
+
|
193 |
+
|
194 |
+
# CPU post process
|
195 |
+
def fast_show_mask(
|
196 |
+
annotation,
|
197 |
+
ax,
|
198 |
+
random_color=False,
|
199 |
+
bbox=None,
|
200 |
+
points=None,
|
201 |
+
point_label=None,
|
202 |
+
retinamask=True,
|
203 |
+
target_height=960,
|
204 |
+
target_width=960,
|
205 |
+
):
|
206 |
+
msak_sum = annotation.shape[0]
|
207 |
+
height = annotation.shape[1]
|
208 |
+
weight = annotation.shape[2]
|
209 |
+
# 将annotation 按照面积 排序
|
210 |
+
areas = np.sum(annotation, axis=(1, 2))
|
211 |
+
sorted_indices = np.argsort(areas)
|
212 |
+
annotation = annotation[sorted_indices]
|
213 |
+
|
214 |
+
index = (annotation != 0).argmax(axis=0)
|
215 |
+
if random_color == True:
|
216 |
+
color = np.random.random((msak_sum, 1, 1, 3))
|
217 |
+
else:
|
218 |
+
color = np.ones((msak_sum, 1, 1, 3)) * np.array(
|
219 |
+
[30 / 255, 144 / 255, 255 / 255]
|
220 |
+
)
|
221 |
+
transparency = np.ones((msak_sum, 1, 1, 1)) * 0.6
|
222 |
+
visual = np.concatenate([color, transparency], axis=-1)
|
223 |
+
mask_image = np.expand_dims(annotation, -1) * visual
|
224 |
+
|
225 |
+
show = np.zeros((height, weight, 4))
|
226 |
+
h_indices, w_indices = np.meshgrid(
|
227 |
+
np.arange(height), np.arange(weight), indexing="ij"
|
228 |
+
)
|
229 |
+
indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))
|
230 |
+
# 使用向量化索引更新show的值
|
231 |
+
show[h_indices, w_indices, :] = mask_image[indices]
|
232 |
+
if bbox is not None:
|
233 |
+
x1, y1, x2, y2 = bbox
|
234 |
+
ax.add_patch(
|
235 |
+
plt.Rectangle(
|
236 |
+
(x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor="b", linewidth=1
|
237 |
+
)
|
238 |
+
)
|
239 |
+
# draw point
|
240 |
+
if points is not None:
|
241 |
+
plt.scatter(
|
242 |
+
[point[0] for i, point in enumerate(points) if point_label[i] == 1],
|
243 |
+
[point[1] for i, point in enumerate(points) if point_label[i] == 1],
|
244 |
+
s=20,
|
245 |
+
c="y",
|
246 |
+
)
|
247 |
+
plt.scatter(
|
248 |
+
[point[0] for i, point in enumerate(points) if point_label[i] == 0],
|
249 |
+
[point[1] for i, point in enumerate(points) if point_label[i] == 0],
|
250 |
+
s=20,
|
251 |
+
c="m",
|
252 |
+
)
|
253 |
+
|
254 |
+
if retinamask == False:
|
255 |
+
show = cv2.resize(
|
256 |
+
show, (target_width, target_height), interpolation=cv2.INTER_NEAREST
|
257 |
+
)
|
258 |
+
ax.imshow(show)
|
259 |
+
|
260 |
+
|
261 |
+
def fast_show_mask_gpu(
|
262 |
+
annotation,
|
263 |
+
ax,
|
264 |
+
random_color=False,
|
265 |
+
bbox=None,
|
266 |
+
points=None,
|
267 |
+
point_label=None,
|
268 |
+
retinamask=True,
|
269 |
+
target_height=960,
|
270 |
+
target_width=960,
|
271 |
+
):
|
272 |
+
msak_sum = annotation.shape[0]
|
273 |
+
height = annotation.shape[1]
|
274 |
+
weight = annotation.shape[2]
|
275 |
+
areas = torch.sum(annotation, dim=(1, 2))
|
276 |
+
sorted_indices = torch.argsort(areas, descending=False)
|
277 |
+
annotation = annotation[sorted_indices]
|
278 |
+
# 找每个位置第一个非零值下标
|
279 |
+
index = (annotation != 0).to(torch.long).argmax(dim=0)
|
280 |
+
if random_color == True:
|
281 |
+
color = torch.rand((msak_sum, 1, 1, 3)).to(annotation.device)
|
282 |
+
else:
|
283 |
+
color = torch.ones((msak_sum, 1, 1, 3)).to(annotation.device) * torch.tensor(
|
284 |
+
[30 / 255, 144 / 255, 255 / 255]
|
285 |
+
).to(annotation.device)
|
286 |
+
transparency = torch.ones((msak_sum, 1, 1, 1)).to(annotation.device) * 0.6
|
287 |
+
visual = torch.cat([color, transparency], dim=-1)
|
288 |
+
mask_image = torch.unsqueeze(annotation, -1) * visual
|
289 |
+
# 按index取数,index指每个位置选哪个batch的数,把mask_image转成一个batch的形式
|
290 |
+
show = torch.zeros((height, weight, 4)).to(annotation.device)
|
291 |
+
h_indices, w_indices = torch.meshgrid(
|
292 |
+
torch.arange(height), torch.arange(weight), indexing="ij"
|
293 |
+
)
|
294 |
+
indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))
|
295 |
+
# 使用向量化索引更新show的值
|
296 |
+
show[h_indices, w_indices, :] = mask_image[indices]
|
297 |
+
show_cpu = show.cpu().numpy()
|
298 |
+
if bbox is not None:
|
299 |
+
x1, y1, x2, y2 = bbox
|
300 |
+
ax.add_patch(
|
301 |
+
plt.Rectangle(
|
302 |
+
(x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor="b", linewidth=1
|
303 |
+
)
|
304 |
+
)
|
305 |
+
# draw point
|
306 |
+
if points is not None:
|
307 |
+
plt.scatter(
|
308 |
+
[point[0] for i, point in enumerate(points) if point_label[i] == 1],
|
309 |
+
[point[1] for i, point in enumerate(points) if point_label[i] == 1],
|
310 |
+
s=20,
|
311 |
+
c="y",
|
312 |
+
)
|
313 |
+
plt.scatter(
|
314 |
+
[point[0] for i, point in enumerate(points) if point_label[i] == 0],
|
315 |
+
[point[1] for i, point in enumerate(points) if point_label[i] == 0],
|
316 |
+
s=20,
|
317 |
+
c="m",
|
318 |
+
)
|
319 |
+
if retinamask == False:
|
320 |
+
show_cpu = cv2.resize(
|
321 |
+
show_cpu, (target_width, target_height), interpolation=cv2.INTER_NEAREST
|
322 |
+
)
|
323 |
+
ax.imshow(show_cpu)
|
324 |
+
|
325 |
+
|
326 |
+
# clip
|
327 |
+
@torch.no_grad()
|
328 |
+
def retriev(
|
329 |
+
model, preprocess, elements: [Image.Image], search_text: str, device
|
330 |
+
):
|
331 |
+
preprocessed_images = [preprocess(image).to(device) for image in elements]
|
332 |
+
tokenized_text = clip.tokenize([search_text]).to(device)
|
333 |
+
stacked_images = torch.stack(preprocessed_images)
|
334 |
+
image_features = model.encode_image(stacked_images)
|
335 |
+
text_features = model.encode_text(tokenized_text)
|
336 |
+
image_features /= image_features.norm(dim=-1, keepdim=True)
|
337 |
+
text_features /= text_features.norm(dim=-1, keepdim=True)
|
338 |
+
probs = 100.0 * image_features @ text_features.T
|
339 |
+
return probs[:, 0].softmax(dim=0)
|
340 |
+
|
341 |
+
|
342 |
+
def crop_image(annotations, image_like):
|
343 |
+
if isinstance(image_like, str):
|
344 |
+
image = Image.open(image_like)
|
345 |
+
else:
|
346 |
+
image = image_like
|
347 |
+
ori_w, ori_h = image.size
|
348 |
+
mask_h, mask_w = annotations[0]["segmentation"].shape
|
349 |
+
if ori_w != mask_w or ori_h != mask_h:
|
350 |
+
image = image.resize((mask_w, mask_h))
|
351 |
+
cropped_boxes = []
|
352 |
+
cropped_images = []
|
353 |
+
not_crop = []
|
354 |
+
origin_id = []
|
355 |
+
for _, mask in enumerate(annotations):
|
356 |
+
if np.sum(mask["segmentation"]) <= 100:
|
357 |
+
continue
|
358 |
+
origin_id.append(_)
|
359 |
+
bbox = get_bbox_from_mask(mask["segmentation"]) # mask 的 bbox
|
360 |
+
cropped_boxes.append(segment_image(image, bbox)) # 保存裁剪的图片
|
361 |
+
# cropped_boxes.append(segment_image(image,mask["segmentation"]))
|
362 |
+
cropped_images.append(bbox) # 保存裁剪的图片的bbox
|
363 |
+
return cropped_boxes, cropped_images, not_crop, origin_id, annotations
|
364 |
+
|
365 |
+
|
366 |
+
def box_prompt(masks, bbox, target_height, target_width):
|
367 |
+
h = masks.shape[1]
|
368 |
+
w = masks.shape[2]
|
369 |
+
if h != target_height or w != target_width:
|
370 |
+
bbox = [
|
371 |
+
int(bbox[0] * w / target_width),
|
372 |
+
int(bbox[1] * h / target_height),
|
373 |
+
int(bbox[2] * w / target_width),
|
374 |
+
int(bbox[3] * h / target_height),
|
375 |
+
]
|
376 |
+
bbox[0] = round(bbox[0]) if round(bbox[0]) > 0 else 0
|
377 |
+
bbox[1] = round(bbox[1]) if round(bbox[1]) > 0 else 0
|
378 |
+
bbox[2] = round(bbox[2]) if round(bbox[2]) < w else w
|
379 |
+
bbox[3] = round(bbox[3]) if round(bbox[3]) < h else h
|
380 |
+
|
381 |
+
# IoUs = torch.zeros(len(masks), dtype=torch.float32)
|
382 |
+
bbox_area = (bbox[3] - bbox[1]) * (bbox[2] - bbox[0])
|
383 |
+
|
384 |
+
masks_area = torch.sum(masks[:, bbox[1] : bbox[3], bbox[0] : bbox[2]], dim=(1, 2))
|
385 |
+
orig_masks_area = torch.sum(masks, dim=(1, 2))
|
386 |
+
|
387 |
+
union = bbox_area + orig_masks_area - masks_area
|
388 |
+
IoUs = masks_area / union
|
389 |
+
max_iou_index = torch.argmax(IoUs)
|
390 |
+
|
391 |
+
return masks[max_iou_index].cpu().numpy(), max_iou_index
|
392 |
+
|
393 |
+
|
394 |
+
def point_prompt(masks, points, point_label, target_height, target_width): # numpy 处理
|
395 |
+
h = masks[0]["segmentation"].shape[0]
|
396 |
+
w = masks[0]["segmentation"].shape[1]
|
397 |
+
if h != target_height or w != target_width:
|
398 |
+
points = [
|
399 |
+
[int(point[0] * w / target_width), int(point[1] * h / target_height)]
|
400 |
+
for point in points
|
401 |
+
]
|
402 |
+
onemask = np.zeros((h, w))
|
403 |
+
masks = sorted(masks, key=lambda x: x['area'], reverse=True)
|
404 |
+
for i, annotation in enumerate(masks):
|
405 |
+
if type(annotation) == dict:
|
406 |
+
mask = annotation['segmentation']
|
407 |
+
else:
|
408 |
+
mask = annotation
|
409 |
+
for i, point in enumerate(points):
|
410 |
+
if mask[point[1], point[0]] == 1 and point_label[i] == 1:
|
411 |
+
onemask[mask] = 1
|
412 |
+
if mask[point[1], point[0]] == 1 and point_label[i] == 0:
|
413 |
+
onemask[mask] = 0
|
414 |
+
onemask = onemask >= 1
|
415 |
+
return onemask, 0
|
416 |
+
|
417 |
+
|
418 |
+
def text_prompt(annotations, text, img_path, device, wider=False, threshold=0.9):
|
419 |
+
cropped_boxes, cropped_images, not_crop, origin_id, annotations_ = crop_image(
|
420 |
+
annotations, img_path
|
421 |
+
)
|
422 |
+
clip_model, preprocess = clip.load("./weights/CLIP_ViT_B_32.pt", device=device)
|
423 |
+
scores = retriev(
|
424 |
+
clip_model, preprocess, cropped_boxes, text, device=device
|
425 |
+
)
|
426 |
+
max_idx = scores.argsort()
|
427 |
+
max_idx = max_idx[-1]
|
428 |
+
max_idx = origin_id[int(max_idx)]
|
429 |
+
|
430 |
+
# find the biggest mask which contains the mask with max score
|
431 |
+
if wider:
|
432 |
+
mask0 = annotations_[max_idx]["segmentation"]
|
433 |
+
area0 = np.sum(mask0)
|
434 |
+
areas = [(i, np.sum(mask["segmentation"])) for i, mask in enumerate(annotations_) if i in origin_id]
|
435 |
+
areas = sorted(areas, key=lambda area: area[1], reverse=True)
|
436 |
+
indices = [area[0] for area in areas]
|
437 |
+
for index in indices:
|
438 |
+
if index == max_idx or np.sum(annotations_[index]["segmentation"] & mask0) / area0 > threshold:
|
439 |
+
max_idx = index
|
440 |
+
break
|
441 |
+
|
442 |
+
return annotations_[max_idx]["segmentation"], max_idx
|
utils/tools_gradio.py
ADDED
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from PIL import Image
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
import cv2
|
5 |
+
import torch
|
6 |
+
|
7 |
+
fdic = {
|
8 |
+
"family" : "Impact",
|
9 |
+
"style" : "italic",
|
10 |
+
"size" : 15,
|
11 |
+
"color" : "yellow",
|
12 |
+
"weight" : "bold"
|
13 |
+
}
|
14 |
+
|
15 |
+
def fast_process(
|
16 |
+
annotations,
|
17 |
+
image,
|
18 |
+
device,
|
19 |
+
scale,
|
20 |
+
better_quality=False,
|
21 |
+
mask_random_color=True,
|
22 |
+
bbox=None,
|
23 |
+
use_retina=True,
|
24 |
+
withContours=True,
|
25 |
+
label = None,
|
26 |
+
):
|
27 |
+
if isinstance(annotations[0], dict):
|
28 |
+
annotations = [annotation['segmentation'] for annotation in annotations]
|
29 |
+
|
30 |
+
original_h = image.height
|
31 |
+
original_w = image.width
|
32 |
+
if better_quality:
|
33 |
+
if isinstance(annotations[0], torch.Tensor):
|
34 |
+
annotations = np.array(annotations.cpu())
|
35 |
+
for i, mask in enumerate(annotations):
|
36 |
+
mask = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
|
37 |
+
annotations[i] = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_OPEN, np.ones((8, 8), np.uint8))
|
38 |
+
if device == 'cpu':
|
39 |
+
annotations = np.array(annotations)
|
40 |
+
inner_mask = fast_show_mask(
|
41 |
+
annotations,
|
42 |
+
plt.gca(),
|
43 |
+
random_color=mask_random_color,
|
44 |
+
bbox=bbox,
|
45 |
+
retinamask=use_retina,
|
46 |
+
target_height=original_h,
|
47 |
+
target_width=original_w,
|
48 |
+
label = label,
|
49 |
+
)
|
50 |
+
else:
|
51 |
+
if isinstance(annotations[0], np.ndarray):
|
52 |
+
annotations = torch.from_numpy(annotations)
|
53 |
+
inner_mask, figure = fast_show_mask_gpu(
|
54 |
+
annotations,
|
55 |
+
plt.gca(),
|
56 |
+
random_color=mask_random_color,
|
57 |
+
bbox=bbox,
|
58 |
+
retinamask=use_retina,
|
59 |
+
target_height=original_h,
|
60 |
+
target_width=original_w,
|
61 |
+
label = label,
|
62 |
+
)
|
63 |
+
if isinstance(annotations, torch.Tensor):
|
64 |
+
annotations = annotations.cpu().numpy()
|
65 |
+
|
66 |
+
if withContours:
|
67 |
+
contour_all = []
|
68 |
+
temp = np.zeros((original_h, original_w, 1))
|
69 |
+
for i, mask in enumerate(annotations):
|
70 |
+
if type(mask) == dict:
|
71 |
+
mask = mask['segmentation']
|
72 |
+
annotation = mask.astype(np.uint8)
|
73 |
+
if use_retina == False:
|
74 |
+
annotation = cv2.resize(
|
75 |
+
annotation,
|
76 |
+
(original_w, original_h),
|
77 |
+
interpolation=cv2.INTER_NEAREST,
|
78 |
+
)
|
79 |
+
contours, _ = cv2.findContours(annotation, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
|
80 |
+
for contour in contours:
|
81 |
+
contour_all.append(contour)
|
82 |
+
cv2.drawContours(temp, contour_all, -1, (255, 255, 255), 2 // scale)
|
83 |
+
color = np.array([0 / 255, 0 / 255, 255 / 255, 0.9])
|
84 |
+
contour_mask = temp / 255 * color.reshape(1, 1, -1)
|
85 |
+
|
86 |
+
image = image.convert('RGBA')
|
87 |
+
overlay_inner = Image.fromarray((inner_mask * 255).astype(np.uint8), 'RGBA')
|
88 |
+
image.paste(overlay_inner, (0, 0), overlay_inner)
|
89 |
+
|
90 |
+
if withContours:
|
91 |
+
overlay_contour = Image.fromarray((contour_mask * 255).astype(np.uint8), 'RGBA')
|
92 |
+
image.paste(overlay_contour, (0, 0), overlay_contour)
|
93 |
+
|
94 |
+
plt.figure(figsize=(16, 10))
|
95 |
+
plt.imshow(image)
|
96 |
+
ax = plt.gca()
|
97 |
+
if bbox is not None:
|
98 |
+
x1, y1, x2, y2 = bbox
|
99 |
+
ax.add_patch(plt.Rectangle((x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor='b', linewidth=1))
|
100 |
+
ax.text(x1, y1, f"{label}", fontdict=fdic)
|
101 |
+
pic = plt.gcf()
|
102 |
+
pic.canvas.draw()
|
103 |
+
w,h = pic.canvas.get_width_height()
|
104 |
+
image = Image.frombytes('RGB', (w,h), pic.canvas.tostring_rgb())
|
105 |
+
|
106 |
+
return image
|
107 |
+
|
108 |
+
|
109 |
+
# CPU post process
|
110 |
+
def fast_show_mask(
|
111 |
+
annotation,
|
112 |
+
ax,
|
113 |
+
random_color=False,
|
114 |
+
bbox=None,
|
115 |
+
retinamask=True,
|
116 |
+
target_height=960,
|
117 |
+
target_width=960,
|
118 |
+
label = None,
|
119 |
+
):
|
120 |
+
mask_sum = annotation.shape[0]
|
121 |
+
height = annotation.shape[1]
|
122 |
+
weight = annotation.shape[2]
|
123 |
+
# 将annotation 按照面积 排序
|
124 |
+
areas = np.sum(annotation, axis=(1, 2))
|
125 |
+
sorted_indices = np.argsort(areas)[::1]
|
126 |
+
annotation = annotation[sorted_indices]
|
127 |
+
|
128 |
+
index = (annotation != 0).argmax(axis=0)
|
129 |
+
if random_color:
|
130 |
+
color = np.random.random((mask_sum, 1, 1, 3))
|
131 |
+
else:
|
132 |
+
color = np.ones((mask_sum, 1, 1, 3)) * np.array([30 / 255, 144 / 255, 255 / 255])
|
133 |
+
transparency = np.ones((mask_sum, 1, 1, 1)) * 0.6
|
134 |
+
visual = np.concatenate([color, transparency], axis=-1)
|
135 |
+
mask_image = np.expand_dims(annotation, -1) * visual
|
136 |
+
|
137 |
+
mask = np.zeros((height, weight, 4))
|
138 |
+
|
139 |
+
h_indices, w_indices = np.meshgrid(np.arange(height), np.arange(weight), indexing='ij')
|
140 |
+
indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))
|
141 |
+
|
142 |
+
mask[h_indices, w_indices, :] = mask_image[indices]
|
143 |
+
if bbox is not None:
|
144 |
+
x1, y1, x2, y2 = bbox
|
145 |
+
ax.add_patch(plt.Rectangle((x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor='b', linewidth=1))
|
146 |
+
# ax.text(x, y, f"{label}: {round(prediction['score']*100, 1)}%", fontdict=fdic)
|
147 |
+
ax.text(x, y, f"{label}", fontdict=fdic)
|
148 |
+
|
149 |
+
if not retinamask:
|
150 |
+
mask = cv2.resize(mask, (target_width, target_height), interpolation=cv2.INTER_NEAREST)
|
151 |
+
|
152 |
+
return mask
|
153 |
+
|
154 |
+
|
155 |
+
def fast_show_mask_gpu(
|
156 |
+
annotation,
|
157 |
+
ax,
|
158 |
+
random_color=False,
|
159 |
+
bbox=None,
|
160 |
+
retinamask=True,
|
161 |
+
target_height=960,
|
162 |
+
target_width=960,
|
163 |
+
label = None,
|
164 |
+
):
|
165 |
+
device = annotation.device
|
166 |
+
mask_sum = annotation.shape[0]
|
167 |
+
height = annotation.shape[1]
|
168 |
+
weight = annotation.shape[2]
|
169 |
+
areas = torch.sum(annotation, dim=(1, 2))
|
170 |
+
sorted_indices = torch.argsort(areas, descending=False)
|
171 |
+
annotation = annotation[sorted_indices]
|
172 |
+
# 找每个位置第一个非零值下标
|
173 |
+
index = (annotation != 0).to(torch.long).argmax(dim=0)
|
174 |
+
if random_color:
|
175 |
+
color = torch.rand((mask_sum, 1, 1, 3)).to(device)
|
176 |
+
else:
|
177 |
+
color = torch.ones((mask_sum, 1, 1, 3)).to(device) * torch.tensor(
|
178 |
+
[30 / 255, 144 / 255, 255 / 255]
|
179 |
+
).to(device)
|
180 |
+
transparency = torch.ones((mask_sum, 1, 1, 1)).to(device) * 0.6
|
181 |
+
visual = torch.cat([color, transparency], dim=-1)
|
182 |
+
mask_image = torch.unsqueeze(annotation, -1) * visual
|
183 |
+
# 按index取数,index指每个位置选哪个batch的数,把mask_image转成一个batch的形式
|
184 |
+
mask = torch.zeros((height, weight, 4)).to(device)
|
185 |
+
h_indices, w_indices = torch.meshgrid(torch.arange(height), torch.arange(weight))
|
186 |
+
indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))
|
187 |
+
# 使用向量化索引更新show的值
|
188 |
+
mask[h_indices, w_indices, :] = mask_image[indices]
|
189 |
+
mask_cpu = mask.cpu().numpy()
|
190 |
+
if bbox is not None:
|
191 |
+
x1, y1, x2, y2 = bbox
|
192 |
+
ax.add_patch(
|
193 |
+
plt.Rectangle(
|
194 |
+
(x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor="b", linewidth=3
|
195 |
+
)
|
196 |
+
)
|
197 |
+
ax.text(x1, y1, f"{label}", fontdict=fdic)
|
198 |
+
# ax.text(x1, y1, f"{label}")
|
199 |
+
if not retinamask:
|
200 |
+
mask_cpu = cv2.resize(
|
201 |
+
mask_cpu, (target_width, target_height), interpolation=cv2.INTER_NEAREST
|
202 |
+
)
|
203 |
+
return mask_cpu, ax
|