crop3d.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. # LICENSE HEADER MANAGED BY add-license-header
  2. #
  3. # Copyright 2018 Kornia Team
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. from typing import Tuple
  18. import torch
  19. from kornia.geometry.bbox import infer_bbox_shape3d, validate_bbox3d
  20. from .imgwarp import get_perspective_transform3d, warp_affine3d
  21. __all__ = ["center_crop3d", "crop_and_resize3d", "crop_by_boxes3d", "crop_by_transform_mat3d"]
  22. def crop_and_resize3d(
  23. tensor: torch.Tensor,
  24. boxes: torch.Tensor,
  25. size: Tuple[int, int, int],
  26. interpolation: str = "bilinear",
  27. align_corners: bool = False,
  28. ) -> torch.Tensor:
  29. r"""Extract crops from 3D volumes (5D tensor) and resize them.
  30. Args:
  31. tensor: the 3D volume tensor with shape (B, C, D, H, W).
  32. boxes: a tensor with shape (B, 8, 3) containing the coordinates of the bounding boxes
  33. to be extracted. The tensor must have the shape of Bx8x3, where each box is defined in the clockwise
  34. order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,
  35. back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in x, y, z order.
  36. size: a tuple with the height and width that will be
  37. used to resize the extracted patches.
  38. interpolation: Interpolation flag.
  39. align_corners: mode for grid_generation.
  40. Returns:
  41. tensor containing the patches with shape (Bx)CxN1xN2xN3.
  42. Example:
  43. >>> input = torch.arange(64, dtype=torch.float32).view(1, 1, 4, 4, 4)
  44. >>> input
  45. tensor([[[[[ 0., 1., 2., 3.],
  46. [ 4., 5., 6., 7.],
  47. [ 8., 9., 10., 11.],
  48. [12., 13., 14., 15.]],
  49. <BLANKLINE>
  50. [[16., 17., 18., 19.],
  51. [20., 21., 22., 23.],
  52. [24., 25., 26., 27.],
  53. [28., 29., 30., 31.]],
  54. <BLANKLINE>
  55. [[32., 33., 34., 35.],
  56. [36., 37., 38., 39.],
  57. [40., 41., 42., 43.],
  58. [44., 45., 46., 47.]],
  59. <BLANKLINE>
  60. [[48., 49., 50., 51.],
  61. [52., 53., 54., 55.],
  62. [56., 57., 58., 59.],
  63. [60., 61., 62., 63.]]]]])
  64. >>> boxes = torch.tensor([[
  65. ... [1., 1., 1.],
  66. ... [3., 1., 1.],
  67. ... [3., 3., 1.],
  68. ... [1., 3., 1.],
  69. ... [1., 1., 2.],
  70. ... [3., 1., 2.],
  71. ... [3., 3., 2.],
  72. ... [1., 3., 2.],
  73. ... ]]) # 1x8x3
  74. >>> crop_and_resize3d(input, boxes, (2, 2, 2), align_corners=True)
  75. tensor([[[[[21.0000, 23.0000],
  76. [29.0000, 31.0000]],
  77. <BLANKLINE>
  78. [[37.0000, 39.0000],
  79. [45.0000, 47.0000]]]]])
  80. """
  81. if not isinstance(tensor, (torch.Tensor)):
  82. raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")
  83. if not isinstance(boxes, (torch.Tensor)):
  84. raise TypeError(f"Input boxes type is not a torch.Tensor. Got {type(boxes)}")
  85. if not isinstance(size, (tuple, list)) and len(size) != 3:
  86. raise ValueError(f"Input size must be a tuple/list of length 3. Got {size}")
  87. if len(tensor.shape) != 5:
  88. raise AssertionError(f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}.")
  89. # unpack input data
  90. dst_d, dst_h, dst_w = size[0], size[1], size[2]
  91. # [x, y, z] origin
  92. # from front to back
  93. # top-left, top-right, bottom-right, bottom-left
  94. points_src: torch.Tensor = boxes
  95. # [x, y, z] destination
  96. # from front to back
  97. # top-left, top-right, bottom-right, bottom-left
  98. points_dst: torch.Tensor = torch.tensor(
  99. [
  100. [
  101. [0, 0, 0],
  102. [dst_w - 1, 0, 0],
  103. [dst_w - 1, dst_h - 1, 0],
  104. [0, dst_h - 1, 0],
  105. [0, 0, dst_d - 1],
  106. [dst_w - 1, 0, dst_d - 1],
  107. [dst_w - 1, dst_h - 1, dst_d - 1],
  108. [0, dst_h - 1, dst_d - 1],
  109. ]
  110. ],
  111. dtype=tensor.dtype,
  112. device=tensor.device,
  113. ).expand(points_src.shape[0], -1, -1)
  114. return crop_by_boxes3d(tensor, points_src, points_dst, interpolation, align_corners)
  115. def center_crop3d(
  116. tensor: torch.Tensor, size: Tuple[int, int, int], interpolation: str = "bilinear", align_corners: bool = True
  117. ) -> torch.Tensor:
  118. r"""Crop the 3D volumes (5D tensor) at the center.
  119. Args:
  120. tensor: the 3D volume tensor with shape (B, C, D, H, W).
  121. size: a tuple with the expected depth, height and width
  122. of the output patch.
  123. interpolation: Interpolation flag.
  124. align_corners : mode for grid_generation.
  125. Returns:
  126. the output tensor with patches.
  127. Examples:
  128. >>> input = torch.arange(64, dtype=torch.float32).view(1, 1, 4, 4, 4)
  129. >>> input
  130. tensor([[[[[ 0., 1., 2., 3.],
  131. [ 4., 5., 6., 7.],
  132. [ 8., 9., 10., 11.],
  133. [12., 13., 14., 15.]],
  134. <BLANKLINE>
  135. [[16., 17., 18., 19.],
  136. [20., 21., 22., 23.],
  137. [24., 25., 26., 27.],
  138. [28., 29., 30., 31.]],
  139. <BLANKLINE>
  140. [[32., 33., 34., 35.],
  141. [36., 37., 38., 39.],
  142. [40., 41., 42., 43.],
  143. [44., 45., 46., 47.]],
  144. <BLANKLINE>
  145. [[48., 49., 50., 51.],
  146. [52., 53., 54., 55.],
  147. [56., 57., 58., 59.],
  148. [60., 61., 62., 63.]]]]])
  149. >>> center_crop3d(input, (2, 2, 2), align_corners=True)
  150. tensor([[[[[21.0000, 22.0000],
  151. [25.0000, 26.0000]],
  152. <BLANKLINE>
  153. [[37.0000, 38.0000],
  154. [41.0000, 42.0000]]]]])
  155. """
  156. if not isinstance(tensor, torch.Tensor):
  157. raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")
  158. if len(tensor.shape) != 5:
  159. raise AssertionError(f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}.")
  160. if not isinstance(size, (tuple, list)) and len(size) == 3:
  161. raise ValueError(f"Input size must be a tuple/list of length 3. Got {size}")
  162. # unpack input sizes
  163. dst_d, dst_h, dst_w = size
  164. src_d, src_h, src_w = tensor.shape[-3:]
  165. # compute start/end offsets
  166. dst_d_half = dst_d / 2
  167. dst_h_half = dst_h / 2
  168. dst_w_half = dst_w / 2
  169. src_d_half = src_d / 2
  170. src_h_half = src_h / 2
  171. src_w_half = src_w / 2
  172. start_x = src_w_half - dst_w_half
  173. start_y = src_h_half - dst_h_half
  174. start_z = src_d_half - dst_d_half
  175. end_x = start_x + dst_w - 1
  176. end_y = start_y + dst_h - 1
  177. end_z = start_z + dst_d - 1
  178. # [x, y, z] origin
  179. # top-left-front, top-right-front, bottom-right-front, bottom-left-front
  180. # top-left-back, top-right-back, bottom-right-back, bottom-left-back
  181. points_src: torch.Tensor = torch.tensor(
  182. [
  183. [
  184. [start_x, start_y, start_z],
  185. [end_x, start_y, start_z],
  186. [end_x, end_y, start_z],
  187. [start_x, end_y, start_z],
  188. [start_x, start_y, end_z],
  189. [end_x, start_y, end_z],
  190. [end_x, end_y, end_z],
  191. [start_x, end_y, end_z],
  192. ]
  193. ],
  194. device=tensor.device,
  195. )
  196. # [x, y, z] destination
  197. # top-left-front, top-right-front, bottom-right-front, bottom-left-front
  198. # top-left-back, top-right-back, bottom-right-back, bottom-left-back
  199. points_dst: torch.Tensor = torch.tensor(
  200. [
  201. [
  202. [0, 0, 0],
  203. [dst_w - 1, 0, 0],
  204. [dst_w - 1, dst_h - 1, 0],
  205. [0, dst_h - 1, 0],
  206. [0, 0, dst_d - 1],
  207. [dst_w - 1, 0, dst_d - 1],
  208. [dst_w - 1, dst_h - 1, dst_d - 1],
  209. [0, dst_h - 1, dst_d - 1],
  210. ]
  211. ],
  212. device=tensor.device,
  213. ).expand(points_src.shape[0], -1, -1)
  214. return crop_by_boxes3d(
  215. tensor, points_src.to(tensor.dtype), points_dst.to(tensor.dtype), interpolation, align_corners
  216. )
  217. def crop_by_boxes3d(
  218. tensor: torch.Tensor,
  219. src_box: torch.Tensor,
  220. dst_box: torch.Tensor,
  221. interpolation: str = "bilinear",
  222. align_corners: bool = False,
  223. ) -> torch.Tensor:
  224. """Perform crop transform on 3D volumes (5D tensor) by bounding boxes.
  225. Given an input tensor, this function selected the interested areas by the provided bounding boxes (src_box).
  226. Then the selected areas would be fitted into the targeted bounding boxes (dst_box) by a perspective transformation.
  227. So far, the ragged tensor is not supported by PyTorch right now. This function hereby requires the bounding boxes
  228. in a batch must be rectangles with same width, height and depth.
  229. Args:
  230. tensor : the 3D volume tensor with shape (B, C, D, H, W).
  231. src_box : a tensor with shape (B, 8, 3) containing the coordinates of the bounding boxes
  232. to be extracted. The tensor must have the shape of Bx8x3, where each box is defined in the clockwise
  233. order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,
  234. back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in x, y, z order.
  235. dst_box: a tensor with shape (B, 8, 3) containing the coordinates of the bounding boxes
  236. to be placed. The tensor must have the shape of Bx8x3, where each box is defined in the clockwise
  237. order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,
  238. back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in x, y, z order.
  239. interpolation: Interpolation flag.
  240. align_corners: mode for grid_generation.
  241. Returns:
  242. the output tensor with patches.
  243. Examples:
  244. >>> input = torch.tensor([[[
  245. ... [[ 0., 1., 2., 3.],
  246. ... [ 4., 5., 6., 7.],
  247. ... [ 8., 9., 10., 11.],
  248. ... [12., 13., 14., 15.]],
  249. ... [[16., 17., 18., 19.],
  250. ... [20., 21., 22., 23.],
  251. ... [24., 25., 26., 27.],
  252. ... [28., 29., 30., 31.]],
  253. ... [[32., 33., 34., 35.],
  254. ... [36., 37., 38., 39.],
  255. ... [40., 41., 42., 43.],
  256. ... [44., 45., 46., 47.]]]]])
  257. >>> src_box = torch.tensor([[
  258. ... [1., 1., 1.],
  259. ... [3., 1., 1.],
  260. ... [3., 3., 1.],
  261. ... [1., 3., 1.],
  262. ... [1., 1., 2.],
  263. ... [3., 1., 2.],
  264. ... [3., 3., 2.],
  265. ... [1., 3., 2.],
  266. ... ]]) # 1x8x3
  267. >>> dst_box = torch.tensor([[
  268. ... [0., 0., 0.],
  269. ... [2., 0., 0.],
  270. ... [2., 2., 0.],
  271. ... [0., 2., 0.],
  272. ... [0., 0., 1.],
  273. ... [2., 0., 1.],
  274. ... [2., 2., 1.],
  275. ... [0., 2., 1.],
  276. ... ]]) # 1x8x3
  277. >>> crop_by_boxes3d(input, src_box, dst_box, interpolation='nearest', align_corners=True)
  278. tensor([[[[[21., 22., 23.],
  279. [25., 26., 27.],
  280. [29., 30., 31.]],
  281. <BLANKLINE>
  282. [[37., 38., 39.],
  283. [41., 42., 43.],
  284. [45., 46., 47.]]]]])
  285. """
  286. validate_bbox3d(src_box)
  287. validate_bbox3d(dst_box)
  288. if len(tensor.shape) != 5:
  289. raise AssertionError(f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}.")
  290. # compute transformation between points and warp
  291. # Note: Tensor.dtype must be float. "solve_cpu" not implemented for 'Long'
  292. dst_trans_src: torch.Tensor = get_perspective_transform3d(src_box.to(tensor.dtype), dst_box.to(tensor.dtype))
  293. # simulate broadcasting
  294. dst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1).type_as(tensor)
  295. bbox = infer_bbox_shape3d(dst_box)
  296. if not ((bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all() and (bbox[2] == bbox[2][0]).all()):
  297. raise AssertionError(
  298. "Cropping height, width and depth must be exact same in a batch."
  299. f"Got height {bbox[0]}, width {bbox[1]} and depth {bbox[2]}."
  300. )
  301. patches: torch.Tensor = crop_by_transform_mat3d(
  302. tensor,
  303. dst_trans_src,
  304. (int(bbox[0][0].item()), int(bbox[1][0].item()), int(bbox[2][0].item())),
  305. mode=interpolation,
  306. align_corners=align_corners,
  307. )
  308. return patches
  309. def crop_by_transform_mat3d(
  310. tensor: torch.Tensor,
  311. transform: torch.Tensor,
  312. out_size: Tuple[int, int, int],
  313. mode: str = "bilinear",
  314. padding_mode: str = "zeros",
  315. align_corners: bool = True,
  316. ) -> torch.Tensor:
  317. """Perform crop transform on 3D volumes (5D tensor) given a perspective transformation matrix.
  318. Args:
  319. tensor: the 2D image tensor with shape (B, C, H, W).
  320. transform: a perspective transformation matrix with shape (B, 4, 4).
  321. out_size: size of the output image (depth, height, width).
  322. mode: interpolation mode to calculate output values
  323. ``'bilinear'`` | ``'nearest'``.
  324. padding_mode: padding mode for outside grid values
  325. ``'zeros'`` | ``'border'`` | ``'reflection'``.
  326. align_corners: mode for grid_generation.
  327. Returns:
  328. the output tensor with patches.
  329. """
  330. # simulate broadcasting
  331. dst_trans_src = transform.expand(tensor.shape[0], -1, -1)
  332. patches: torch.Tensor = warp_affine3d(
  333. tensor, dst_trans_src[:, :3, :], out_size, flags=mode, padding_mode=padding_mode, align_corners=align_corners
  334. )
  335. return patches