File size: 79,341 Bytes
e8f2571 |
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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 |
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import os.path
from typing import Dict, List, Tuple, Optional
from torch import Tensor
from mmcv.cnn import Linear
from mmengine.model import bias_init_with_prob, constant_init
from mmengine.structures import InstanceData
from mmengine.model import BaseModule
from mmdet.registry import MODELS
from mmdet.structures import SampleList
from mmdet.structures.bbox import bbox_cxcywh_to_xyxy, bbox_xyxy_to_cxcywh, bbox_overlaps
from mmdet.utils import InstanceList, OptInstanceList, reduce_mean
from ..utils import multi_apply
from ..layers import inverse_sigmoid
from .detr_head import DETRHead
from mmdet.registry import MODELS, TASK_UTILS
from mmdet.utils import (ConfigType, InstanceList, OptInstanceList,OptConfigType,
OptMultiConfig, reduce_mean)
from mmcv.ops import nms, batched_nms
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Transformer
import scipy.io as sio
import os
from ..losses import QualityFocalLoss
# def adjust_bbox_to_pixel(bboxes: Tensor):
# # 向下取整得到目标的左上角坐标
# adjusted_bboxes = torch.floor(bboxes)
# # 向上取整得到目标的右下角坐标
# adjusted_bboxes[:, 2:] = torch.ceil(bboxes[:, 2:])
# return adjusted_bboxes
def adjust_bbox_to_pixel(bboxes: Tensor):
# 四舍五入取整坐标
adjusted_bboxes = torch.round(bboxes)
return adjusted_bboxes
@MODELS.register_module()
class EvloveDetHead(BaseModule):
r"""Head of the DINO: DETR with Improved DeNoising Anchor Boxes
for End-to-End Object Detection
Code is modified from the `official github repo
<https://github.com/IDEA-Research/DINO>`_.
More details can be found in the `paper
<https://arxiv.org/abs/2203.03605>`_ .
"""
def __init__(self,
num_classes: int,
embed_dims: int = 256,
decoder_embed_dims: int = 256,
num_reg_fcs: int = 2,
center_feat_indice: int=1,
sync_cls_avg_factor: bool = False,
use_nms: bool = False,
score_threshold: float = 0.0,
class_wise_nms: bool = True,
test_nms: OptConfigType = dict(type='nms', iou_threshold=0.01, ),
loss_cls: ConfigType = dict(
type='FocalLoss',
use_sigmoid=True,
gamma=2.0,
alpha=0.25,
loss_weight=1.0),
loss_center_cls: ConfigType = dict(
type='FocalLoss',
use_sigmoid=True,
gamma=2.0,
alpha=0.25,
loss_weight=1.0),
loss_bbox: ConfigType = dict(type='L1Loss', loss_weight=5.0),
loss_iou: OptConfigType = None,
loss_seg: ConfigType = dict(
type='FocalLoss',
use_sigmoid=True,
gamma=2.0,
alpha=0.25,
loss_weight=1.0),
# loss_seg: ConfigType = dict(type='L1Loss', loss_weight=1.0),
loss_abu: ConfigType = dict(type='L1Loss', loss_weight=1.0),
train_cfg: ConfigType = dict(
assigner=dict(
type='HungarianAssigner',
match_costs=[
dict(type='ClassificationCost', weight=1.),
dict(type='BBoxL1Cost', weight=5.0, box_format='xywh'),
dict(type='IoUCost', iou_mode='giou', weight=2.0)
])),
test_cfg: ConfigType = dict(max_per_img=100),
init_cfg: OptMultiConfig = None,
share_pred_layer: bool = False,
num_pred_layer: int = 6,
as_two_stage: bool = False,
pre_bboxes_round: bool = True,
neg_hard_num: int = 0,
seg_neg_hard_num: int = 0,
loss_center_th: float = 0.2,
loss_iou_th: float = 0.3,
center_ds_ratio: int = 1,
use_center: bool = True,
predict_segmentation: bool = False,
predict_abundance: bool = False,
save_path: Optional[str]= None,
mask_threshold:float = 0.5,
mask_extend_pixel: int = 2,
) -> None:
self.share_pred_layer = share_pred_layer
self.num_pred_layer = num_pred_layer
self.as_two_stage = as_two_stage
self.pre_bboxes_round = pre_bboxes_round
self.score_threshold = score_threshold
self.loss_center_th = loss_center_th
self.loss_iou_th = loss_iou_th
self.center_feat_indice = center_feat_indice
self.center_ds_ratio = center_ds_ratio
super().__init__(init_cfg=init_cfg)
self.bg_cls_weight = 0
self.sync_cls_avg_factor = sync_cls_avg_factor
class_weight = loss_cls.get('class_weight', None)
if class_weight is not None and (self.__class__ is DETRHead):
assert isinstance(class_weight, float), 'Expected ' \
'class_weight to have type float. Found ' \
f'{type(class_weight)}.'
# NOTE following the official DETR repo, bg_cls_weight means
# relative classification weight of the no-object class.
bg_cls_weight = loss_cls.get('bg_cls_weight', class_weight)
assert isinstance(bg_cls_weight, float), 'Expected ' \
'bg_cls_weight to have type float. Found ' \
f'{type(bg_cls_weight)}.'
class_weight = torch.ones(num_classes + 1) * class_weight
# set background class as the last indice
class_weight[num_classes] = bg_cls_weight
loss_cls.update({'class_weight': class_weight})
if 'bg_cls_weight' in loss_cls:
loss_cls.pop('bg_cls_weight')
self.bg_cls_weight = bg_cls_weight
if train_cfg:
assert 'assigner' in train_cfg, 'assigner should be provided ' \
'when train_cfg is set.'
assigner = train_cfg['assigner']
self.assigner = TASK_UTILS.build(assigner)
if train_cfg.get('sampler', None) is not None:
raise RuntimeError('DETR do not build sampler.')
# self.bbox_assigner = TASK_UTILS.build(bbox_assigner)
# self.dn_assigner = TASK_UTILS.build(dn_assigner)
self.num_classes = num_classes
self.embed_dims = embed_dims
self.num_reg_fcs = num_reg_fcs
self.train_cfg = train_cfg
self.test_cfg = test_cfg
self.loss_cls = MODELS.build(loss_cls)
self.loss_center_cls = MODELS.build(loss_center_cls)
self.loss_bbox = MODELS.build(loss_bbox)
if loss_iou is not None:
self.loss_iou = MODELS.build(loss_iou)
else:
self.loss_iou = None
self.loss_seg = MODELS.build(loss_seg)
self.loss_abu = MODELS.build(loss_abu)
self.use_nms = use_nms
self.class_wise_nms = class_wise_nms
self.score_threshold = score_threshold
self.test_nms = test_nms
if self.loss_cls.use_sigmoid:
self.cls_out_channels = num_classes
else:
self.cls_out_channels = num_classes + 1
self.neg_hard_num = neg_hard_num
self.seg_neg_hard_num = neg_hard_num
self.use_center = use_center
self.decoder_embed_dims = decoder_embed_dims
self.predict_segmentation = predict_segmentation
self.predict_abundance = predict_abundance
self.save_path = save_path
if self.save_path is not None:
os.makedirs(self.save_path,exist_ok=True)
self.mask_threshold = mask_threshold
self.mask_extend_pixel = mask_extend_pixel
self._init_layers()
def _init_layers(self) -> None:
"""Initialize classification branch and regression branch of head."""
# fc_cls = Linear(self.embed_dims, self.cls_out_channels)
fc_cls = []
for _ in range(2):
fc_cls.append(Linear(self.embed_dims, self.embed_dims))
fc_cls.append(Linear(self.embed_dims, self.cls_out_channels))
fc_cls = nn.Sequential(*fc_cls)
self.cls_branch = fc_cls
if self.predict_segmentation:
fc_cls = []
for _ in range(2):
fc_cls.append(Linear(self.embed_dims, self.embed_dims))
fc_cls.append(Linear(self.embed_dims, 1))
fc_cls = nn.Sequential(*fc_cls)
self.seg_branch = fc_cls
if self.predict_abundance:
fc_cls = []
for _ in range(2):
fc_cls.append(Linear(self.embed_dims, self.embed_dims))
fc_cls.append(Linear(self.embed_dims, 1))
fc_cls = nn.Sequential(*fc_cls)
self.abu_branch = fc_cls
reg_branch = []
ratio=2
reg_branch.append(Linear(self.decoder_embed_dims, self.decoder_embed_dims*ratio))
reg_branch.append(nn.ReLU())
for _ in range(self.num_reg_fcs-1):
reg_branch.append(Linear(self.decoder_embed_dims*ratio, self.decoder_embed_dims*ratio))
reg_branch.append(nn.ReLU())
reg_branch.append(Linear(self.decoder_embed_dims*ratio, 4))
reg_branch = nn.Sequential(*reg_branch)
if self.share_pred_layer:
self.reg_branches = nn.ModuleList(
[reg_branch for _ in range(self.num_pred_layer)])
else:
self.reg_branches = nn.ModuleList([
copy.deepcopy(reg_branch) for _ in range(self.num_pred_layer)
])
if self.use_center:
center_cls = []
for _ in range(2):
center_cls.append(Linear(self.embed_dims, self.embed_dims))
center_cls.append(Linear(self.embed_dims, 1))
center_cls = nn.Sequential(*center_cls)
self.center_branch = center_cls
def init_weights(self) -> None:
"""Initialize weights of the Deformable DETR head."""
if self.loss_cls.use_sigmoid:
bias_init = bias_init_with_prob(0.01)
# for m in self.cls_branches:
nn.init.constant_(self.cls_branch.bias, bias_init)
if self.use_center:
nn.init.constant_(self.center_branch.bias, bias_init)
if self.predict_segmentation:
nn.init.constant_(self.seg_branch.bias, bias_init)
if self.predict_abundance:
nn.init.constant_(self.abu_branch.bias, bias_init)
for m in self.reg_branches:
constant_init(m[-1], 0, bias=0)
nn.init.constant_(m[-1].bias.data[2:], 0.0)
nn.init.constant_(self.reg_branches[0][-1].bias.data[2:], -2.0)
# def _get_targets_single(self, cls_score: Tensor, bbox_pred: Tensor,
# gt_instances: InstanceData,
# img_meta: dict,
# with_neg_cls:bool=True,
# assigner_type:str = None) -> tuple:
# """Compute regression and classification targets for one image.
#
# Outputs from a single decoder layer of a single feature level are used.
#
# Args:
# cls_score (Tensor): Box score logits from a single decoder layer
# for one image. Shape [num_queries, cls_out_channels].
# bbox_pred (Tensor): Sigmoid outputs from a single decoder layer
# for one image, with normalized coordinate (cx, cy, w, h) and
# shape [num_queries, 4].
# gt_instances (:obj:`InstanceData`): Ground truth of instance
# annotations. It should includes ``bboxes`` and ``labels``
# attributes.
# img_meta (dict): Meta information for one image.
#
# Returns:
# tuple[Tensor]: a tuple containing the following for one image.
#
# - labels (Tensor): Labels of each image.
# - label_weights (Tensor]): Label weights of each image.
# - bbox_targets (Tensor): BBox targets of each image.
# - bbox_weights (Tensor): BBox weights of each image.
# - pos_inds (Tensor): Sampled positive indices for each image.
# - neg_inds (Tensor): Sampled negative indices for each image.
# """
# img_h, img_w = img_meta['img_shape']
# factor = bbox_pred.new_tensor([img_w, img_h, img_w,
# img_h]).unsqueeze(0)
# num_bboxes = bbox_pred.size(0)
# # convert bbox_pred from xywh, normalized to xyxy, unnormalized
# bbox_pred = bbox_cxcywh_to_xyxy(bbox_pred)
# bbox_pred = bbox_pred * factor
#
# pred_instances = InstanceData(scores=cls_score, bboxes=bbox_pred,priors=bbox_pred)
# # assigner and sampler
# if assigner_type == 'dn':
# assign_result = self.dn_assigner.assign(
# pred_instances=pred_instances,
# gt_instances=gt_instances,
# img_meta=img_meta)
# else:
# assign_result = self.assigner.assign(
# pred_instances=pred_instances,
# gt_instances=gt_instances,
# img_meta=img_meta)
#
# gt_bboxes = gt_instances.bboxes
# gt_labels = gt_instances.labels
# pos_inds = torch.nonzero(
# assign_result.gt_inds > 0, as_tuple=False).squeeze(-1).unique()
# neg_inds = torch.nonzero(
# assign_result.gt_inds == 0, as_tuple=False).squeeze(-1).unique()
# pos_assigned_gt_inds = assign_result.gt_inds[pos_inds] - 1
# pos_gt_bboxes = gt_bboxes[pos_assigned_gt_inds.long(), :]
# # label targets
# labels = gt_bboxes.new_full((num_bboxes,),
# self.num_classes,
# dtype=torch.long)
# labels[pos_inds] = gt_labels[pos_assigned_gt_inds]
# label_weights = gt_bboxes.new_zeros(num_bboxes)
# label_weights[pos_inds] = 1
# label_weights[neg_inds] = 1
# if not with_neg_cls:
# label_weights[neg_inds] = 0
# # bbox targets
# bbox_targets = torch.zeros_like(bbox_pred)
# bbox_weights = torch.zeros_like(bbox_pred)
# bbox_weights[pos_inds] = 1.0
# # DETR regress the relative position of boxes (cxcywh) in the image.
# # Thus the learning target should be normalized by the image size, also
# # the box format should be converted from defaultly x1y1x2y2 to cxcywh.
# pos_gt_bboxes_normalized = pos_gt_bboxes / factor
# pos_gt_bboxes_targets = bbox_xyxy_to_cxcywh(pos_gt_bboxes_normalized)
# bbox_targets[pos_inds] = pos_gt_bboxes_targets
# return (labels, label_weights, bbox_targets, bbox_weights, pos_inds,
# neg_inds)
def _get_targets_single_center(self,
center: Tensor,
center_scores: Tensor,
cls_scores: Tensor,
spatial_shapes: Tensor,
gt_instances: InstanceData,
img_meta: dict) -> tuple:
"""Compute regression and classification targets for one image.
Outputs from a single decoder layer of a single feature level are used.
Args:
cls_score (Tensor): Box score logits from a single decoder layer
for one image. Shape [num_queries, cls_out_channels].
bbox_pred (Tensor): Sigmoid outputs from a single decoder layer
for one image, with normalized coordinate (cx, cy, w, h) and
shape [num_queries, 4].
gt_instances (:obj:`InstanceData`): Ground truth of instance
annotations. It should includes ``bboxes`` and ``labels``
attributes.
img_meta (dict): Meta information for one image.
Returns:
tuple[Tensor]: a tuple containing the following for one image.
- labels (Tensor): Labels of each image.
- label_weights (Tensor]): Label weights of each image.
- bbox_targets (Tensor): BBox targets of each image.
- bbox_weights (Tensor): BBox weights of each image.
- pos_inds (Tensor): Sampled positive indices for each image.
- neg_inds (Tensor): Sampled negative indices for each image.
"""
img_h, img_w = img_meta['img_shape']
feat_h = int(spatial_shapes[self.center_feat_indice][0]/self.center_ds_ratio)
feat_w = int(spatial_shapes[self.center_feat_indice][1]/self.center_ds_ratio)
factor = spatial_shapes.new_tensor([feat_w, feat_h]).unsqueeze(0)
# factor = center.new_tensor([img_w, img_h,]).unsqueeze(0)
gt_bboxes = gt_instances.bboxes
gt_labels = gt_instances.labels
gt_cxcy = bbox_xyxy_to_cxcywh(gt_bboxes)[:, :2]
gt_cxcy[:, 0] = gt_cxcy[:, 0] * feat_w / img_w
gt_cxcy[:, 1] = gt_cxcy[:, 1] * feat_h / img_h
gt_cxcy= gt_cxcy.long()
gt_bboxes[:, 2:] -= 0.1
gt_bboxes_x = gt_bboxes[:, 0::2]
gt_bboxes_y = gt_bboxes[:, 1::2]
gt_bboxes_x = torch.floor(gt_bboxes_x * feat_w / img_w)
gt_bboxes_y = torch.floor(gt_bboxes_y * feat_h / img_h)
gt_bboxes_x = gt_bboxes_x.long()
gt_bboxes_y = gt_bboxes_y.long()
heat_map = gt_bboxes.new_full((feat_h, feat_w), 0, dtype=torch.long)
for t_i in range(gt_bboxes.size(0)):
# if gt_bboxes_x[t_i, 1] - gt_bboxes_x[t_i, 0] > 3:
# gt_bboxes_x[t_i,1] = gt_cxcy[t_i, 0] + 1
# gt_bboxes_x[t_i,0] = gt_cxcy[t_i, 0] - 1
# if gt_bboxes_y[t_i,1] - gt_bboxes_y[t_i,0] > 3:
# gt_bboxes_y[t_i,1] = gt_cxcy[t_i, 1] + 1
# gt_bboxes_y[t_i,0] = gt_cxcy[t_i, 1] - 1
grid_y, grid_x = torch.meshgrid(
torch.linspace(gt_bboxes_y[t_i, 0], gt_bboxes_y[t_i, 1], gt_bboxes_y[t_i, 1]+1-gt_bboxes_y[t_i, 0],
dtype=torch.long, device=gt_cxcy.device),
torch.linspace(gt_bboxes_x[t_i, 0], gt_bboxes_x[t_i, 1], gt_bboxes_x[t_i, 1]+1-gt_bboxes_x[t_i, 0],
dtype=torch.long, device=gt_cxcy.device))
grid = torch.cat([grid_y.unsqueeze(-1), grid_x.unsqueeze(-1)], -1)
grid = grid.view(-1, 2)
value_input = gt_bboxes.new_full((grid.size(0),), -1, dtype=torch.long)
heat_map.index_put_((grid[:,0],grid[:,1]), value_input)
# cls_labels.index_put_((grid[:,0],grid[:,1]), value_input)
value_input = gt_bboxes.new_full((gt_cxcy.size(0),), 1, dtype=torch.long)
heat_map = heat_map.index_put_((gt_cxcy[:,1], gt_cxcy[:,0]), value_input)
heat_map = heat_map.view(-1)
mask = heat_map != -1
# new_center_score = center_score[mask]
# heat_map = heat_map[mask]
pos_inds = torch.where(heat_map == 1)[0]
ignore_inds = torch.where(heat_map == -1)[0]
neg_inds = torch.where(heat_map == 0)[0]
cls_labels = gt_bboxes.new_full((feat_h, feat_w), self.num_classes, dtype=torch.long)
cls_labels = cls_labels.index_put_((gt_cxcy[:,1], gt_cxcy[:,0]), gt_labels)
cls_labels = cls_labels.view(-1)
center_labels = gt_bboxes.new_full((heat_map.size(0),), 1, dtype=torch.long)
center_labels[pos_inds] = 0
label_weights = gt_bboxes.new_ones(heat_map.size(0))
if ignore_inds.numel() > 0:
label_weights[ignore_inds] = 0
if self.neg_hard_num>0:
if self.use_center:
_, indices = torch.sort(center_scores, dim=0, descending=True)
else:
cls_scores_max = torch.max(cls_scores, dim=-1, keepdim=True)[0]
_, indices = torch.sort(cls_scores_max, dim=0, descending=True)
sorted_inds = indices.squeeze()
non_neg_inds = torch.cat([pos_inds,ignore_inds],dim=0)
mask = torch.isin(sorted_inds, non_neg_inds)
remaining_inds = sorted_inds[~mask]
neg_hard_inds = remaining_inds[:self.neg_hard_num]
new_inds = torch.cat([pos_inds, neg_hard_inds], dim=0)
neg_inds = neg_hard_inds
center_labels = center_labels[new_inds]
cls_labels = cls_labels[new_inds]
center_scores = center_scores[new_inds]
cls_scores = cls_scores[new_inds]
label_weights = gt_bboxes.new_ones(new_inds.size(0))
return (center_labels, cls_labels, center_scores, cls_scores, label_weights, pos_inds, neg_inds)
def _get_targets_single_pixel(self,
seg_scores: Tensor,
abu_scores: Optional[Tensor],
spatial_shapes: Tensor,
gt_seg: Tensor,
gt_abu: Optional[Tensor],
img_meta: dict) -> tuple:
assert seg_scores.shape[0] == gt_seg.numel()
assert spatial_shapes[0][0]*spatial_shapes[0][1] == gt_seg.numel()
gt_seg = gt_seg.view(-1,1)
pos_inds = torch.where(gt_seg >0)[0]
seg_labels = gt_seg.detach().clone()
seg_labels[gt_seg >0] = 0
seg_labels[gt_seg == 0] = 1
seg_labels = seg_labels.long()
# gt_abu= gt_abu.view(-1,1)
# pos_inds = torch.where(gt_abu > 0)[0]
if self.seg_neg_hard_num== 0:
neg_inds = torch.where(gt_seg == 0)[0]
seg_label_weights = seg_scores.new_ones(seg_labels.size(0))
else:
seg_scores_max = torch.max(seg_scores, dim=-1, keepdim=True)[0]
_, indices = torch.sort(seg_scores_max, dim=0, descending=True)
sorted_inds = indices.squeeze()
mask = torch.isin(sorted_inds, pos_inds)
remaining_inds = sorted_inds[~mask]
neg_hard_inds = remaining_inds[:self.seg_neg_hard_num]
neg_inds = neg_hard_inds
new_inds = torch.cat([pos_inds, neg_hard_inds], dim=0)
seg_scores = seg_scores[new_inds]
seg_labels = seg_labels[new_inds]
seg_label_weights = seg_scores.new_ones(seg_labels.size(0))
if self.predict_abundance:
gt_abu = gt_abu.view(-1,1)
abu_scores = abu_scores[pos_inds]
abu_labels = gt_abu[pos_inds]*0.5+0.25
abu_label_weights = seg_scores.new_ones(abu_labels.size(0))
else:
abu_scores = None
abu_labels = None
abu_label_weights = None
return seg_scores, seg_labels, seg_label_weights,abu_scores, abu_labels, abu_label_weights, pos_inds, neg_inds
# def _get_targets_single_bbox(self,
# cls_score: Tensor,
# bbox_pred: Tensor,
# gt_instances: InstanceData,
# img_meta: dict) -> tuple:
# """Compute regression and classification targets for one image.
#
# Outputs from a single decoder layer of a single feature level are used.
#
# Args:
# cls_score (Tensor): Box score logits from a single decoder layer
# for one image. Shape [num_queries, cls_out_channels].
# bbox_pred (Tensor): Sigmoid outputs from a single decoder layer
# for one image, with normalized coordinate (cx, cy, w, h) and
# shape [num_queries, 4].
# gt_instances (:obj:`InstanceData`): Ground truth of instance
# annotations. It should includes ``bboxes`` and ``labels``
# attributes.
# img_meta (dict): Meta information for one image.
#
# Returns:
# tuple[Tensor]: a tuple containing the following for one image.
#
# - labels (Tensor): Labels of each image.
# - label_weights (Tensor]): Label weights of each image.
# - bbox_targets (Tensor): BBox targets of each image.
# - bbox_weights (Tensor): BBox weights of each image.
# - pos_inds (Tensor): Sampled positive indices for each image.
# - neg_inds (Tensor): Sampled negative indices for each image.
# """
# img_h, img_w = img_meta['img_shape']
# factor = bbox_pred.new_tensor([img_w, img_h, img_w,
# img_h]).unsqueeze(0)
# num_bboxes = bbox_pred.size(0)
# # convert bbox_pred from xywh, normalized to xyxy, unnormalized
# bbox_pred = bbox_cxcywh_to_xyxy(bbox_pred)
# bbox_pred = bbox_pred * factor
#
# pred_instances = InstanceData(scores=cls_score, bboxes=bbox_pred,priors=bbox_pred)
# # assigner and sampler
# assign_result = self.bbox_assigner.assign(
# pred_instances=pred_instances,
# gt_instances=gt_instances,
# img_meta=img_meta)
# gt_bboxes = gt_instances.bboxes
# gt_labels = gt_instances.labels
# pos_inds = torch.nonzero(
# assign_result.gt_inds > 0, as_tuple=False).squeeze(-1).unique()
# neg_inds = torch.nonzero(
# assign_result.gt_inds == 0, as_tuple=False).squeeze(-1).unique()
# pos_assigned_gt_inds = assign_result.gt_inds[pos_inds] - 1
# pos_gt_bboxes = gt_bboxes[pos_assigned_gt_inds.long(), :]
#
# # bbox targets
# bbox_targets = torch.zeros_like(bbox_pred)
# bbox_weights = torch.zeros_like(bbox_pred)
# bbox_weights[pos_inds] = 1.0
#
# # DETR regress the relative position of boxes (cxcywh) in the image.
# # Thus the learning target should be normalized by the image size, also
# # the box format should be converted from defaultly x1y1x2y2 to cxcywh.
# pos_gt_bboxes_normalized = pos_gt_bboxes / factor
# pos_gt_bboxes_targets = bbox_xyxy_to_cxcywh(pos_gt_bboxes_normalized)
# bbox_targets[pos_inds] = pos_gt_bboxes_targets
# return (bbox_targets, bbox_weights, pos_inds, neg_inds)
def loss_and_predict(
self, hidden_states: Tuple[Tensor],
batch_data_samples: SampleList) -> Tuple[dict, InstanceList]:
"""Perform forward propagation of the head, then calculate loss and
predictions from the features and data samples. Over-write because
img_metas are needed as inputs for bbox_head.
Args:
hidden_states (tuple[Tensor]): Feature from the transformer
decoder, has shape (num_decoder_layers, bs, num_queries, dim).
batch_data_samples (list[:obj:`DetDataSample`]): Each item contains
the meta information of each image and corresponding
annotations.
Returns:
tuple: the return value is a tuple contains:
- losses: (dict[str, Tensor]): A dictionary of loss components.
- predictions (list[:obj:`InstanceData`]): Detection
results of each image after the post process.
"""
batch_gt_instances = []
batch_img_metas = []
for data_sample in batch_data_samples:
batch_img_metas.append(data_sample.metainfo)
batch_gt_instances.append(data_sample.gt_instances)
outs = self(hidden_states)
loss_inputs = outs + (batch_gt_instances, batch_img_metas)
losses = self.loss_by_feat(*loss_inputs)
predictions = self.predict_by_feat(
*outs, batch_img_metas=batch_img_metas)
return losses, predictions
def forward(self, hidden_states: Tensor,
references: List[Tensor],
topk_cls_scores: Tensor,) -> Tuple[Tensor]:
"""Forward function.
Args:
hidden_states (Tensor): Hidden states output from each decoder
layer, has shape (num_decoder_layers, bs, num_queries, dim).
references (list[Tensor]): List of the reference from the decoder.
The first reference is the `init_reference` (initial) and the
other num_decoder_layers(6) references are `inter_references`
(intermediate). The `init_reference` has shape (bs,
num_queries, 4) when `as_two_stage` of the detector is `True`,
otherwise (bs, num_queries, 2). Each `inter_reference` has
shape (bs, num_queries, 4) when `with_box_refine` of the
detector is `True`, otherwise (bs, num_queries, 2). The
coordinates are arranged as (cx, cy) when the last dimension is
2, and (cx, cy, w, h) when it is 4.
Returns:
tuple[Tensor]: results of head containing the following tensor.
- all_layers_outputs_classes (Tensor): Outputs from the
classification head, has shape (num_decoder_layers, bs,
num_queries, cls_out_channels).
- all_layers_outputs_coords (Tensor): Sigmoid outputs from the
regression head with normalized coordinate format (cx, cy, w,
h), has shape (num_decoder_layers, bs, num_queries, 4) with the
last dimension arranged as (cx, cy, w, h).
"""
all_layers_outputs_coords = []
for layer_id in range(hidden_states.shape[0]):
reference = inverse_sigmoid(references[layer_id])
# NOTE The last reference will not be used.
hidden_state = hidden_states[layer_id]
tmp_reg_preds = self.reg_branches[layer_id](hidden_state)
if reference.shape[-1] == 4:
# When `layer` is 0 and `as_two_stage` of the detector
# is `True`, or when `layer` is greater than 0 and
# `with_box_refine` of the detector is `True`.
tmp_reg_preds += reference
else:
# When `layer` is 0 and `as_two_stage` of the detector
# is `False`, or when `layer` is greater than 0 and
# `with_box_refine` of the detector is `False`.
assert reference.shape[-1] == 2
tmp_reg_preds[..., :2] += reference
outputs_coord = tmp_reg_preds.sigmoid()
all_layers_outputs_coords.append(outputs_coord)
all_layers_outputs_classes = topk_cls_scores.unsqueeze(0).repeat(hidden_states.shape[0],1,1,1)
all_layers_outputs_coords = torch.stack(all_layers_outputs_coords)
return all_layers_outputs_classes, all_layers_outputs_coords
def loss(self, hidden_states: Tensor,
references: List[Tensor],
centers: Tensor,
center_scores: Tensor,
topk_centers_scores: Tensor,
cls_scores: Tensor,
topk_cls_scores: Tensor,
seg_scores:Optional[Tensor],
abu_scores: Optional[Tensor],
batch_data_samples: SampleList,
dn_meta: Dict[str, int],
spatial_shapes: Tensor) -> dict:
"""Perform forward propagation and loss calculation of the detection
head on the queries of the upstream network.
Args:
hidden_states (Tensor): Hidden states output from each decoder
layer, has shape (num_decoder_layers, bs, num_queries_total,
dim), where `num_queries_total` is the sum of
`num_denoising_queries` and `num_matching_queries` when
`self.training` is `True`, else `num_matching_queries`.
references (list[Tensor]): List of the reference from the decoder.
The first reference is the `init_reference` (initial) and the
other num_decoder_layers(6) references are `inter_references`
(intermediate). The `init_reference` has shape (bs,
num_queries_total, 4) and each `inter_reference` has shape
(bs, num_queries, 4) with the last dimension arranged as
(cx, cy, w, h).
enc_outputs_class (Tensor): The score of each point on encode
feature map, has shape (bs, num_feat_points, cls_out_channels).
enc_outputs_coord (Tensor): The proposal generate from the
encode feature map, has shape (bs, num_feat_points, 4) with the
last dimension arranged as (cx, cy, w, h).
batch_data_samples (list[:obj:`DetDataSample`]): The Data
Samples. It usually includes information such as
`gt_instance`, `gt_panoptic_seg` and `gt_sem_seg`.
dn_meta (Dict[str, int]): The dictionary saves information about
group collation, including 'num_denoising_queries' and
'num_denoising_groups'. It will be used for split outputs of
denoising and matching parts and loss calculation.
Returns:
dict: A dictionary of loss components.
"""
batch_gt_instances = []
batch_img_metas = []
batch_gt_seg = []
batch_gt_abu = []
for data_sample in batch_data_samples:
batch_img_metas.append(data_sample.metainfo)
batch_gt_instances.append(data_sample.gt_instances)
if self.predict_segmentation:
batch_gt_seg.append(data_sample.gt_pixel.seg)
else:
batch_gt_seg.append(None)
if self.predict_abundance:
batch_gt_abu.append(data_sample.gt_pixel.abu)
else:
batch_gt_abu.append(None)
outs = self(hidden_states, references, topk_cls_scores)
loss_inputs = outs + (centers, center_scores, topk_centers_scores, cls_scores, topk_cls_scores,
seg_scores,abu_scores,
batch_gt_instances, batch_img_metas, dn_meta, spatial_shapes,batch_gt_seg,batch_gt_abu)
losses = self.loss_by_feat(*loss_inputs)
return losses
def loss_by_feat(
self,
all_layers_cls_scores: Tensor,
all_layers_bbox_preds: Tensor,
centers: Tensor,
center_scores: Tensor,
topk_centers_scores: Tensor,
cls_scores: Tensor,
topk_cls_scores: Tensor,
seg_scores: Optional[Tensor],
abu_scores: Optional[Tensor],
batch_gt_instances: InstanceList,
batch_img_metas: List[dict],
dn_meta: Dict[str, int],
spatial_shapes: Tensor,
batch_gt_seg: List,
batch_gt_abu: List,
batch_gt_instances_ignore: OptInstanceList = None,
) -> Dict[str, Tensor]:
"""Loss function.
Args:
all_layers_cls_scores (Tensor): Classification scores of all
decoder layers, has shape (num_decoder_layers, bs,
num_queries_total, cls_out_channels), where
`num_queries_total` is the sum of `num_denoising_queries`
and `num_matching_queries`.
all_layers_bbox_preds (Tensor): Regression outputs of all decoder
layers. Each is a 4D-tensor with normalized coordinate format
(cx, cy, w, h) and has shape (num_decoder_layers, bs,
num_queries_total, 4).
enc_cls_scores (Tensor): The score of each point on encode
feature map, has shape (bs, num_feat_points, cls_out_channels).
enc_bbox_preds (Tensor): The proposal generate from the encode
feature map, has shape (bs, num_feat_points, 4) with the last
dimension arranged as (cx, cy, w, h).
batch_gt_instances (list[:obj:`InstanceData`]): Batch of
gt_instance. It usually includes ``bboxes`` and ``labels``
attributes.
batch_img_metas (list[dict]): Meta information of each image, e.g.,
image size, scaling factor, etc.
dn_meta (Dict[str, int]): The dictionary saves information about
group collation, including 'num_denoising_queries' and
'num_denoising_groups'. It will be used for split outputs of
denoising and matching parts and loss calculation.
batch_gt_instances_ignore (list[:obj:`InstanceData`], optional):
Batch of gt_instances_ignore. It includes ``bboxes`` attribute
data that is ignored during training and testing.
Defaults to None.
Returns:
dict[str, Tensor]: A dictionary of loss components.
"""
# extract denoising and matching part of outputs
weight_bbox = 0
weight_cls = 0
# (all_layers_matching_cls_scores, all_layers_matching_bbox_preds,
# all_layers_denoising_cls_scores, all_layers_denoising_bbox_preds) = \
# self.split_outputs(all_layers_cls_scores, all_layers_bbox_preds, dn_meta)
# (matching_cls_scores, all_layers_matching_bbox_preds,
# denoising_cls_scores, all_layers_denoising_bbox_preds) = \
# self.split_outputsv1(cls_scores, all_layers_bbox_preds, dn_meta)
loss_dict = dict()
loss_center, loss_cls = self.loss_center(centers,
center_scores,
cls_scores,
spatial_shapes,
batch_gt_instances=batch_gt_instances,
batch_img_metas=batch_img_metas)
if self.use_center:
loss_dict['loss_center'] = loss_center
loss_dict['loss_cls'] = loss_cls
if loss_cls <= self.loss_center_th:
weight_bbox = 1
if self.predict_segmentation:
# seg_scores = seg_scores.sigmoid()
if self.predict_abundance:
abu_scores = abu_scores.sigmoid()
loss_seg, loss_abu = self.loss_pixel(seg_scores, abu_scores, spatial_shapes,
batch_gt_seg,batch_gt_abu,
batch_img_metas=batch_img_metas)
loss_dict['loss_seg'] = loss_seg*weight_bbox
if self.predict_abundance:
loss_dict['loss_abu'] = loss_abu*weight_bbox
reg_targets = self.get_dn_targets(batch_gt_instances, batch_img_metas, dn_meta)
dn_losses_bbox, dn_losses_iou = multi_apply(
self._loss_dn_single,
all_layers_bbox_preds,
reg_targets=reg_targets,
batch_gt_instances=batch_gt_instances,
batch_img_metas=batch_img_metas,
dn_meta=dn_meta)
for num_dec_layer, (loss_bbox_i, loss_iou_i) in \
enumerate(zip(dn_losses_bbox, dn_losses_iou)):
loss_dict[f'd{num_dec_layer+1}.dn_loss_bbox'] = loss_bbox_i*weight_bbox
if self.loss_iou is not None:
loss_dict[f'd{num_dec_layer+1}.dn_loss_iou'] = loss_iou_i*weight_bbox
return loss_dict
# def loss_by_feat_single(self, cls_scores: Tensor, bbox_preds: Tensor,
# batch_gt_instances: InstanceList,
# batch_img_metas: List[dict]) -> Tuple[Tensor]:
# """Loss function for outputs from a single decoder layer of a single
# feature level.
#
# Args:
# cls_scores (Tensor): Box score logits from a single decoder layer
# for all images, has shape (bs, num_queries, cls_out_channels).
# bbox_preds (Tensor): Sigmoid outputs from a single decoder layer
# for all images, with normalized coordinate (cx, cy, w, h) and
# shape (bs, num_queries, 4).
# batch_gt_instances (list[:obj:`InstanceData`]): Batch of
# gt_instance. It usually includes ``bboxes`` and ``labels``
# attributes.
# batch_img_metas (list[dict]): Meta information of each image, e.g.,
# image size, scaling factor, etc.
#
# Returns:
# Tuple[Tensor]: A tuple including `loss_cls`, `loss_box` and
# `loss_iou`.
# """
# num_imgs = cls_scores.size(0)
# cls_scores_list = [cls_scores[i] for i in range(num_imgs)]
# bbox_preds_list = [bbox_preds[i] for i in range(num_imgs)]
# cls_reg_targets = self.get_targets_bbox(cls_scores_list, bbox_preds_list,
# batch_gt_instances, batch_img_metas)
# (bbox_targets_list, bbox_weights_list,
# num_total_pos, num_total_neg) = cls_reg_targets
# bbox_targets = torch.cat(bbox_targets_list, 0)
# bbox_weights = torch.cat(bbox_weights_list, 0)
#
#
# # Compute the average number of gt boxes across all gpus, for
# # normalization purposes
# num_total_pos = bbox_targets.new_tensor([num_total_pos])
# num_total_pos = torch.clamp(reduce_mean(num_total_pos), min=1).item()
#
# # construct factors used for rescale bboxes
# factors = []
# for img_meta, bbox_pred in zip(batch_img_metas, bbox_preds):
# img_h, img_w, = img_meta['img_shape']
# factor = bbox_pred.new_tensor([img_w, img_h, img_w,
# img_h]).unsqueeze(0).repeat(
# bbox_pred.size(0), 1)
# factors.append(factor)
# factors = torch.cat(factors, 0)
#
# # DETR regress the relative position of boxes (cxcywh) in the image,
# # thus the learning target is normalized by the image size. So here
# # we need to re-scale them for calculating IoU loss
# bbox_preds = bbox_preds.reshape(-1, 4)
# bboxes = bbox_cxcywh_to_xyxy(bbox_preds) * factors
# bboxes_gt = bbox_cxcywh_to_xyxy(bbox_targets) * factors
#
# # regression IoU loss, defaultly GIoU loss
# loss_iou = self.loss_iou(
# bboxes, bboxes_gt, bbox_weights, avg_factor=num_total_pos)
#
# # regression L1 loss
# loss_bbox = self.loss_bbox(
# bbox_preds, bbox_targets, bbox_weights, avg_factor=num_total_pos)
# return loss_bbox, loss_iou
def loss_center(self,
centers: Tensor,
center_scores: Tensor,
cls_scores: Tensor,
spatial_shapes: Tensor,
batch_gt_instances: InstanceList,
batch_img_metas: List[dict]) -> Tuple[Tensor]:
"""Loss function for outputs from a single decoder layer of a single
feature level.
Args:
cls_scores (Tensor): Box score logits from a single decoder layer
for all images, has shape (bs, num_queries, cls_out_channels).
bbox_preds (Tensor): Sigmoid outputs from a single decoder layer
for all images, with normalized coordinate (cx, cy, w, h) and
shape (bs, num_queries, 4).
batch_gt_instances (list[:obj:`InstanceData`]): Batch of
gt_instance. It usually includes ``bboxes`` and ``labels``
attributes.
batch_img_metas (list[dict]): Meta information of each image, e.g.,
image size, scaling factor, etc.
Returns:
Tuple[Tensor]: A tuple including `loss_cls`, `loss_box` and
`loss_iou`.
"""
num_imgs = centers.size(0)
if center_scores is None:
center_scores_list = [cls_scores[i] for i in range(num_imgs)]
else:
center_scores_list = [center_scores[i] for i in range(num_imgs)]
cls_scores_list = [cls_scores[i] for i in range(num_imgs)]
# center_scores =center_scores.view(-1, center_scores.shape[2])
# cls_scores = cls_scores.view(-1, cls_scores.shape[2])
centers_list = [centers[i] for i in range(num_imgs)]
spatial_shapes_list = [spatial_shapes for i in range(num_imgs)]
(center_labels_list, cls_labels_list, center_scores_list, cls_scores_list, label_weights_list, pos_inds_list, neg_inds_list,) = multi_apply(self._get_targets_single_center,
centers_list, center_scores_list, cls_scores_list, spatial_shapes_list, batch_gt_instances, batch_img_metas)
num_total_pos = sum((inds.numel() for inds in pos_inds_list))
num_total_neg = sum((inds.numel() for inds in neg_inds_list))
center_labels = torch.cat(center_labels_list, 0)
cls_labels = torch.cat(cls_labels_list, 0)
center_scores = torch.cat(center_scores_list, 0)
cls_scores = torch.cat(cls_scores_list, 0)
label_weights = torch.cat(label_weights_list, 0)
# construct weighted avg_factor to match with the official DETR repo
cls_avg_factor = num_total_pos * 1.0 + \
num_total_neg * 0
if self.sync_cls_avg_factor:
cls_avg_factor = reduce_mean(
centers.new_tensor([cls_avg_factor]))
cls_avg_factor = max(cls_avg_factor, 1)
if self.use_center:
loss_center = self.loss_center_cls(
center_scores, center_labels, label_weights, avg_factor=cls_avg_factor)
else:
loss_center = None
loss_cls = self.loss_cls(
cls_scores, cls_labels, label_weights, avg_factor=cls_avg_factor)
return loss_center, loss_cls
def loss_pixel(self,
seg_scores: Tensor,
abu_scores: Tensor,
spatial_shapes: Tensor,
batch_gt_seg: List,
batch_gt_abu: List,
batch_img_metas: List) -> Tuple[Tensor]:
num_imgs = seg_scores.size(0)
seg_scores_list = [seg_scores[i] for i in range(num_imgs)]
if abu_scores is not None:
abu_scores_list = [abu_scores[i] for i in range(num_imgs)]
else:
abu_scores_list = [None for i in range(num_imgs)]
spatial_shapes_list = [spatial_shapes for i in range(num_imgs)]
(seg_scores_list, seg_labels_list, seg_label_weights_list,abu_scores_list, abu_labels_list, abu_label_weights_list, pos_inds_list, neg_inds_list) = multi_apply(self._get_targets_single_pixel,
seg_scores_list, abu_scores_list,
spatial_shapes_list,
batch_gt_seg,
batch_gt_abu,
batch_img_metas)
num_total_pos = sum((inds.numel() for inds in pos_inds_list))
num_total_neg = sum((inds.numel() for inds in neg_inds_list))
seg_scores = torch.cat(seg_scores_list, 0)
seg_labels = torch.cat(seg_labels_list, 0)
seg_label_weights = torch.cat(seg_label_weights_list, 0)
cls_avg_factor = num_total_pos * 1.0 + num_total_neg * 0
if self.sync_cls_avg_factor:
cls_avg_factor = reduce_mean(
seg_scores.new_tensor([cls_avg_factor]))
cls_avg_factor = max(cls_avg_factor, 1)
loss_seg = self.loss_seg(
seg_scores, seg_labels, seg_label_weights, avg_factor=cls_avg_factor)
if self.predict_abundance:
abu_scores = torch.cat(abu_scores_list, 0)
abu_labels = torch.cat(abu_labels_list, 0)
abu_label_weights = torch.cat(abu_label_weights_list, 0)
# cls_avg_factor = num_total_pos * 1.0
# if self.sync_cls_avg_factor:
# cls_avg_factor = reduce_mean(
# seg_scores.new_tensor([cls_avg_factor]))
# cls_avg_factor = max(cls_avg_factor, 1)
loss_abu = self.loss_abu(
abu_scores, abu_labels, abu_label_weights)
else:
loss_abu = None
return loss_seg, loss_abu
# def get_targets(self, cls_scores_list: List[Tensor],
# bbox_preds_list: List[Tensor],
# batch_gt_instances: InstanceList,
# batch_img_metas: List[dict],
# with_neg_cls:bool=True,
# assigner_type:str = None) -> tuple:
# """Compute regression and classification targets for a batch image.
#
# Outputs from a single decoder layer of a single feature level are used.
#
# Args:
# cls_scores_list (list[Tensor]): Box score logits from a single
# decoder layer for each image, has shape [num_queries,
# cls_out_channels].
# bbox_preds_list (list[Tensor]): Sigmoid outputs from a single
# decoder layer for each image, with normalized coordinate
# (cx, cy, w, h) and shape [num_queries, 4].
# batch_gt_instances (list[:obj:`InstanceData`]): Batch of
# gt_instance. It usually includes ``bboxes`` and ``labels``
# attributes.
# batch_img_metas (list[dict]): Meta information of each image, e.g.,
# image size, scaling factor, etc.
#
# Returns:
# tuple: a tuple containing the following targets.
#
# - labels_list (list[Tensor]): Labels for all images.
# - label_weights_list (list[Tensor]): Label weights for all images.
# - bbox_targets_list (list[Tensor]): BBox targets for all images.
# - bbox_weights_list (list[Tensor]): BBox weights for all images.
# - num_total_pos (int): Number of positive samples in all images.
# - num_total_neg (int): Number of negative samples in all images.
# """
# (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list,
# pos_inds_list,
# neg_inds_list) = multi_apply(self._get_targets_single,
# cls_scores_list, bbox_preds_list,
# batch_gt_instances, batch_img_metas,
# with_neg_cls=with_neg_cls,
# assigner_type= assigner_type)
# num_total_pos = sum((inds.numel() for inds in pos_inds_list))
# num_total_neg = sum((inds.numel() for inds in neg_inds_list))
# if not with_neg_cls:
# num_total_neg = 0
# return (labels_list, label_weights_list, bbox_targets_list,
# bbox_weights_list, num_total_pos, num_total_neg)
# def get_targets_bbox(self,
# cls_scores_list: List[Tensor],
# bbox_preds_list: List[Tensor],
# batch_gt_instances: InstanceList,
# batch_img_metas: List[dict]) -> tuple:
# """Compute regression and classification targets for a batch image.
#
# Outputs from a single decoder layer of a single feature level are used.
#
# Args:
# cls_scores_list (list[Tensor]): Box score logits from a single
# decoder layer for each image, has shape [num_queries,
# cls_out_channels].
# bbox_preds_list (list[Tensor]): Sigmoid outputs from a single
# decoder layer for each image, with normalized coordinate
# (cx, cy, w, h) and shape [num_queries, 4].
# batch_gt_instances (list[:obj:`InstanceData`]): Batch of
# gt_instance. It usually includes ``bboxes`` and ``labels``
# attributes.
# batch_img_metas (list[dict]): Meta information of each image, e.g.,
# image size, scaling factor, etc.
#
# Returns:
# tuple: a tuple containing the following targets.
#
# - labels_list (list[Tensor]): Labels for all images.
# - label_weights_list (list[Tensor]): Label weights for all images.
# - bbox_targets_list (list[Tensor]): BBox targets for all images.
# - bbox_weights_list (list[Tensor]): BBox weights for all images.
# - num_total_pos (int): Number of positive samples in all images.
# - num_total_neg (int): Number of negative samples in all images.
# """
# (bbox_targets_list, bbox_weights_list, pos_inds_list,
# neg_inds_list) = multi_apply(self._get_targets_single_bbox, cls_scores_list,
# bbox_preds_list,
# batch_gt_instances, batch_img_metas)
# num_total_pos = sum((inds.numel() for inds in pos_inds_list))
# num_total_neg = sum((inds.numel() for inds in neg_inds_list))
# return (bbox_targets_list, bbox_weights_list, num_total_pos, num_total_neg)
def _loss_dn_single(self, dn_bbox_preds: Tensor,
reg_targets: Tuple[list, int],
batch_gt_instances: InstanceList,
batch_img_metas: List[dict],
dn_meta: Dict[str, int]) -> Tuple[Tensor]:
"""Denoising loss for outputs from a single decoder layer.
Args:
dn_cls_scores (Tensor): Classification scores of a single decoder
layer in denoising part, has shape (bs, num_denoising_queries,
cls_out_channels).
dn_bbox_preds (Tensor): Regression outputs of a single decoder
layer in denoising part. Each is a 4D-tensor with normalized
coordinate format (cx, cy, w, h) and has shape
(bs, num_denoising_queries, 4).
batch_gt_instances (list[:obj:`InstanceData`]): Batch of
gt_instance. It usually includes ``bboxes`` and ``labels``
attributes.
batch_img_metas (list[dict]): Meta information of each image, e.g.,
image size, scaling factor, etc.
dn_meta (Dict[str, int]): The dictionary saves information about
group collation, including 'num_denoising_queries' and
'num_denoising_groups'. It will be used for split outputs of
denoising and matching parts and loss calculation.
Returns:
Tuple[Tensor]: A tuple including `loss_cls`, `loss_box` and
`loss_iou`.
"""
(labels_list, label_weights_list, bbox_targets_list, bbox_weights_list,num_total_pos) = reg_targets
bbox_targets = torch.cat(bbox_targets_list, 0)
bbox_weights = torch.cat(bbox_weights_list, 0)
# Compute the average number of gt boxes across all gpus, for
# normalization purposes
num_total_pos = dn_bbox_preds.new_tensor([num_total_pos])
num_total_pos = torch.clamp(reduce_mean(num_total_pos), min=1).item()
# construct factors used for rescale bboxes
factors = []
for img_meta, bbox_pred in zip(batch_img_metas, dn_bbox_preds):
img_h, img_w = img_meta['img_shape']
factor = bbox_pred.new_tensor([img_w, img_h, img_w,
img_h]).unsqueeze(0).repeat(
bbox_pred.size(0), 1)
factors.append(factor)
factors = torch.cat(factors)
# DETR regress the relative position of boxes (cxcywh) in the image,
# thus the learning target is normalized by the image size. So here
# we need to re-scale them for calculating IoU loss
bbox_preds = dn_bbox_preds.reshape(-1, 4)
bboxes = bbox_cxcywh_to_xyxy(bbox_preds) * factors
bboxes_gt = bbox_cxcywh_to_xyxy(bbox_targets) * factors
# regression IoU loss, defaultly GIoU loss
if self.loss_iou is not None:
loss_iou = self.loss_iou(
bboxes, bboxes_gt, bbox_weights, avg_factor=num_total_pos)
else:
loss_iou = None
# regression L1 loss
loss_bbox = self.loss_bbox(
bbox_preds, bbox_targets, bbox_weights, avg_factor=num_total_pos)
return loss_bbox, loss_iou
def get_dn_targets(self, batch_gt_instances: InstanceList,
batch_img_metas: dict, dn_meta: Dict[str,
int]) -> tuple:
"""Get targets in denoising part for a batch of images.
Args:
batch_gt_instances (list[:obj:`InstanceData`]): Batch of
gt_instance. It usually includes ``bboxes`` and ``labels``
attributes.
batch_img_metas (list[dict]): Meta information of each image, e.g.,
image size, scaling factor, etc.
dn_meta (Dict[str, int]): The dictionary saves information about
group collation, including 'num_denoising_queries' and
'num_denoising_groups'. It will be used for split outputs of
denoising and matching parts and loss calculation.
Returns:
tuple: a tuple containing the following targets.
- labels_list (list[Tensor]): Labels for all images.
- label_weights_list (list[Tensor]): Label weights for all images.
- bbox_targets_list (list[Tensor]): BBox targets for all images.
- bbox_weights_list (list[Tensor]): BBox weights for all images.
- num_total_pos (int): Number of positive samples in all images.
- num_total_neg (int): Number of negative samples in all images.
"""
(labels_list, label_weights_list, bbox_targets_list, bbox_weights_list,pos_inds_list) = multi_apply(
self._get_dn_targets_single,
batch_gt_instances,
batch_img_metas,
dn_meta=dn_meta)
num_total_pos = sum((inds.numel() for inds in pos_inds_list))
return (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list, num_total_pos,)
def _get_dn_targets_single(self, gt_instances: InstanceData,
img_meta: dict, dn_meta: Dict[str,
int]) -> tuple:
"""Get targets in denoising part for one image.
Args:
gt_instances (:obj:`InstanceData`): Ground truth of instance
annotations. It should includes ``bboxes`` and ``labels``
attributes.
img_meta (dict): Meta information for one image.
dn_meta (Dict[str, int]): The dictionary saves information about
group collation, including 'num_denoising_queries' and
'num_denoising_groups'. It will be used for split outputs of
denoising and matching parts and loss calculation.
Returns:
tuple[Tensor]: a tuple containing the following for one image.
- labels (Tensor): Labels of each image.
- label_weights (Tensor]): Label weights of each image.
- bbox_targets (Tensor): BBox targets of each image.
- bbox_weights (Tensor): BBox weights of each image.
- pos_inds (Tensor): Sampled positive indices for each image.
- neg_inds (Tensor): Sampled negative indices for each image.
"""
gt_bboxes = gt_instances.bboxes
gt_labels = gt_instances.labels
num_groups = dn_meta['num_denoising_groups']
num_denoising_queries = dn_meta['num_denoising_queries']
num_queries_each_group = int(num_denoising_queries / num_groups)
device = gt_bboxes.device
if len(gt_labels) > 0:
t = torch.arange(len(gt_labels), dtype=torch.long, device=device)
t = t.unsqueeze(0).repeat(num_groups, 1)
pos_assigned_gt_inds = t.flatten()
pos_inds = torch.arange(num_groups, dtype=torch.long, device=device)
pos_inds = pos_inds.unsqueeze(1) * num_queries_each_group + t
pos_inds = pos_inds.flatten()
else:
pos_inds = pos_assigned_gt_inds = \
gt_bboxes.new_tensor([], dtype=torch.long)
# label targets
labels = gt_bboxes.new_full((num_denoising_queries, ),
self.num_classes,
dtype=torch.long)
labels[pos_inds] = gt_labels[pos_assigned_gt_inds]
label_weights = gt_bboxes.new_zeros(num_denoising_queries)
label_weights[pos_inds] = 1.0
# bbox targets
bbox_targets = torch.zeros(num_denoising_queries, 4, device=device)
bbox_weights = torch.zeros(num_denoising_queries, 4, device=device)
bbox_weights[pos_inds] = 1.0
img_h, img_w = img_meta['img_shape']
# DETR regress the relative position of boxes (cxcywh) in the image.
# Thus the learning target should be normalized by the image size, also
# the box format should be converted from defaultly x1y1x2y2 to cxcywh.
factor = gt_bboxes.new_tensor([img_w, img_h, img_w,
img_h]).unsqueeze(0)
gt_bboxes_normalized = gt_bboxes / factor
gt_bboxes_targets = bbox_xyxy_to_cxcywh(gt_bboxes_normalized)
bbox_targets[pos_inds] = gt_bboxes_targets.repeat([num_groups, 1])
return (labels, label_weights,bbox_targets, bbox_weights, pos_inds)
@staticmethod
def split_outputs(all_layers_cls_scores: Tensor,
all_layers_bbox_preds: Tensor,
dn_meta: Dict[str, int]) -> Tuple[Tensor]:
"""Split outputs of the denoising part and the matching part.
For the total outputs of `num_queries_total` length, the former
`num_denoising_queries` outputs are from denoising queries, and
the rest `num_matching_queries` ones are from matching queries,
where `num_queries_total` is the sum of `num_denoising_queries` and
`num_matching_queries`.
Args:
all_layers_cls_scores (Tensor): Classification scores of all
decoder layers, has shape (num_decoder_layers, bs,
num_queries_total, cls_out_channels).
all_layers_bbox_preds (Tensor): Regression outputs of all decoder
layers. Each is a 4D-tensor with normalized coordinate format
(cx, cy, w, h) and has shape (num_decoder_layers, bs,
num_queries_total, 4).
dn_meta (Dict[str, int]): The dictionary saves information about
group collation, including 'num_denoising_queries' and
'num_denoising_groups'.
Returns:
Tuple[Tensor]: a tuple containing the following outputs.
- all_layers_matching_cls_scores (Tensor): Classification scores
of all decoder layers in matching part, has shape
(num_decoder_layers, bs, num_matching_queries, cls_out_channels).
- all_layers_matching_bbox_preds (Tensor): Regression outputs of
all decoder layers in matching part. Each is a 4D-tensor with
normalized coordinate format (cx, cy, w, h) and has shape
(num_decoder_layers, bs, num_matching_queries, 4).
- all_layers_denoising_cls_scores (Tensor): Classification scores
of all decoder layers in denoising part, has shape
(num_decoder_layers, bs, num_denoising_queries,
cls_out_channels).
- all_layers_denoising_bbox_preds (Tensor): Regression outputs of
all decoder layers in denoising part. Each is a 4D-tensor with
normalized coordinate format (cx, cy, w, h) and has shape
(num_decoder_layers, bs, num_denoising_queries, 4).
"""
if dn_meta is not None:
num_denoising_queries = dn_meta['num_denoising_queries']
all_layers_denoising_cls_scores = \
all_layers_cls_scores[:,:, : num_denoising_queries, :]
all_layers_denoising_bbox_preds = \
all_layers_bbox_preds[:, :, : num_denoising_queries, :]
all_layers_matching_cls_scores = \
all_layers_cls_scores[:, :, num_denoising_queries:, :]
all_layers_matching_bbox_preds = \
all_layers_bbox_preds[:, :, num_denoising_queries:, :]
else:
all_layers_denoising_cls_scores = None
all_layers_denoising_bbox_preds = None
all_layers_matching_cls_scores = all_layers_cls_scores
all_layers_matching_bbox_preds = all_layers_bbox_preds
return (all_layers_matching_cls_scores, all_layers_matching_bbox_preds,
all_layers_denoising_cls_scores,
all_layers_denoising_bbox_preds)
@staticmethod
def split_outputsv1(all_layers_cls_scores: Tensor,
all_layers_bbox_preds: Tensor,
dn_meta: Dict[str, int]) -> Tuple[Tensor]:
"""Split outputs of the denoising part and the matching part.
For the total outputs of `num_queries_total` length, the former
`num_denoising_queries` outputs are from denoising queries, and
the rest `num_matching_queries` ones are from matching queries,
where `num_queries_total` is the sum of `num_denoising_queries` and
`num_matching_queries`.
Args:
all_layers_cls_scores (Tensor): Classification scores of all
decoder layers, has shape (num_decoder_layers, bs,
num_queries_total, cls_out_channels).
all_layers_bbox_preds (Tensor): Regression outputs of all decoder
layers. Each is a 4D-tensor with normalized coordinate format
(cx, cy, w, h) and has shape (num_decoder_layers, bs,
num_queries_total, 4).
dn_meta (Dict[str, int]): The dictionary saves information about
group collation, including 'num_denoising_queries' and
'num_denoising_groups'.
Returns:
Tuple[Tensor]: a tuple containing the following outputs.
- all_layers_matching_cls_scores (Tensor): Classification scores
of all decoder layers in matching part, has shape
(num_decoder_layers, bs, num_matching_queries, cls_out_channels).
- all_layers_matching_bbox_preds (Tensor): Regression outputs of
all decoder layers in matching part. Each is a 4D-tensor with
normalized coordinate format (cx, cy, w, h) and has shape
(num_decoder_layers, bs, num_matching_queries, 4).
- all_layers_denoising_cls_scores (Tensor): Classification scores
of all decoder layers in denoising part, has shape
(num_decoder_layers, bs, num_denoising_queries,
cls_out_channels).
- all_layers_denoising_bbox_preds (Tensor): Regression outputs of
all decoder layers in denoising part. Each is a 4D-tensor with
normalized coordinate format (cx, cy, w, h) and has shape
(num_decoder_layers, bs, num_denoising_queries, 4).
"""
if dn_meta is not None:
num_denoising_queries = dn_meta['num_denoising_queries']
all_layers_denoising_cls_scores = \
all_layers_cls_scores[:, : num_denoising_queries, :]
all_layers_denoising_bbox_preds = \
all_layers_bbox_preds[:, :, : num_denoising_queries, :]
all_layers_matching_cls_scores = \
all_layers_cls_scores[:, num_denoising_queries:, :]
all_layers_matching_bbox_preds = \
all_layers_bbox_preds[:, :, num_denoising_queries:, :]
else:
all_layers_denoising_cls_scores = None
all_layers_denoising_bbox_preds = None
all_layers_matching_cls_scores = all_layers_cls_scores
all_layers_matching_bbox_preds = all_layers_bbox_preds
return (all_layers_matching_cls_scores, all_layers_matching_bbox_preds,
all_layers_denoising_cls_scores,
all_layers_denoising_bbox_preds)
def predict(self,
hidden_states: Tensor,
references: List[Tensor],
centers: Tensor,
center_scores: Tensor,
topk_centers_scores: Tensor,
cls_scores: Tensor,
topk_cls_scores: Tensor,
seg_scores: Optional[Tensor],
abu_scores: Optional[Tensor],
batch_data_samples: SampleList,
rescale: bool = True) -> InstanceList:
"""Perform forward propagation and loss calculation of the detection
head on the queries of the upstream network.
Args:
hidden_states (Tensor): Hidden states output from each decoder
layer, has shape (num_decoder_layers, num_queries, bs, dim).
references (list[Tensor]): List of the reference from the decoder.
The first reference is the `init_reference` (initial) and the
other num_decoder_layers(6) references are `inter_references`
(intermediate). The `init_reference` has shape (bs,
num_queries, 4) when `as_two_stage` of the detector is `True`,
otherwise (bs, num_queries, 2). Each `inter_reference` has
shape (bs, num_queries, 4) when `with_box_refine` of the
detector is `True`, otherwise (bs, num_queries, 2). The
coordinates are arranged as (cx, cy) when the last dimension is
2, and (cx, cy, w, h) when it is 4.
batch_data_samples (list[:obj:`DetDataSample`]): The Data
Samples. It usually includes information such as
`gt_instance`, `gt_panoptic_seg` and `gt_sem_seg`.
rescale (bool, optional): If `True`, return boxes in original
image space. Defaults to `True`.
Returns:
list[obj:`InstanceData`]: Detection results of each image
after the post process.
"""
batch_img_metas = [
data_samples.metainfo for data_samples in batch_data_samples
]
outs = self(hidden_states, references, topk_cls_scores)
if self.predict_segmentation:
seg_scores = seg_scores.sigmoid()
if self.predict_abundance:
abu_scores = torch.clamp((abu_scores.sigmoid()-0.25)*2,0,1)
predictions = self.predict_by_feat(
*outs,seg_scores,abu_scores, batch_img_metas=batch_img_metas, rescale=rescale)
return predictions
def predict_by_feat(self,
all_layers_cls_scores: Tensor,
all_layers_bbox_preds: Tensor,
seg_scores: Optional[Tensor],
abu_scores: Optional[Tensor],
batch_img_metas: List[Dict],
rescale: bool = False) -> InstanceList:
"""Transform a batch of output features extracted from the head into
bbox results.
Args:
all_layers_cls_scores (Tensor): Classification scores of all
decoder layers, has shape (num_decoder_layers, bs, num_queries,
cls_out_channels).
all_layers_bbox_preds (Tensor): Regression outputs of all decoder
layers. Each is a 4D-tensor with normalized coordinate format
(cx, cy, w, h) and shape (num_decoder_layers, bs, num_queries,
4) with the last dimension arranged as (cx, cy, w, h).
batch_img_metas (list[dict]): Meta information of each image.
rescale (bool, optional): If `True`, return boxes in original
image space. Default `False`.
Returns:
list[obj:`InstanceData`]: Detection results of each image
after the post process.
"""
cls_scores = all_layers_cls_scores[-1]
bbox_preds = all_layers_bbox_preds[-1]
result_list = []
for img_id in range(len(batch_img_metas)):
cls_score = cls_scores[img_id]
bbox_pred = bbox_preds[img_id]
img_meta = batch_img_metas[img_id]
if self.predict_segmentation:
seg_score = seg_scores[img_id]
else:
seg_score = None
if self.predict_abundance:
abu_score = abu_scores[img_id]
else:
abu_score = None
results = self._predict_by_feat_single(cls_score, bbox_pred,
seg_score,abu_score,
img_meta, rescale)
result_list.append(results)
return result_list
def _predict_by_feat_single(self,
cls_score: Tensor,
bbox_pred: Tensor,
seg_score: Optional[Tensor],
abu_score: Optional[Tensor],
img_meta: dict,
rescale: bool = True) -> InstanceData:
"""Transform outputs from the last decoder layer into bbox predictions
for each image.
Args:
cls_score (Tensor): Box score logits from the last decoder layer
for each image. Shape [num_queries, cls_out_channels].
bbox_pred (Tensor): Sigmoid outputs from the last decoder layer
for each image, with coordinate format (cx, cy, w, h) and
shape [num_queries, 4].
img_meta (dict): Image meta info.
rescale (bool): If True, return boxes in original image
space. Default True.
Returns:
:obj:`InstanceData`: Detection results of each image
after the post process.
Each item usually contains following keys.
- scores (Tensor): Classification scores, has a shape
(num_instance, )
- labels (Tensor): Labels of bboxes, has a shape
(num_instances, ).
- bboxes (Tensor): Has a shape (num_instances, 4),
the last dimension 4 arrange as (x1, y1, x2, y2).
"""
assert len(cls_score) == len(bbox_pred) # num_queries
max_per_img = self.test_cfg.get('max_per_img', len(cls_score))
img_shape = img_meta['img_shape']
assert self.loss_cls.use_sigmoid
cls_score = cls_score.sigmoid()
# scores, indexes = cls_score.view(-1).topk(max_per_img)
scores, indexes = torch.sort(cls_score.view(-1), descending=True)
# indexes = indexes[scores > self.score_threshold]
# scores = scores[scores > self.score_threshold]
det_labels = indexes % self.num_classes
bbox_index = torch.div(indexes, self.num_classes, rounding_mode='trunc')
bbox_pred = bbox_pred[bbox_index]
det_bboxes = bbox_cxcywh_to_xyxy(bbox_pred)
det_bboxes[:, 0::2] = det_bboxes[:, 0::2] * img_shape[1]
det_bboxes[:, 1::2] = det_bboxes[:, 1::2] * img_shape[0]
det_bboxes[:, 0::2].clamp_(min=0, max=img_shape[1])
det_bboxes[:, 1::2].clamp_(min=0, max=img_shape[0])
if self.use_nms:
if det_labels.numel() > 0:
bboxes_scores, keep = batched_nms(det_bboxes, scores.contiguous(), det_labels, self.test_nms, class_agnostic=(not self.class_wise_nms))
if keep.numel() > max_per_img:
bboxes_scores = bboxes_scores[:max_per_img]
det_labels = det_labels[keep][:max_per_img]
else:
det_labels = det_labels[keep]
det_bboxes = bboxes_scores[:, :-1]
scores = bboxes_scores[:, -1]
if self.pre_bboxes_round:
det_bboxes = adjust_bbox_to_pixel(det_bboxes)
if rescale:
# assert img_meta.get('scale_factor') is not None
# det_bboxes /= det_bboxes.new_tensor(
# img_meta['scale_factor']).repeat((1, 2))
# rw by lzx
if img_meta.get('scale_factor') is not None:
det_bboxes /= det_bboxes.new_tensor(
img_meta['scale_factor']).repeat((1, 2))
if self.predict_segmentation:
img_h, img_w = img_meta['ori_shape'][:2]
seg_score = seg_score.view(img_h, img_w)
seg_mask=seg_score>self.mask_threshold
N = det_bboxes.size(0)
im_mask = torch.zeros(
N,
img_shape[0],
img_shape[1],
device=det_bboxes.device,
dtype=torch.bool)
for i in range(N):
x0, y0, x1, y1 = det_bboxes[i,:]
x0 = max(int(x0)-self.mask_extend_pixel,0)
x1 = min(int(x1)+self.mask_extend_pixel,img_w)
y0 = max(int(y0)-self.mask_extend_pixel,0)
y1 = min(int(y1)+self.mask_extend_pixel,img_h)
im_mask[i, y0:y1,x0:x1] =seg_mask[y0:y1,x0:x1 ]
new_mask = torch.sum(im_mask,dim=0)
seg_score_new = seg_score.clone().detach()
seg_score_new[new_mask==0] = 0
if self.save_path is not None:
img_name=img_meta['img_path'].split('/')[-1].replace('.npy','').replace('.png','').replace('.jpg','').replace('.mat','')
sio.savemat(os.path.join(self.save_path,img_name+'_seg_scoremap.mat'),
{'data':seg_score.detach().cpu().numpy()})
sio.savemat(os.path.join(self.save_path,img_name+'_seg_predictionmap.mat'),
{'data':seg_score_new.detach().cpu().numpy()})
if self.predict_abundance:
abu_score = abu_score.view(img_h, img_w)
abu_score_new = abu_score.clone().detach()
abu_score_new[new_mask == 0] = 0
sio.savemat(os.path.join(self.save_path, img_name + '_abu_scoremap.mat'),
{'data': abu_score.detach().cpu().numpy()})
sio.savemat(os.path.join(self.save_path, img_name + '_abu_predictionmap.mat'),
{'data': seg_score_new.detach().cpu().numpy()})
results = InstanceData()
results.bboxes = det_bboxes
results.scores = scores
results.labels = det_labels
if self.predict_segmentation:
results.masks = im_mask
return results
|