现从一张图片上去认识numpy
首先导入numpy 和 matplotlib.pylot
import numpy as np
# matplotlib画图的,也可以读取图片
import matplotlib.pyplot as plt
这里给一张cat.jpg的图片
# 图片,音频都叫流(数据流)
# 用matplotlib中的pylot模块中的函数imread()读取图片
# 如果图片有颜色则是三维数组, 如果是黑白的都出来的是二维数组
cat = plt.imread('cat.jpg')
# display是jupyter中的一种打印方式
display(cat,cat.shape)
输出结果:cat 是一组三维数组,cat.shape输出(456, 730, 3),456表示图片的 宽, 730表示图片的长度, 3表示颜色
array([[[231, 186, 131],
[232, 187, 132],
[233, 188, 133],
...,
[100, 54, 54],
[ 92, 48, 47],
[ 85, 43, 44]],
[[232, 187, 132],
[232, 187, 132],
[233, 188, 133],
...,
[100, 54, 54],
[ 92, 48, 47],
[ 84, 42, 43]],
[[232, 187, 132],
[233, 188, 133],
[233, 188, 133],
...,
[ 99, 53, 53],
[ 91, 47, 46],
[ 83, 41, 42]],
...,
[[199, 119, 82],
[199, 119, 82],
[200, 120, 83],
...,
[189, 99, 65],
[187, 97, 63],
[187, 97, 63]],
[[199, 119, 82],
[199, 119, 82],
[199, 119, 82],
...,
[188, 98, 64],
[186, 96, 62],
[188, 95, 62]],
[[199, 119, 82],
[199, 119, 82],
[199, 119, 82],
...,
[188, 98, 64],
[188, 95, 62],
[188, 95, 62]]], dtype=uint8)
(456, 730, 3)
# cat.shape输出(456, 730, 3),456表示图片的宽度, 730表示图片的长度, 3表示颜色
cat.shape
(456, 730, 3)
# 刚刚上面用imread方法得到一组数据流赋给变量cat
# 通过imshow()可以把该数据流还原成图片
plt.imshow(cat)
输出:
#RGB 0 255
# cat是numpy.ndarray数组对象
type(cat)
numpy.ndarray
# 因为上读出的cat.jpg是三维数组, 这里创建一个随机的三位数组
# 它也是一张图片
im = np.random.randint(0,255,size=(456,730,3))
im = im.astype(np.float64)
plt.imshow(im)
2 Numpy
numeric python 数字化的python
numpy中最重要的一个形式叫ndarray n 表示的是n个 d dimension 维度 array 数组
Python 本身支持的数值类型有 int
(整型,python2 中存在 long 长整型)、float
(浮点型)、bool
(布尔型) 和 complex
(复数型)。
而 Numpy 支持比 Python 本身更为丰富的数值类型,细分如下:
类型 | 描述 | 取值范围 |
---|---|---|
bool | 布尔类型, | 1 个字节,值为 True 或 False。 |
int | 整数类型, | 通常为 int64 或 int32 。 |
intc | 与 C 里的 int 相同, | 通常为 int32 或 int64。 |
intp | 用于索引, | 通常为 int32 或 int64。 |
int8 | 与MySQL中tinyint 1字节 -2 ^7 ~ 2^7-1 (-128~127) | 字节(从 -128 到 127) |
int16 | 与MySQL中(smallint 2字节 -2 ^15 ~ 2^15-1 (-32768~32765)) | 整数(从 -32768 到 32767) |
int32 | (int 4字节 -2 ^31~ 2^31-1 (-2147483648~2147483647)) | 整数(从 -2147483648 到 2147483647) |
int64 | (bigint 8字节 -2 ^63 ~ 2^63-1) | 整数(从 -9223372036854775808 到 9223372036854775807) |
uint8 | 无符号整数 | (从 0 到 255) unsigned |