You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

vision.py 23 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. # -*- coding: utf-8 -*-
  2. from typing import Iterable, Optional, Tuple, Union
  3. import numpy as np
  4. from ..core import _config
  5. from ..core._imperative_rt.core2 import apply
  6. from ..core.ops import builtin
  7. from ..core.tensor import megbrain_graph, utils
  8. from ..core.tensor.utils import astensor1d
  9. from ..tensor import Tensor
  10. from .elemwise import floor
  11. from .math import argsort
  12. from .tensor import broadcast_to, concat, expand_dims, reshape, transpose
  13. __all__ = [
  14. "correlation",
  15. "cvt_color",
  16. "interpolate",
  17. "nms",
  18. "nvof",
  19. "remap",
  20. "roi_align",
  21. "roi_pooling",
  22. "warp_affine",
  23. "warp_perspective",
  24. ]
  25. def cvt_color(inp: Tensor, mode: str = ""):
  26. r"""Convert images from one format to another
  27. Args:
  28. inp: input images.
  29. mode: format mode.
  30. Returns:
  31. convert result.
  32. Note:
  33. There are different supported modes for different combinations of :attr:`~.Tensor.device` and :attr:`~.Tensor.dtype`.
  34. x86/ARM:
  35. float32:
  36. "RGB2GRAY", "RGB2YUV", "YUV2RGB", "GRAY2RGB", "BGR2GRAY"
  37. uint8:
  38. "RGB2GRAY", "RGB2YUV", "YUV2RGB", "GRAY2RGB", "RGBA2RGB", "RGBA2BGR",
  39. "RGBA2GRAY", "RGB2BGR", "BGR2GRAY", "BGR2RGB", "YUV2GRAY_NV21", "YUV2RGB_NV21",
  40. "YUV2BGR_NV21", "YUV2GRAY_NV12", "YUV2RGB_NV12", "YUV2BGR_NV12", "YUV2GRAY_YV12",
  41. "YUV2RGB_YV12", "YUV2BGR_YV12", "YUV2GRAY_YU12", "YUV2RGB_YU12", "YUV2BGR_YU12",
  42. "YCrCb2RGB", "YCrCb2BGR", "BT601_YUV2RGB_NV21", "BT601_YUV2BGR_NV21", "BT601_YUV2RGB_NV12",
  43. "BT601_YUV2BGR_NV12", "BT601_YUV2RGB_YV12", "BT601_YUV2BGR_YV12" ,"BT601_YUV2RGB_YU12",
  44. "BT601_YUV2BGR_YU12"
  45. CUDA:
  46. float32:
  47. "RGB2GRAY", "BGR2GRAY", "RGB2YUV", "YUV2RGB", "GRAY2RGB"
  48. uint8:
  49. "RGB2GRAY", "BGR2GRAY", "RGB2YUV", "YUV2RGB", "GRAY2RGB",
  50. "YUV2GRAY_NV12", "YUV2GRAY_NV21", "YUV2GRAY_YU12"
  51. "YUV2GRAY_YV12", "YUV2RGB_NV12", "YUV2RGB_NV21", "YUV2BGR_NV12"
  52. "YUV2BGR_NV21", "YUV2RGB_YU12", "YUV2RGB_YV12", "YUV2BGR_YU12",
  53. "YUV2BGR_YV12"
  54. Examples:
  55. >>> import numpy as np
  56. >>> x = mge.tensor(np.array([[[[-0.58675045, 1.7526233, 0.10702174]]]]).astype(np.float32))
  57. >>> y = F.vision.cvt_color(x, mode="RGB2GRAY")
  58. >>> y.numpy()
  59. array([[[[0.86555195]]]], dtype=float32)
  60. """
  61. mode = mode.upper() if "YCrCb" not in mode else mode
  62. assert mode in builtin.CvtColor.Mode.__dict__, "unspport mode for cvt_color"
  63. mode = getattr(builtin.CvtColor.Mode, mode)
  64. assert isinstance(mode, builtin.CvtColor.Mode)
  65. op = builtin.CvtColor(mode=mode)
  66. (out,) = apply(op, inp)
  67. return out
  68. def roi_pooling(
  69. inp: Tensor,
  70. rois: Tensor,
  71. output_shape: Union[int, tuple, list],
  72. mode: str = "max",
  73. scale: float = 1.0,
  74. ) -> Tensor:
  75. r"""Applies roi pooling on input feature.
  76. Args:
  77. inp: tensor that represents the input feature, `(N, C, H, W)` images.
  78. rois: `(K, 5)` boxes. First column is the index into N. The other 4 columns are xyxy.
  79. output_shape: `(height, width)` of output rois feature.
  80. mode: "max" or "average", use max/average align just like max/average pooling. Default: "max"
  81. scale: scale the input boxes by this number. Default: 1.0
  82. Returns:
  83. ``K, C, output_shape[0], output_shape[1])`` feature of rois.
  84. Examples:
  85. >>> import numpy as np
  86. >>> np.random.seed(42)
  87. >>> inp = Tensor(np.random.randn(1, 1, 128, 128))
  88. >>> rois = Tensor(np.random.random((4, 5)))
  89. >>> y = F.vision.roi_pooling(inp, rois, (2, 2))
  90. >>> y.numpy()[0].round(decimals=4)
  91. array([[[-0.1383, -0.1383],
  92. [-0.5035, -0.5035]]], dtype=float32)
  93. """
  94. assert mode.lower() in ["max", "average"], "only max/average mode is supported"
  95. if isinstance(output_shape, int):
  96. output_shape = (output_shape, output_shape)
  97. op = builtin.ROIPooling(mode=mode, scale=scale)
  98. result, _ = apply(
  99. op, inp, rois, Tensor(output_shape, dtype="int32", device=inp.device)
  100. )
  101. return result
  102. def correlation(
  103. data1: Tensor,
  104. data2: Tensor,
  105. kernel_size: int = 1,
  106. max_displacement: int = 1,
  107. stride1: int = 1,
  108. stride2: int = 1,
  109. pad_size: int = 0,
  110. is_multiply: bool = True,
  111. ) -> Tensor:
  112. r"""Applies correlation to inputs.
  113. Args:
  114. data1: Input data1 to the correlation. format must be nchw
  115. data2: Input data2 to the correlation. format must be nchw
  116. kernel_size: int (non-negative), optional, default=1) – kernel size for Correlation must be an odd number
  117. max_displacement: int (non-negative), optional, default=1) – Max displacement of Correlation
  118. stride1: int (non-negative), optional, default=1) – stride1 quantize data1 globally
  119. stride2: int (non-negative), optional, default=1) – stride2 quantize data2 within the neighborhood centered around data1
  120. pad_size: int (non-negative), optional, default=0) – pad for Correlation
  121. is_multiply: boolean, optional, default=True) – operation type is either multiplication or absolute difference
  122. """
  123. # Currently correlation only support NCHW mode
  124. format = "NCHW"
  125. op = builtin.Correlation(
  126. format=format,
  127. kernel_size=kernel_size,
  128. max_displacement=max_displacement,
  129. stride1=stride1,
  130. stride2=stride2,
  131. pad_size=pad_size,
  132. is_multiply=is_multiply,
  133. )
  134. result, *_ = apply(op, data1, data2)
  135. return result
  136. def roi_align(
  137. inp: Tensor,
  138. rois: Tensor,
  139. output_shape: Union[int, tuple, list],
  140. mode: str = "average",
  141. spatial_scale: float = 1.0,
  142. sample_points: Union[int, tuple, list] = 2,
  143. aligned: bool = True,
  144. ) -> Tensor:
  145. r"""Applies roi align on input feature.
  146. Args:
  147. inp: tensor that represents the input feature, shape is `(N, C, H, W)`.
  148. rois: `(N, 5)` boxes. First column is the box index. The other 4 columns are ``xyxy``.
  149. output_shape: `(height, width)` shape of output rois feature.
  150. mode: "max" or "average", use max/average align just like max/average pooling. Default: "average"
  151. spatial_scale: scale the input boxes by this number. Default: 1.0
  152. sample_points: number of inputs samples to take for each output sample.
  153. 0 to take samples densely. Default: 2
  154. aligned: wheather to align the input feature, with `aligned=True`,
  155. we first appropriately scale the ROI and then shift it by -0.5. Default: True
  156. Returns:
  157. output tensor.
  158. Examples:
  159. >>> import numpy as np
  160. >>> np.random.seed(42)
  161. >>> inp = Tensor(np.random.randn(1, 1, 128, 128))
  162. >>> rois = Tensor(np.random.random((4, 5)))
  163. >>> y = F.vision.roi_align(inp, rois, (2, 2))
  164. >>> y.numpy()[0].round(decimals=4)
  165. array([[[0.175 , 0.175 ],
  166. [0.1359, 0.1359]]], dtype=float32)
  167. """
  168. if inp.dtype != np.float32:
  169. inp = inp.astype(np.float32)
  170. mode = mode.lower()
  171. assert mode in ["max", "average"], "only max/average mode is supported"
  172. if isinstance(output_shape, int):
  173. output_shape = (output_shape, output_shape)
  174. pooled_height, pooled_width = output_shape
  175. if isinstance(sample_points, int):
  176. sample_points = (sample_points, sample_points)
  177. sample_height, sample_width = sample_points
  178. offset = 0.5 if aligned else 0.0
  179. # Currently roi_align only support NCHW mode
  180. format = "NCHW"
  181. op = builtin.ROIAlign(
  182. mode=mode,
  183. format=format,
  184. spatial_scale=spatial_scale,
  185. offset=offset,
  186. pooled_height=pooled_height,
  187. pooled_width=pooled_width,
  188. sample_height=sample_height,
  189. sample_width=sample_width,
  190. )
  191. result, *_ = apply(op, inp, rois)
  192. return result
  193. def nms(
  194. boxes: Tensor, scores: Tensor, iou_thresh: float, max_output: Optional[int] = None
  195. ) -> Tensor:
  196. r"""Performs non-maximum suppression (NMS) on the boxes according to their intersection-over-union(IoU).
  197. Args:
  198. boxes: tensor of shape `(N, 4)`; the boxes to perform nms on; each box is expected to be in `(x1, y1, x2, y2)` format.
  199. iou_thresh: IoU threshold for overlapping.
  200. scores: tensor of shape `(N,)`, the score of boxes.
  201. max_output: the maximum number of boxes to keep; it is optional if this operator is not traced
  202. otherwise it required to be specified; if it is not specified, all boxes are kept.
  203. Returns:
  204. indices of the elements that have been kept by NMS, sorted by scores.
  205. Note:
  206. max_output should be specified and should have valid positive value under tracing.
  207. Examples:
  208. >>> import numpy as np
  209. >>> x = np.zeros((100,4))
  210. >>> np.random.seed(42)
  211. >>> x[:,:2] = np.random.rand(100,2)*20
  212. >>> x[:,2:] = np.random.rand(100,2)*20 + 100
  213. >>> scores = Tensor(np.random.rand(100))
  214. >>> inp = Tensor(x)
  215. >>> F.vision.nms(inp, scores, iou_thresh=0.7)
  216. Tensor([75 69], dtype=int32, device=xpux:0)
  217. """
  218. assert (
  219. boxes.ndim == 2 and boxes.shape[1] == 4
  220. ), "the expected shape of boxes is (N, 4)"
  221. assert scores.ndim == 1, "the expected shape of scores is (N,)"
  222. assert (
  223. boxes.shape[0] == scores.shape[0]
  224. ), "number of boxes and scores are not matched"
  225. boxes = boxes.detach()
  226. scores = scores.detach()
  227. sorted_idx = argsort(scores, descending=True)
  228. boxes = boxes[sorted_idx]
  229. if max_output is None:
  230. max_output = boxes.shape[0]
  231. op = builtin.NMSKeep(iou_thresh, max_output)
  232. inp = (boxes.reshape(1, -1, 4),)
  233. indices, count = apply(op, *inp)
  234. indices = indices[0][: count[0]]
  235. keep_inds = sorted_idx[indices]
  236. return keep_inds
  237. def remap(
  238. inp: Tensor,
  239. map_xy: Tensor,
  240. border_mode: str = "replicate",
  241. scalar: float = 0.0,
  242. interp_mode: str = "linear",
  243. ) -> Tensor:
  244. r"""Applies remap transformation to batched 2D images.
  245. The input images are transformed to the output images by the tensor map_xy.
  246. The output's H and W are same as map_xy's H and W.
  247. Args:
  248. inp: input image
  249. map_xy: transformation matrix, its shape represents [batch_size, H, W, 2]. map_xy's H and W are the same as output's H and W.
  250. For each output location output[n, h, w], the vector map_xy[n, h, w] specifies input pixel location x and y, which are
  251. used to interpolate the output value output[n, h, w]. In the case of 2D inputs, map_xy[n, h, w] specifies the x, y pixel
  252. locations for interpolating output[n, h, w], map_xy specifies the sampling pixel locations normalized by the inp spatial
  253. dimensions. Therefore, it should have most values in the range of [0, h - 1) and [0, w - 1).
  254. border_mode: pixel extrapolation method. Default: "replicate". Currently also support "constant", "reflect", "reflect_101", "wrap".
  255. "replicate": repeatedly fills the edge pixel values of the duplicate image, expanding the new boundary pixel values with
  256. the edge pixel values.
  257. "constant": fills the edges of the image with a fixed numeric value.
  258. scalar: value used in case of a constant border. Default: 0
  259. interp_mode: interpolation methods. Default: "linear". Currently also support "nearest" mode.
  260. Returns:
  261. output tensor.
  262. Examples:
  263. >>> import numpy as np
  264. >>> inp_shape = (1, 1, 4, 4)
  265. >>> inp = Tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  266. >>> map_xy_shape = (1, 2, 2, 2)
  267. >>> map_xy = Tensor(np.array([[[1., 0.],[0., 1.]],
  268. ... [[0., 1.],[0., 1.]]],
  269. ... dtype=np.float32).reshape(map_xy_shape))
  270. >>> out = F.vision.remap(inp, map_xy)
  271. >>> out.numpy()
  272. array([[[[1., 4.],
  273. [4., 4.]]]], dtype=float32)
  274. """
  275. format = "NCHW"
  276. op = builtin.Remap(
  277. imode=interp_mode, border_type=border_mode, format=format, scalar=scalar
  278. )
  279. assert isinstance(inp, (Tensor, megbrain_graph.VarNode)), "inp must be Tensor type"
  280. (result,) = apply(op, inp, map_xy)
  281. return result
  282. def warp_affine(
  283. inp: Tensor,
  284. mat: Tensor,
  285. out_shape: Union[Tuple[int, int], int, Tensor],
  286. border_mode: str = "replicate",
  287. border_val: float = 0.0,
  288. format: str = "NHWC",
  289. interp_mode: str = "linear",
  290. ) -> Tensor:
  291. r"""Batched affine transform on 2D images.
  292. Args:
  293. inp: input image.
  294. mat: `(batch, 2, 3)` transformation matrix.
  295. out_shape: output tensor shape.
  296. border_mode: pixel extrapolation method.
  297. Default: "wrap". Currently "constant", "reflect",
  298. "reflect_101", "isolated", "wrap", "replicate", "transparent" are supported.
  299. border_val: value used in case of a constant border. Default: 0
  300. format: NHWC" as default based on historical concerns,
  301. "NCHW" is also supported. Default: "NHWC".
  302. interp_mode: interpolation methods. Could be "linear", "nearest", "cubic", "area".
  303. Default: "linear".
  304. Returns:
  305. output tensor.
  306. Note:
  307. Here all available options for params are listed,
  308. however it does not mean that you can use all the combinations.
  309. On different platforms, different combinations are supported.
  310. ``warp_affine`` only support forward inference, Please refer to ``warp_perspective`` if backward is needed.
  311. """
  312. op = builtin.WarpAffine(
  313. border_mode=border_mode,
  314. border_val=border_val,
  315. format=format,
  316. imode=interp_mode,
  317. )
  318. out_shape = utils.astensor1d(out_shape, inp, dtype="int32", device=inp.device)
  319. (result,) = apply(op, inp, mat, out_shape)
  320. return result
  321. def warp_perspective(
  322. inp: Tensor,
  323. mat: Tensor,
  324. out_shape: Union[Tuple[int, int], int, Tensor],
  325. mat_idx: Optional[Union[Iterable[int], Tensor]] = None,
  326. border_mode: str = "replicate",
  327. border_val: float = 0.0,
  328. format: str = "NCHW",
  329. interp_mode: str = "linear",
  330. ) -> Tensor:
  331. r"""Applies perspective transformation to batched 2D images.
  332. The input images are transformed to the output images by the transformation matrix:
  333. .. math::
  334. \text{output}(n, c, h, w) = \text{input} \left( n, c,
  335. \frac{M_{00}w + M_{01}h + M_{02}}{M_{20}w + M_{21}h + M_{22}},
  336. \frac{M_{10}w + M_{11}h + M_{12}}{M_{20}w + M_{21}h + M_{22}}
  337. \right)
  338. Optionally, we can set `mat_idx` to assign different transformations to the same image,
  339. otherwise the input images and transformations should be one-to-one correnspondence.
  340. Args:
  341. inp: input image.
  342. mat: batch, 3, 3)` transformation matrix.
  343. out_shape: h, w)` size of the output image.
  344. mat_idx: batch, )` image batch idx assigned to each matrix. Default: None
  345. border_mode: pixel extrapolation method.
  346. Default: "replicate". Currently also support "constant", "reflect",
  347. "reflect_101", "wrap".
  348. border_val: value used in case of a constant border. Default: 0
  349. format: NHWC" is also supported. Default: "NCHW".
  350. interp_mode: interpolation methods.
  351. Default: "linear". Currently only support "linear" mode.
  352. Returns:
  353. output tensor.
  354. Note:
  355. The transformation matrix is the inverse of that used by `cv2.warpPerspective`.
  356. Examples:
  357. >>> import numpy as np
  358. >>> inp_shape = (1, 1, 4, 4)
  359. >>> x = Tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  360. >>> M_shape = (1, 3, 3)
  361. >>> # M defines a translation: dst(1, 1, h, w) = rst(1, 1, h+1, w+1)
  362. >>> M = Tensor(np.array([[1., 0., 1.],
  363. ... [0., 1., 1.],
  364. ... [0., 0., 1.]], dtype=np.float32).reshape(M_shape))
  365. >>> out = F.vision.warp_perspective(x, M, (2, 2))
  366. >>> out.numpy()
  367. array([[[[ 5., 6.],
  368. [ 9., 10.]]]], dtype=float32)
  369. """
  370. if inp.dtype == np.float32:
  371. mat = mat.astype("float32")
  372. if inp.dtype == np.float16:
  373. inp = inp.astype("float32")
  374. op = builtin.WarpPerspective(
  375. imode=interp_mode, bmode=border_mode, format=format, border_val=border_val
  376. )
  377. out_shape = astensor1d(out_shape, inp, dtype="int32", device=inp.device)
  378. if mat_idx is not None:
  379. mat_idx = astensor1d(mat_idx, inp, dtype="int32", device=inp.device)
  380. (result,) = apply(op, inp, mat, mat_idx, out_shape)
  381. return result
  382. (result,) = apply(op, inp, mat, out_shape)
  383. return result
  384. def interpolate(
  385. inp: Tensor,
  386. size: Optional[Union[int, Tuple[int, int]]] = None,
  387. scale_factor: Optional[Union[float, Tuple[float, float]]] = None,
  388. mode: str = "bilinear",
  389. align_corners: Optional[bool] = None,
  390. ) -> Tensor:
  391. r"""Down/up samples the input tensor to either the given size or with the given scale_factor. ``size`` can not coexist with ``scale_factor``.
  392. Args:
  393. inp: input tensor.
  394. size: size of the output tensor. Default: None
  395. scale_factor: scaling factor of the output tensor. Default: None
  396. mode: interpolation methods, acceptable values are:
  397. "bilinear", "linear", "bicubic" and "nearest". Default: "bilinear"
  398. align_corners: This only has an effect when `mode`
  399. is "bilinear" or "linear". Geometrically, we consider the pixels of the input
  400. and output as squares rather than points. If set to ``True``, the input
  401. and output tensors are aligned by the center points of their corner
  402. pixels, preserving the values at the corner pixels. If set to ``False``,
  403. the input and output tensors are aligned by the corner points of their
  404. corner pixels, and the interpolation uses edge value padding for
  405. out-of-boundary values, making this operation *independent* of input size
  406. Returns:
  407. output tensor.
  408. Examples:
  409. >>> import numpy as np
  410. >>> x = Tensor(np.arange(1, 5, dtype=np.float32).reshape(1, 1, 2, 2))
  411. >>> out = F.vision.interpolate(x, [4, 4], align_corners=False)
  412. >>> out.numpy()
  413. array([[[[1. , 1.25, 1.75, 2. ],
  414. [1.5 , 1.75, 2.25, 2.5 ],
  415. [2.5 , 2.75, 3.25, 3.5 ],
  416. [3. , 3.25, 3.75, 4. ]]]], dtype=float32)
  417. >>> out2 = F.vision.interpolate(x, scale_factor=2.)
  418. >>> np.testing.assert_allclose(out.numpy(), out2.numpy())
  419. """
  420. mode = mode.lower()
  421. if mode not in ["bilinear", "linear", "bicubic", "nearest"]:
  422. raise ValueError("unsupported interpolate mode: {}".format(mode))
  423. if mode not in ["bilinear", "linear"]:
  424. if align_corners is not None:
  425. raise ValueError(
  426. "align_corners option can only be set in the bilinear/linear interpolating mode"
  427. )
  428. else:
  429. if align_corners is None:
  430. align_corners = False
  431. if mode == "linear":
  432. inp = expand_dims(inp, 3)
  433. if inp.ndim != 4:
  434. raise ValueError("shape of input tensor must correspond to the operartion mode")
  435. def get_dsize(scale_factor):
  436. if isinstance(scale_factor, (float, int)):
  437. scale_factor = float(scale_factor)
  438. if mode == "linear":
  439. scale_factor = (scale_factor, float(1))
  440. else:
  441. scale_factor = (scale_factor, scale_factor)
  442. else:
  443. if mode == "linear":
  444. raise ValueError(
  445. "under linear mode, scale_factor can only be single value"
  446. )
  447. assert len(scale_factor) == 2, "shape of scale_factor must be equal to (2, )"
  448. assert isinstance(scale_factor[0], float) and isinstance(
  449. scale_factor[1], float
  450. ), "scale_factor must be float type"
  451. dsize = tuple(
  452. floor(
  453. Tensor(
  454. inp.shape[i + 2] * scale_factor[i],
  455. dtype="float32",
  456. device=inp.device,
  457. )
  458. )
  459. for i in range(2)
  460. )
  461. dsize = concat([dsize[0], dsize[1]], axis=0)
  462. return dsize
  463. if size is None:
  464. if scale_factor is None:
  465. raise ValueError("scale_factor must not be None when size is None")
  466. dsize = get_dsize(scale_factor)
  467. else:
  468. if scale_factor is not None:
  469. raise ValueError("scale_factor must be None when size is provided")
  470. if isinstance(size, int):
  471. size = (size, 1)
  472. else:
  473. if mode == "linear":
  474. raise ValueError("under linear mode, size can only be single value")
  475. dsize = size
  476. if not align_corners:
  477. # fastpath for interpolate
  478. mode_map = {
  479. "linear": "linear",
  480. "bilinear": "linear",
  481. "nearest": "nearest",
  482. "bicubic": "cubic",
  483. }
  484. if inp.dtype == np.float16:
  485. inp = inp.astype("float32")
  486. # Currently resize only support NCHW mode
  487. format = "NCHW"
  488. op = builtin.Resize(imode=mode_map[mode], format=format)
  489. shape = astensor1d(dsize, inp, dtype="int32", device=inp.device)
  490. (ret,) = apply(op, inp, shape)
  491. else:
  492. assert mode in [
  493. "linear",
  494. "bilinear",
  495. ], "align_corners only support linear or bilinear mode"
  496. oh, ow = dsize[0], dsize[1]
  497. ih, iw = inp.shape[2], inp.shape[3]
  498. hscale = (ih - 1.0) / (oh - 1.0)
  499. wscale = 1.0 * iw / ow
  500. if mode != "linear":
  501. wscale = (iw - 1.0) / (ow - 1.0)
  502. row0 = concat(
  503. [
  504. Tensor(wscale, dtype="float32", device=inp.device),
  505. Tensor([0, 0], dtype="float32", device=inp.device),
  506. ],
  507. axis=0,
  508. ).reshape(1, 3)
  509. zeros = Tensor([0], dtype="float32", device=inp.device)
  510. row1 = concat(
  511. [zeros, Tensor(hscale, dtype="float32", device=inp.device), zeros], axis=0,
  512. ).reshape(1, 3)
  513. weight = concat(
  514. [row0, row1, Tensor([[0, 0, 1]], dtype="float32", device=inp.device)],
  515. axis=0,
  516. ).reshape(1, 3, 3)
  517. weight = broadcast_to(weight, (inp.shape[0], 3, 3))
  518. ret = warp_perspective(inp, weight, dsize, interp_mode="linear")
  519. if mode == "linear":
  520. ret = reshape(ret, ret.shape[0:3])
  521. return ret
  522. def nvof(src: Tensor, precision: int = 1) -> Tensor:
  523. r"""Implements NVIDIA Optical Flow SDK.
  524. Args:
  525. src: input tensor with shape (n, t, h, w, c4) and unit8 dtype.
  526. precision: 0:NV_OF_PERF_LEVEL_SLOW 1:NV_OF_PERF_LEVEL_MEDIUM 2:NV_OF_PERF_LEVEL_FAST.
  527. Returns:
  528. output tensor with shape: ``(n, t-1, (h+out_grid_size-1)//out_grid_size, (w+out_grid_size-1)//out_grid_size, c2)``.
  529. By default, out_grid_size = 4. dtype: int16.
  530. """
  531. assert src.ndim == 5 and src.shape[4] == 4
  532. src = src.detach()
  533. op = builtin.NvOf(precision=precision)
  534. return apply(op, src)[0]