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

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

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