NumPy 是 Python 中用于数值计算的库,它提供了大量的数学函数和工具,用于高效处理大型多维数组。
快速入门
安装 NumPy
- 使用 pip 安装:
pip install numpy
- 使用 pip 安装:
创建数组
import numpy as np
array = np.array([1, 2, 3, 4])
数组操作
- 索引:
array[0]
或array[0:2]
- 追加:
array.append(5)
- 切片:
array[:2]
- 索引:
图像处理
NumPy 在图像处理中有着广泛的应用,以下是一些常用的操作:
- 加载图像:
image = np.array(Image.open('path/to/image.jpg'))
- 获取图像尺寸:
image.shape
- 图像缩放:
resized_image = cv2.resize(image, (new_width, new_height))
示例代码
以下是一个简单的示例,演示如何使用 NumPy 创建一个 3x3 的矩阵并计算其转置:
import numpy as np
# 创建矩阵
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# 计算转置
transposed_matrix = np.transpose(matrix)
print("原始矩阵:")
print(matrix)
print("转置矩阵:")
print(transposed_matrix)
扩展阅读
更多关于 NumPy 的信息和教程,请访问 NumPy 官方文档。
NumPy 图标