opencv学习笔记05-numpy 介绍

opencv 简易笔记 5--numpy 介绍

1.numpy 介绍

NumPy(Numerical Python)是 Python 的一种开源的数值计算扩展。这种工具可用来存储和处理大型矩阵,比 Python 自身的嵌套列表(nested list structure)结构要高效的多(该结构也可以用来表示矩阵(matrix)),支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。

一个用 python 实现的科学计算,包括:1、一个强大的 N 维数组对象 Array;2、比较成熟的(广播)函数库;3、用于整合 C/C++和 Fortran 代码的工具包;4、实用的线性代数、傅里叶变换和随机数生成函数。numpy 和稀疏矩阵运算包 scipy 配合使用更加方便。

numpy 支持的数据类型比 Python 内置的类型要多很多,基本上可以和 C 语言的数据类型对应上,其中部分类型对应为 Python 内置的类型。下表列举了常用 NumPy 基本类型。


numpy 的数值类型实际上是 dtype 对象的实例,并对应唯一的字符,包括 np.bool_,np.int32,np.float32,等等。在 opencv 中通常使用 np.uint8,因为刚好对应 0-255.

2.相关函数

2.1 numpy.array() -> ndarray

创建数组。

a = numpy.array([1, 2, 3])
b = numpy.array([[1, 2, 3], [4, 5, 6]])

2.2 numpy.zeros(shape, dtype, order, *, like) -> ndarray

c = numpy.zeros((8, 8, 3), numpy.uint8)

创建一个全是 0 的矩阵。
(1) shape : int or tuple of ints,opencv 中最好是 3 元组,(8,8,3), 3 为 3 通道
  Shape of the new array, e.g., (2, 3) or 2.
(2) dtype : data-type, optional
  The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64. e.g., numpy.uint8
(3) order : {'C', 'F'}, optional, default: 'C'
  Whether to store multi-dimensional data in row-major (C-style) or column-major(Fortran-style) order in memory.
(4) like : array_like

2.3 numpy.full(shape, fill_value, dtype, order, *, like) -> ndarray

d = numpy.full((8, 8), 255, numpy.uint8)

Return a new array of given shape and type, filled with fill_value.

(1) shape : int or sequence of ints
  Shape of the new array, e.g., (2, 3) or 2.
(2) fill_value : scalar or array_like
  Fill value.
(3) dtype : data-type, optional
  The desired data-type for the array The default, None, means
  np.array(fill_value).dtype.
(4) order : {'C', 'F'}, optional
  Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory.

2.4 numpy.identity(n, dytpe, *, like) -> ndarray

e = numpy.identity(8, numpy.uint8)

The identity array is a square array with ones on the main diagonal.

(1) n : int
  Number of rows (and columns) in n x n output.
(2) dtype : data-type, optional
  Data-type of the output. Defaults to float.

2.5 numpy.eye(N, M, k, dytpe, order, *, like) -> ndarray[Any, Any]

f = numpy.eye(N=5, M=6, k=0, dtype=numpy.uint8)

Return a 2-D array with ones on the diagonal and zeros elsewhere.

(1) N : int
  Number of rows in the output.
(2) M : int, optional
  Number of columns in the output. If None, defaults to N.
(3) k : int, optional
  Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal.
(4) dtype : data-type, optional
  Data-type of the returned array.
(5) order : {'C', 'F'}, optional
  Whether the output should be stored in row-major (C-style) or column-major (Fortran-style) order in memory.

posted @ 2023-06-02 17:32  (⊃・ᴥ・)つ  阅读(22)  评论(0编辑  收藏  举报