general.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. import cv2
  2. import numpy as np
  3. import torch
  4. import torch.nn.functional as F
  5. def crop_mask(masks, boxes):
  6. """
  7. "Crop" predicted masks by zeroing out everything not in the predicted bbox.
  8. Vectorized by Chong (thanks Chong).
  9. Args:
  10. - masks should be a size [n, h, w] tensor of masks
  11. - boxes should be a size [n, 4] tensor of bbox coords in relative point form
  12. """
  13. n, h, w = masks.shape
  14. x1, y1, x2, y2 = torch.chunk(boxes[:, :, None], 4, 1) # x1 shape(1,1,n)
  15. r = torch.arange(w, device=masks.device, dtype=x1.dtype)[None, None, :] # rows shape(1,w,1)
  16. c = torch.arange(h, device=masks.device, dtype=x1.dtype)[None, :, None] # cols shape(h,1,1)
  17. return masks * ((r >= x1) * (r < x2) * (c >= y1) * (c < y2))
  18. def process_mask_upsample(protos, masks_in, bboxes, shape):
  19. """
  20. Crop after upsample.
  21. protos: [mask_dim, mask_h, mask_w]
  22. masks_in: [n, mask_dim], n is number of masks after nms
  23. bboxes: [n, 4], n is number of masks after nms
  24. shape: input_image_size, (h, w)
  25. return: h, w, n
  26. """
  27. c, mh, mw = protos.shape # CHW
  28. masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw)
  29. masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0] # CHW
  30. masks = crop_mask(masks, bboxes) # CHW
  31. return masks.gt_(0.5)
  32. def process_mask(protos, masks_in, bboxes, shape, upsample=False):
  33. """
  34. Crop before upsample.
  35. proto_out: [mask_dim, mask_h, mask_w]
  36. out_masks: [n, mask_dim], n is number of masks after nms
  37. bboxes: [n, 4], n is number of masks after nms
  38. shape:input_image_size, (h, w)
  39. return: h, w, n
  40. """
  41. c, mh, mw = protos.shape # CHW
  42. ih, iw = shape
  43. masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw) # CHW
  44. downsampled_bboxes = bboxes.clone()
  45. downsampled_bboxes[:, 0] *= mw / iw
  46. downsampled_bboxes[:, 2] *= mw / iw
  47. downsampled_bboxes[:, 3] *= mh / ih
  48. downsampled_bboxes[:, 1] *= mh / ih
  49. masks = crop_mask(masks, downsampled_bboxes) # CHW
  50. if upsample:
  51. masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0] # CHW
  52. return masks.gt_(0.5)
  53. def process_mask_native(protos, masks_in, bboxes, shape):
  54. """
  55. Crop after upsample.
  56. protos: [mask_dim, mask_h, mask_w]
  57. masks_in: [n, mask_dim], n is number of masks after nms
  58. bboxes: [n, 4], n is number of masks after nms
  59. shape: input_image_size, (h, w)
  60. return: h, w, n
  61. """
  62. c, mh, mw = protos.shape # CHW
  63. masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw)
  64. gain = min(mh / shape[0], mw / shape[1]) # gain = old / new
  65. pad = (mw - shape[1] * gain) / 2, (mh - shape[0] * gain) / 2 # wh padding
  66. top, left = int(pad[1]), int(pad[0]) # y, x
  67. bottom, right = int(mh - pad[1]), int(mw - pad[0])
  68. masks = masks[:, top:bottom, left:right]
  69. masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0] # CHW
  70. masks = crop_mask(masks, bboxes) # CHW
  71. return masks.gt_(0.5)
  72. def scale_image(im1_shape, masks, im0_shape, ratio_pad=None):
  73. """
  74. img1_shape: model input shape, [h, w]
  75. img0_shape: origin pic shape, [h, w, 3]
  76. masks: [h, w, num]
  77. """
  78. # Rescale coordinates (xyxy) from im1_shape to im0_shape
  79. if ratio_pad is None: # calculate from im0_shape
  80. gain = min(im1_shape[0] / im0_shape[0], im1_shape[1] / im0_shape[1]) # gain = old / new
  81. pad = (im1_shape[1] - im0_shape[1] * gain) / 2, (im1_shape[0] - im0_shape[0] * gain) / 2 # wh padding
  82. else:
  83. pad = ratio_pad[1]
  84. top, left = int(pad[1]), int(pad[0]) # y, x
  85. bottom, right = int(im1_shape[0] - pad[1]), int(im1_shape[1] - pad[0])
  86. if len(masks.shape) < 2:
  87. raise ValueError(f'"len of masks shape" should be 2 or 3, but got {len(masks.shape)}')
  88. masks = masks[top:bottom, left:right]
  89. # masks = masks.permute(2, 0, 1).contiguous()
  90. # masks = F.interpolate(masks[None], im0_shape[:2], mode='bilinear', align_corners=False)[0]
  91. # masks = masks.permute(1, 2, 0).contiguous()
  92. masks = cv2.resize(masks, (im0_shape[1], im0_shape[0]))
  93. if len(masks.shape) == 2:
  94. masks = masks[:, :, None]
  95. return masks
  96. def mask_iou(mask1, mask2, eps=1e-7):
  97. """
  98. mask1: [N, n] m1 means number of predicted objects
  99. mask2: [M, n] m2 means number of gt objects
  100. Note: n means image_w x image_h
  101. return: masks iou, [N, M]
  102. """
  103. intersection = torch.matmul(mask1, mask2.t()).clamp(0)
  104. union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection # (area1 + area2) - intersection
  105. return intersection / (union + eps)
  106. def masks_iou(mask1, mask2, eps=1e-7):
  107. """
  108. mask1: [N, n] m1 means number of predicted objects
  109. mask2: [N, n] m2 means number of gt objects
  110. Note: n means image_w x image_h
  111. return: masks iou, (N, )
  112. """
  113. intersection = (mask1 * mask2).sum(1).clamp(0) # (N, )
  114. union = (mask1.sum(1) + mask2.sum(1))[None] - intersection # (area1 + area2) - intersection
  115. return intersection / (union + eps)
  116. def masks2segments(masks, strategy='largest'):
  117. # Convert masks(n,160,160) into segments(n,xy)
  118. segments = []
  119. for x in masks.int().cpu().numpy().astype('uint8'):
  120. c = cv2.findContours(x, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
  121. if c:
  122. if strategy == 'concat': # concatenate all segments
  123. c = np.concatenate([x.reshape(-1, 2) for x in c])
  124. elif strategy == 'largest': # select largest segment
  125. c = np.array(c[np.array([len(x) for x in c]).argmax()]).reshape(-1, 2)
  126. else:
  127. c = np.zeros((0, 2)) # no segments found
  128. segments.append(c.astype('float32'))
  129. return segments