target.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import six
  15. import math
  16. import numpy as np
  17. import paddle
  18. from ..bbox_utils import bbox2delta, bbox_overlaps
  19. import copy
  20. def rpn_anchor_target(anchors,
  21. gt_boxes,
  22. rpn_batch_size_per_im,
  23. rpn_positive_overlap,
  24. rpn_negative_overlap,
  25. rpn_fg_fraction,
  26. use_random=True,
  27. batch_size=1,
  28. ignore_thresh=-1,
  29. is_crowd=None,
  30. weights=[1., 1., 1., 1.]):
  31. tgt_labels = []
  32. tgt_bboxes = []
  33. tgt_deltas = []
  34. for i in range(batch_size):
  35. gt_bbox = gt_boxes[i]
  36. is_crowd_i = is_crowd[i] if is_crowd else None
  37. # Step1: match anchor and gt_bbox
  38. matches, match_labels = label_box(
  39. anchors, gt_bbox, rpn_positive_overlap, rpn_negative_overlap, True,
  40. ignore_thresh, is_crowd_i)
  41. # Step2: sample anchor
  42. fg_inds, bg_inds = subsample_labels(match_labels, rpn_batch_size_per_im,
  43. rpn_fg_fraction, 0, use_random)
  44. # Fill with the ignore label (-1), then set positive and negative labels
  45. labels = paddle.full(match_labels.shape, -1, dtype='int32')
  46. if bg_inds.shape[0] > 0:
  47. labels = paddle.scatter(labels, bg_inds, paddle.zeros_like(bg_inds))
  48. if fg_inds.shape[0] > 0:
  49. labels = paddle.scatter(labels, fg_inds, paddle.ones_like(fg_inds))
  50. # Step3: make output
  51. if gt_bbox.shape[0] == 0:
  52. matched_gt_boxes = paddle.zeros([0, 4])
  53. tgt_delta = paddle.zeros([0, 4])
  54. else:
  55. matched_gt_boxes = paddle.gather(gt_bbox, matches)
  56. tgt_delta = bbox2delta(anchors, matched_gt_boxes, weights)
  57. matched_gt_boxes.stop_gradient = True
  58. tgt_delta.stop_gradient = True
  59. labels.stop_gradient = True
  60. tgt_labels.append(labels)
  61. tgt_bboxes.append(matched_gt_boxes)
  62. tgt_deltas.append(tgt_delta)
  63. return tgt_labels, tgt_bboxes, tgt_deltas
  64. def label_box(anchors,
  65. gt_boxes,
  66. positive_overlap,
  67. negative_overlap,
  68. allow_low_quality,
  69. ignore_thresh,
  70. is_crowd=None):
  71. iou = bbox_overlaps(gt_boxes, anchors)
  72. n_gt = gt_boxes.shape[0]
  73. if n_gt == 0 or is_crowd is None:
  74. n_gt_crowd = 0
  75. else:
  76. n_gt_crowd = paddle.nonzero(is_crowd).shape[0]
  77. if iou.shape[0] == 0 or n_gt_crowd == n_gt:
  78. # No truth, assign everything to background
  79. default_matches = paddle.full((iou.shape[1], ), 0, dtype='int64')
  80. default_match_labels = paddle.full((iou.shape[1], ), 0, dtype='int32')
  81. return default_matches, default_match_labels
  82. # if ignore_thresh > 0, remove anchor if it is closed to
  83. # one of the crowded ground-truth
  84. if n_gt_crowd > 0:
  85. N_a = anchors.shape[0]
  86. ones = paddle.ones([N_a])
  87. mask = is_crowd * ones
  88. if ignore_thresh > 0:
  89. crowd_iou = iou * mask
  90. valid = (paddle.sum((crowd_iou > ignore_thresh).cast('int32'),
  91. axis=0) > 0).cast('float32')
  92. iou = iou * (1 - valid) - valid
  93. # ignore the iou between anchor and crowded ground-truth
  94. iou = iou * (1 - mask) - mask
  95. matched_vals, matches = paddle.topk(iou, k=1, axis=0)
  96. match_labels = paddle.full(matches.shape, -1, dtype='int32')
  97. # set ignored anchor with iou = -1
  98. neg_cond = paddle.logical_and(matched_vals > -1,
  99. matched_vals < negative_overlap)
  100. match_labels = paddle.where(neg_cond,
  101. paddle.zeros_like(match_labels), match_labels)
  102. match_labels = paddle.where(matched_vals >= positive_overlap,
  103. paddle.ones_like(match_labels), match_labels)
  104. if allow_low_quality:
  105. highest_quality_foreach_gt = iou.max(axis=1, keepdim=True)
  106. pred_inds_with_highest_quality = paddle.logical_and(
  107. iou > 0, iou == highest_quality_foreach_gt).cast('int32').sum(
  108. 0, keepdim=True)
  109. match_labels = paddle.where(pred_inds_with_highest_quality > 0,
  110. paddle.ones_like(match_labels),
  111. match_labels)
  112. matches = matches.flatten()
  113. match_labels = match_labels.flatten()
  114. return matches, match_labels
  115. def subsample_labels(labels,
  116. num_samples,
  117. fg_fraction,
  118. bg_label=0,
  119. use_random=True):
  120. positive = paddle.nonzero(
  121. paddle.logical_and(labels != -1, labels != bg_label))
  122. negative = paddle.nonzero(labels == bg_label)
  123. fg_num = int(num_samples * fg_fraction)
  124. fg_num = min(positive.numel(), fg_num)
  125. bg_num = num_samples - fg_num
  126. bg_num = min(negative.numel(), bg_num)
  127. if fg_num == 0 and bg_num == 0:
  128. fg_inds = paddle.zeros([0], dtype='int32')
  129. bg_inds = paddle.zeros([0], dtype='int32')
  130. return fg_inds, bg_inds
  131. # randomly select positive and negative examples
  132. negative = negative.cast('int32').flatten()
  133. bg_perm = paddle.randperm(negative.numel(), dtype='int32')
  134. bg_perm = paddle.slice(bg_perm, axes=[0], starts=[0], ends=[bg_num])
  135. if use_random:
  136. bg_inds = paddle.gather(negative, bg_perm)
  137. else:
  138. bg_inds = paddle.slice(negative, axes=[0], starts=[0], ends=[bg_num])
  139. if fg_num == 0:
  140. fg_inds = paddle.zeros([0], dtype='int32')
  141. return fg_inds, bg_inds
  142. positive = positive.cast('int32').flatten()
  143. fg_perm = paddle.randperm(positive.numel(), dtype='int32')
  144. fg_perm = paddle.slice(fg_perm, axes=[0], starts=[0], ends=[fg_num])
  145. if use_random:
  146. fg_inds = paddle.gather(positive, fg_perm)
  147. else:
  148. fg_inds = paddle.slice(positive, axes=[0], starts=[0], ends=[fg_num])
  149. return fg_inds, bg_inds
  150. def generate_proposal_target(rpn_rois,
  151. gt_classes,
  152. gt_boxes,
  153. batch_size_per_im,
  154. fg_fraction,
  155. fg_thresh,
  156. bg_thresh,
  157. num_classes,
  158. ignore_thresh=-1.,
  159. is_crowd=None,
  160. use_random=True,
  161. is_cascade=False,
  162. cascade_iou=0.5):
  163. rois_with_gt = []
  164. tgt_labels = []
  165. tgt_bboxes = []
  166. tgt_gt_inds = []
  167. new_rois_num = []
  168. # In cascade rcnn, the threshold for foreground and background
  169. # is used from cascade_iou
  170. fg_thresh = cascade_iou if is_cascade else fg_thresh
  171. bg_thresh = cascade_iou if is_cascade else bg_thresh
  172. for i, rpn_roi in enumerate(rpn_rois):
  173. gt_bbox = gt_boxes[i]
  174. is_crowd_i = is_crowd[i] if is_crowd else None
  175. gt_class = paddle.squeeze(gt_classes[i], axis=-1)
  176. # Concat RoIs and gt boxes except cascade rcnn or none gt
  177. if not is_cascade and gt_bbox.shape[0] > 0:
  178. bbox = paddle.concat([rpn_roi, gt_bbox])
  179. else:
  180. bbox = rpn_roi
  181. # Step1: label bbox
  182. matches, match_labels = label_box(bbox, gt_bbox, fg_thresh, bg_thresh,
  183. False, ignore_thresh, is_crowd_i)
  184. # Step2: sample bbox
  185. sampled_inds, sampled_gt_classes = sample_bbox(
  186. matches, match_labels, gt_class, batch_size_per_im, fg_fraction,
  187. num_classes, use_random, is_cascade)
  188. # Step3: make output
  189. rois_per_image = bbox if is_cascade else paddle.gather(bbox,
  190. sampled_inds)
  191. sampled_gt_ind = matches if is_cascade else paddle.gather(matches,
  192. sampled_inds)
  193. if gt_bbox.shape[0] > 0:
  194. sampled_bbox = paddle.gather(gt_bbox, sampled_gt_ind)
  195. else:
  196. sampled_bbox = paddle.zeros([0, 4], dtype='float32')
  197. rois_per_image.stop_gradient = True
  198. sampled_gt_ind.stop_gradient = True
  199. sampled_bbox.stop_gradient = True
  200. tgt_labels.append(sampled_gt_classes)
  201. tgt_bboxes.append(sampled_bbox)
  202. rois_with_gt.append(rois_per_image)
  203. tgt_gt_inds.append(sampled_gt_ind)
  204. new_rois_num.append(paddle.shape(sampled_inds)[0])
  205. new_rois_num = paddle.concat(new_rois_num)
  206. return rois_with_gt, tgt_labels, tgt_bboxes, tgt_gt_inds, new_rois_num
  207. def sample_bbox(matches,
  208. match_labels,
  209. gt_classes,
  210. batch_size_per_im,
  211. fg_fraction,
  212. num_classes,
  213. use_random=True,
  214. is_cascade=False):
  215. n_gt = gt_classes.shape[0]
  216. if n_gt == 0:
  217. # No truth, assign everything to background
  218. gt_classes = paddle.ones(matches.shape, dtype='int32') * num_classes
  219. #return matches, match_labels + num_classes
  220. else:
  221. gt_classes = paddle.gather(gt_classes, matches)
  222. gt_classes = paddle.where(match_labels == 0,
  223. paddle.ones_like(gt_classes) * num_classes,
  224. gt_classes)
  225. gt_classes = paddle.where(match_labels == -1,
  226. paddle.ones_like(gt_classes) * -1, gt_classes)
  227. if is_cascade:
  228. index = paddle.arange(matches.shape[0])
  229. return index, gt_classes
  230. rois_per_image = int(batch_size_per_im)
  231. fg_inds, bg_inds = subsample_labels(gt_classes, rois_per_image, fg_fraction,
  232. num_classes, use_random)
  233. if fg_inds.shape[0] == 0 and bg_inds.shape[0] == 0:
  234. # fake output labeled with -1 when all boxes are neither
  235. # foreground nor background
  236. sampled_inds = paddle.zeros([1], dtype='int32')
  237. else:
  238. sampled_inds = paddle.concat([fg_inds, bg_inds])
  239. sampled_gt_classes = paddle.gather(gt_classes, sampled_inds)
  240. return sampled_inds, sampled_gt_classes
  241. def polygons_to_mask(polygons, height, width):
  242. """
  243. Args:
  244. polygons (list[ndarray]): each array has shape (Nx2,)
  245. height, width (int)
  246. Returns:
  247. ndarray: a bool mask of shape (height, width)
  248. """
  249. import pycocotools.mask as mask_util
  250. assert len(polygons) > 0, "COCOAPI does not support empty polygons"
  251. rles = mask_util.frPyObjects(polygons, height, width)
  252. rle = mask_util.merge(rles)
  253. return mask_util.decode(rle).astype(np.bool)
  254. def rasterize_polygons_within_box(poly, box, resolution):
  255. w, h = box[2] - box[0], box[3] - box[1]
  256. polygons = [np.asarray(p, dtype=np.float64) for p in poly]
  257. for p in polygons:
  258. p[0::2] = p[0::2] - box[0]
  259. p[1::2] = p[1::2] - box[1]
  260. ratio_h = resolution / max(h, 0.1)
  261. ratio_w = resolution / max(w, 0.1)
  262. if ratio_h == ratio_w:
  263. for p in polygons:
  264. p *= ratio_h
  265. else:
  266. for p in polygons:
  267. p[0::2] *= ratio_w
  268. p[1::2] *= ratio_h
  269. # 3. Rasterize the polygons with coco api
  270. mask = polygons_to_mask(polygons, resolution, resolution)
  271. mask = paddle.to_tensor(mask, dtype='int32')
  272. return mask
  273. def generate_mask_target(gt_segms, rois, labels_int32, sampled_gt_inds,
  274. num_classes, resolution):
  275. mask_rois = []
  276. mask_rois_num = []
  277. tgt_masks = []
  278. tgt_classes = []
  279. mask_index = []
  280. tgt_weights = []
  281. for k in range(len(rois)):
  282. labels_per_im = labels_int32[k]
  283. # select rois labeled with foreground
  284. fg_inds = paddle.nonzero(
  285. paddle.logical_and(labels_per_im != -1, labels_per_im !=
  286. num_classes))
  287. has_fg = True
  288. # generate fake roi if foreground is empty
  289. if fg_inds.numel() == 0:
  290. has_fg = False
  291. fg_inds = paddle.ones([1], dtype='int32')
  292. inds_per_im = sampled_gt_inds[k]
  293. inds_per_im = paddle.gather(inds_per_im, fg_inds)
  294. rois_per_im = rois[k]
  295. fg_rois = paddle.gather(rois_per_im, fg_inds)
  296. # Copy the foreground roi to cpu
  297. # to generate mask target with ground-truth
  298. boxes = fg_rois.numpy()
  299. gt_segms_per_im = gt_segms[k]
  300. new_segm = []
  301. inds_per_im = inds_per_im.numpy()
  302. if len(gt_segms_per_im) > 0:
  303. for i in inds_per_im:
  304. new_segm.append(gt_segms_per_im[i])
  305. fg_inds_new = fg_inds.reshape([-1]).numpy()
  306. results = []
  307. if len(gt_segms_per_im) > 0:
  308. for j in fg_inds_new:
  309. results.append(
  310. rasterize_polygons_within_box(new_segm[j], boxes[j],
  311. resolution))
  312. else:
  313. results.append(paddle.ones([resolution, resolution], dtype='int32'))
  314. fg_classes = paddle.gather(labels_per_im, fg_inds)
  315. weight = paddle.ones([fg_rois.shape[0]], dtype='float32')
  316. if not has_fg:
  317. # now all sampled classes are background
  318. # which will cause error in loss calculation,
  319. # make fake classes with weight of 0.
  320. fg_classes = paddle.zeros([1], dtype='int32')
  321. weight = weight - 1
  322. tgt_mask = paddle.stack(results)
  323. tgt_mask.stop_gradient = True
  324. fg_rois.stop_gradient = True
  325. mask_index.append(fg_inds)
  326. mask_rois.append(fg_rois)
  327. mask_rois_num.append(paddle.shape(fg_rois)[0])
  328. tgt_classes.append(fg_classes)
  329. tgt_masks.append(tgt_mask)
  330. tgt_weights.append(weight)
  331. mask_index = paddle.concat(mask_index)
  332. mask_rois_num = paddle.concat(mask_rois_num)
  333. tgt_classes = paddle.concat(tgt_classes, axis=0)
  334. tgt_masks = paddle.concat(tgt_masks, axis=0)
  335. tgt_weights = paddle.concat(tgt_weights, axis=0)
  336. return mask_rois, mask_rois_num, tgt_classes, tgt_masks, mask_index, tgt_weights
  337. def libra_sample_pos(max_overlaps, max_classes, pos_inds, num_expected):
  338. if len(pos_inds) <= num_expected:
  339. return pos_inds
  340. else:
  341. unique_gt_inds = np.unique(max_classes[pos_inds])
  342. num_gts = len(unique_gt_inds)
  343. num_per_gt = int(round(num_expected / float(num_gts)) + 1)
  344. sampled_inds = []
  345. for i in unique_gt_inds:
  346. inds = np.nonzero(max_classes == i)[0]
  347. before_len = len(inds)
  348. inds = list(set(inds) & set(pos_inds))
  349. after_len = len(inds)
  350. if len(inds) > num_per_gt:
  351. inds = np.random.choice(inds, size=num_per_gt, replace=False)
  352. sampled_inds.extend(list(inds)) # combine as a new sampler
  353. if len(sampled_inds) < num_expected:
  354. num_extra = num_expected - len(sampled_inds)
  355. extra_inds = np.array(list(set(pos_inds) - set(sampled_inds)))
  356. assert len(sampled_inds) + len(extra_inds) == len(pos_inds), \
  357. "sum of sampled_inds({}) and extra_inds({}) length must be equal with pos_inds({})!".format(
  358. len(sampled_inds), len(extra_inds), len(pos_inds))
  359. if len(extra_inds) > num_extra:
  360. extra_inds = np.random.choice(
  361. extra_inds, size=num_extra, replace=False)
  362. sampled_inds.extend(extra_inds.tolist())
  363. elif len(sampled_inds) > num_expected:
  364. sampled_inds = np.random.choice(
  365. sampled_inds, size=num_expected, replace=False)
  366. return paddle.to_tensor(sampled_inds)
  367. def libra_sample_via_interval(max_overlaps, full_set, num_expected, floor_thr,
  368. num_bins, bg_thresh):
  369. max_iou = max_overlaps.max()
  370. iou_interval = (max_iou - floor_thr) / num_bins
  371. per_num_expected = int(num_expected / num_bins)
  372. sampled_inds = []
  373. for i in range(num_bins):
  374. start_iou = floor_thr + i * iou_interval
  375. end_iou = floor_thr + (i + 1) * iou_interval
  376. tmp_set = set(
  377. np.where(
  378. np.logical_and(max_overlaps >= start_iou, max_overlaps <
  379. end_iou))[0])
  380. tmp_inds = list(tmp_set & full_set)
  381. if len(tmp_inds) > per_num_expected:
  382. tmp_sampled_set = np.random.choice(
  383. tmp_inds, size=per_num_expected, replace=False)
  384. else:
  385. tmp_sampled_set = np.array(tmp_inds, dtype=np.int)
  386. sampled_inds.append(tmp_sampled_set)
  387. sampled_inds = np.concatenate(sampled_inds)
  388. if len(sampled_inds) < num_expected:
  389. num_extra = num_expected - len(sampled_inds)
  390. extra_inds = np.array(list(full_set - set(sampled_inds)))
  391. assert len(sampled_inds) + len(extra_inds) == len(full_set), \
  392. "sum of sampled_inds({}) and extra_inds({}) length must be equal with full_set({})!".format(
  393. len(sampled_inds), len(extra_inds), len(full_set))
  394. if len(extra_inds) > num_extra:
  395. extra_inds = np.random.choice(extra_inds, num_extra, replace=False)
  396. sampled_inds = np.concatenate([sampled_inds, extra_inds])
  397. return sampled_inds
  398. def libra_sample_neg(max_overlaps,
  399. max_classes,
  400. neg_inds,
  401. num_expected,
  402. floor_thr=-1,
  403. floor_fraction=0,
  404. num_bins=3,
  405. bg_thresh=0.5):
  406. if len(neg_inds) <= num_expected:
  407. return neg_inds
  408. else:
  409. # balance sampling for negative samples
  410. neg_set = set(neg_inds.tolist())
  411. if floor_thr > 0:
  412. floor_set = set(
  413. np.where(
  414. np.logical_and(max_overlaps >= 0, max_overlaps < floor_thr))
  415. [0])
  416. iou_sampling_set = set(np.where(max_overlaps >= floor_thr)[0])
  417. elif floor_thr == 0:
  418. floor_set = set(np.where(max_overlaps == 0)[0])
  419. iou_sampling_set = set(np.where(max_overlaps > floor_thr)[0])
  420. else:
  421. floor_set = set()
  422. iou_sampling_set = set(np.where(max_overlaps > floor_thr)[0])
  423. floor_thr = 0
  424. floor_neg_inds = list(floor_set & neg_set)
  425. iou_sampling_neg_inds = list(iou_sampling_set & neg_set)
  426. num_expected_iou_sampling = int(num_expected * (1 - floor_fraction))
  427. if len(iou_sampling_neg_inds) > num_expected_iou_sampling:
  428. if num_bins >= 2:
  429. iou_sampled_inds = libra_sample_via_interval(
  430. max_overlaps,
  431. set(iou_sampling_neg_inds), num_expected_iou_sampling,
  432. floor_thr, num_bins, bg_thresh)
  433. else:
  434. iou_sampled_inds = np.random.choice(
  435. iou_sampling_neg_inds,
  436. size=num_expected_iou_sampling,
  437. replace=False)
  438. else:
  439. iou_sampled_inds = np.array(iou_sampling_neg_inds, dtype=np.int)
  440. num_expected_floor = num_expected - len(iou_sampled_inds)
  441. if len(floor_neg_inds) > num_expected_floor:
  442. sampled_floor_inds = np.random.choice(
  443. floor_neg_inds, size=num_expected_floor, replace=False)
  444. else:
  445. sampled_floor_inds = np.array(floor_neg_inds, dtype=np.int)
  446. sampled_inds = np.concatenate((sampled_floor_inds, iou_sampled_inds))
  447. if len(sampled_inds) < num_expected:
  448. num_extra = num_expected - len(sampled_inds)
  449. extra_inds = np.array(list(neg_set - set(sampled_inds)))
  450. if len(extra_inds) > num_extra:
  451. extra_inds = np.random.choice(
  452. extra_inds, size=num_extra, replace=False)
  453. sampled_inds = np.concatenate((sampled_inds, extra_inds))
  454. return paddle.to_tensor(sampled_inds)
  455. def libra_label_box(anchors, gt_boxes, gt_classes, positive_overlap,
  456. negative_overlap, num_classes):
  457. # TODO: use paddle API to speed up
  458. gt_classes = gt_classes.numpy()
  459. gt_overlaps = np.zeros((anchors.shape[0], num_classes))
  460. matches = np.zeros((anchors.shape[0]), dtype=np.int32)
  461. if len(gt_boxes) > 0:
  462. proposal_to_gt_overlaps = bbox_overlaps(anchors, gt_boxes).numpy()
  463. overlaps_argmax = proposal_to_gt_overlaps.argmax(axis=1)
  464. overlaps_max = proposal_to_gt_overlaps.max(axis=1)
  465. # Boxes which with non-zero overlap with gt boxes
  466. overlapped_boxes_ind = np.where(overlaps_max > 0)[0]
  467. overlapped_boxes_gt_classes = gt_classes[overlaps_argmax[
  468. overlapped_boxes_ind]]
  469. for idx in range(len(overlapped_boxes_ind)):
  470. gt_overlaps[overlapped_boxes_ind[idx], overlapped_boxes_gt_classes[
  471. idx]] = overlaps_max[overlapped_boxes_ind[idx]]
  472. matches[overlapped_boxes_ind[idx]] = overlaps_argmax[
  473. overlapped_boxes_ind[idx]]
  474. gt_overlaps = paddle.to_tensor(gt_overlaps)
  475. matches = paddle.to_tensor(matches)
  476. matched_vals = paddle.max(gt_overlaps, axis=1)
  477. match_labels = paddle.full(matches.shape, -1, dtype='int32')
  478. match_labels = paddle.where(matched_vals < negative_overlap,
  479. paddle.zeros_like(match_labels), match_labels)
  480. match_labels = paddle.where(matched_vals >= positive_overlap,
  481. paddle.ones_like(match_labels), match_labels)
  482. return matches, match_labels, matched_vals
  483. def libra_sample_bbox(matches,
  484. match_labels,
  485. matched_vals,
  486. gt_classes,
  487. batch_size_per_im,
  488. num_classes,
  489. fg_fraction,
  490. fg_thresh,
  491. bg_thresh,
  492. num_bins,
  493. use_random=True,
  494. is_cascade_rcnn=False):
  495. rois_per_image = int(batch_size_per_im)
  496. fg_rois_per_im = int(np.round(fg_fraction * rois_per_image))
  497. bg_rois_per_im = rois_per_image - fg_rois_per_im
  498. if is_cascade_rcnn:
  499. fg_inds = paddle.nonzero(matched_vals >= fg_thresh)
  500. bg_inds = paddle.nonzero(matched_vals < bg_thresh)
  501. else:
  502. matched_vals_np = matched_vals.numpy()
  503. match_labels_np = match_labels.numpy()
  504. # sample fg
  505. fg_inds = paddle.nonzero(matched_vals >= fg_thresh).flatten()
  506. fg_nums = int(np.minimum(fg_rois_per_im, fg_inds.shape[0]))
  507. if (fg_inds.shape[0] > fg_nums) and use_random:
  508. fg_inds = libra_sample_pos(matched_vals_np, match_labels_np,
  509. fg_inds.numpy(), fg_rois_per_im)
  510. fg_inds = fg_inds[:fg_nums]
  511. # sample bg
  512. bg_inds = paddle.nonzero(matched_vals < bg_thresh).flatten()
  513. bg_nums = int(np.minimum(rois_per_image - fg_nums, bg_inds.shape[0]))
  514. if (bg_inds.shape[0] > bg_nums) and use_random:
  515. bg_inds = libra_sample_neg(
  516. matched_vals_np,
  517. match_labels_np,
  518. bg_inds.numpy(),
  519. bg_rois_per_im,
  520. num_bins=num_bins,
  521. bg_thresh=bg_thresh)
  522. bg_inds = bg_inds[:bg_nums]
  523. sampled_inds = paddle.concat([fg_inds, bg_inds])
  524. gt_classes = paddle.gather(gt_classes, matches)
  525. gt_classes = paddle.where(match_labels == 0,
  526. paddle.ones_like(gt_classes) * num_classes,
  527. gt_classes)
  528. gt_classes = paddle.where(match_labels == -1,
  529. paddle.ones_like(gt_classes) * -1, gt_classes)
  530. sampled_gt_classes = paddle.gather(gt_classes, sampled_inds)
  531. return sampled_inds, sampled_gt_classes
  532. def libra_generate_proposal_target(rpn_rois,
  533. gt_classes,
  534. gt_boxes,
  535. batch_size_per_im,
  536. fg_fraction,
  537. fg_thresh,
  538. bg_thresh,
  539. num_classes,
  540. use_random=True,
  541. is_cascade_rcnn=False,
  542. max_overlaps=None,
  543. num_bins=3):
  544. rois_with_gt = []
  545. tgt_labels = []
  546. tgt_bboxes = []
  547. sampled_max_overlaps = []
  548. tgt_gt_inds = []
  549. new_rois_num = []
  550. for i, rpn_roi in enumerate(rpn_rois):
  551. max_overlap = max_overlaps[i] if is_cascade_rcnn else None
  552. gt_bbox = gt_boxes[i]
  553. gt_class = paddle.squeeze(gt_classes[i], axis=-1)
  554. if is_cascade_rcnn:
  555. rpn_roi = filter_roi(rpn_roi, max_overlap)
  556. bbox = paddle.concat([rpn_roi, gt_bbox])
  557. # Step1: label bbox
  558. matches, match_labels, matched_vals = libra_label_box(
  559. bbox, gt_bbox, gt_class, fg_thresh, bg_thresh, num_classes)
  560. # Step2: sample bbox
  561. sampled_inds, sampled_gt_classes = libra_sample_bbox(
  562. matches, match_labels, matched_vals, gt_class, batch_size_per_im,
  563. num_classes, fg_fraction, fg_thresh, bg_thresh, num_bins,
  564. use_random, is_cascade_rcnn)
  565. # Step3: make output
  566. rois_per_image = paddle.gather(bbox, sampled_inds)
  567. sampled_gt_ind = paddle.gather(matches, sampled_inds)
  568. sampled_bbox = paddle.gather(gt_bbox, sampled_gt_ind)
  569. sampled_overlap = paddle.gather(matched_vals, sampled_inds)
  570. rois_per_image.stop_gradient = True
  571. sampled_gt_ind.stop_gradient = True
  572. sampled_bbox.stop_gradient = True
  573. sampled_overlap.stop_gradient = True
  574. tgt_labels.append(sampled_gt_classes)
  575. tgt_bboxes.append(sampled_bbox)
  576. rois_with_gt.append(rois_per_image)
  577. sampled_max_overlaps.append(sampled_overlap)
  578. tgt_gt_inds.append(sampled_gt_ind)
  579. new_rois_num.append(paddle.shape(sampled_inds)[0])
  580. new_rois_num = paddle.concat(new_rois_num)
  581. # rois_with_gt, tgt_labels, tgt_bboxes, tgt_gt_inds, new_rois_num
  582. return rois_with_gt, tgt_labels, tgt_bboxes, tgt_gt_inds, new_rois_num