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

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

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