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 24 kB

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