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

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

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台