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

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

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