Jupyter notebook

shift+enter 执行生效
Z 恢复删除的单元格
按esc键进入命令模式。在命令行模式在,按y m切换markdown和code模式

numpy

科学计算基础库
N维数组对象 array
广播函数功能
线性代数、傅里叶变换、随机数生成

Array(数组)

rank:数组的维数(轴的数量)
axis:保存的数据的维度

列表与数组

共同:一组数据的有序结构
区别:
列表:数据类型可以不同
数组:数据类型相同
优化速度,去除循环步骤
有利于节省运算和存储的空间

对象属性

  1. import numpy as np
  2. a=np.array([[1,2,3,4,5],[1,4,5,6,4],[3,4,2,5,6]])
  3. a.nidm#秩,轴的数量,即维数 2:横轴与纵轴
  4. a.shape#对象的尺度 (3,5)
  5. a.size#对象的个数 15
  6. a.dtype#对象的类型 dtype('int32')
  7. a.itemsize#对象中每个元素的大小,以字节为单位 4

元素类型

草图.png2.png 3.png

基本使用

ndarray在程序中的别名是array

  1. import numpy as np
  2. a=np.array([1,2,3])
  3. type(a)
  4. a.shape #(3,) 一维数组
  5. a=a.reshape((1,-1)) #重塑维数,表示整个数组只有一行,-1 占位符
  6. #索引 从0开始
  7. a[2,0] #第三行第一列 注:a[][] 不可以作为索引
  8. #自带数组
  9. a=np.zeros((2,3))
  10. a=np.ones((2,3))
  11. a=np.full((3,3),0) #全0数组
  12. a=np.eye(3) #单位矩阵
  13. a=np.random.random(3,4) #随机数
  14. #索引和切片
  15. a[ax1,ax2,ax3]
  16. #表示每个维度,用逗号分割,维度中,用:分割
  17. a[1:4:1,,] #起始1,终点4,步长1
  18. a[np.arange(3),1] #第一到三行的第二列
  19. a[a>10]
  20. #数学运算与常用函数
  21. #标量运算
  22. np.add(a,b) #数组各元素相加
  23. np.subtract(a,b)#相减
  24. np.multiply(a,b)#乘法
  25. np.divide(a,b)#除法
  26. np.abs(a) #绝对值
  27. np.square(a) #平方
  28. np.log(a) np.log10(a) #对数
  29. np.ceil(a) np.floor(a) #取整的天花板与地板
  30. np.rint(a) #s四舍五入
  31. np.modf() #小数和整数部分分开返回
  32. np.cos() #三角函数
  33. np.exp() #指数
  34. np.sign() #符号值
  35. np.sqrt(a)#算术平方根
  36. #有两个同型数组a b,求对应位的最大值
  37. np.maximum(a,b) #返回新数组
  38. #针对矩阵的操作
  39. a.dot(b) np.dot(a,b) #矩阵乘法
  40. #常用函数
  41. np.sum(a) #求和所有元素
  42. np.sum(a,axis=0) #对所有列求和
  43. np.sum(a,axis=1) #对行操作
  44. np.mean(a) #平均值
  45. np.random.uniform(3,4) #生成一个在3,4的随机数值
  46. np.tile(a,(2,3))#将a在行上重复两次,在列上重复三次
  47. a.argsort() #对每行从小到大排序 返回的是下标
  48. a.argsort(axis=0) #对列操作
  49. a.T 或者 np.transpose(a) #转置
  50. #广播特性
  51. 自动重复

ndarray的创建方法

  1. #从列表、元组等类型创建
  2. x=np.array([listname,tuplename],dtype=np.float32) #dtype可缺省
  3. #函数创建
  4. np.ones_like(a) #根据数组a的形状生成一个全1数组
  5. np.zeros_like(a)
  6. np.full_like(a,val)#指定值
  7. np.linspace(初始值,结束值,个数)
  8. np.concatenate()#数组合并
  9. import numpy as np
  10. b=np.linspace(1,10,4,endpoint=False)
  11. print(b)
  12. [out]:[1. 3.25 5.5 7.75]

变换

  1. .reshape(shape) #返回shape形状的数组,原数组不变(生成备份)
  2. .resize(shape)#同上,原数组改变
  3. .swapaxes(ax1,ax2)#将数组的两个维度调换
  4. .flatten() #降维,返回一维数组(不改变)
  5. .tolist() #转换生成列表
  6. #swapaxes
  7. import numpy as np
  8. a=np.ones((2,3,4))
  9. a
  10. Out[4]:
  11. array([[[1., 1., 1., 1.],
  12. [1., 1., 1., 1.],
  13. [1., 1., 1., 1.]],
  14. [[1., 1., 1., 1.],
  15. [1., 1., 1., 1.],
  16. [1., 1., 1., 1.]]])
  17. a.swapaxes(0,1)
  18. Out[5]:
  19. array([[[1., 1., 1., 1.],
  20. [1., 1., 1., 1.]],
  21. [[1., 1., 1., 1.],
  22. [1., 1., 1., 1.]],
  23. [[1., 1., 1., 1.],
  24. [1., 1., 1., 1.]]])
  25. #flatten
  26. import numpy as np
  27. a=np.ones((2,3,4),dtype=np.int32)
  28. b=a.flatten()
  29. print(b)
  30. #[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]

随机数函数

  1. numpy.random.rand(d0, d1, ..., dn)
  2. Random values in a given shape.
  3. Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1)
  4. 生成给定形状的随机值,随机值在[0,1)
  5. import numpy as np
  6. np.random.rand(10)
  7. Out[2]:
  8. array([ 0.41103285, 0.19043225, 0.30385602, 0.19330136, 0.09727556,
  9. 0.96518049, 0.29930132, 0.00633969, 0.64269577, 0.79953589])
  10. np.random.rand(2,3)
  11. Out[3]:
  12. array([[ 0.86213038, 0.56657202, 0.83083843],
  13. [ 0.48660386, 0.20508572, 0.4927877 ]])
  14. np.random.rand(2,3,1)
  15. Out[4]:
  16. array([[[ 0.06676746],
  17. [ 0.55548283],
  18. [ 0.04411342]],
  19. [[ 0.18659571],
  20. [ 0.02209355],
  21. [ 0.83529269]]])
  22. numpy.random.rand(d0, d1, ..., dn)
  23. Random values in a given shape.
  24. Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1)
  25. 生成给定形状的随机值,随机值在[0,1)
  26. import numpy as np
  27. np.random.rand(10)
  28. Out[2]:
  29. array([ 0.41103285, 0.19043225, 0.30385602, 0.19330136, 0.09727556,
  30. 0.96518049, 0.29930132, 0.00633969, 0.64269577, 0.79953589])
  31. np.random.rand(2,3)
  32. Out[3]:
  33. array([[ 0.86213038, 0.56657202, 0.83083843],
  34. [ 0.48660386, 0.20508572, 0.4927877 ]])
  35. np.random.rand(2,3,1)
  36. Out[4]:
  37. array([[[ 0.06676746],
  38. [ 0.55548283],
  39. [ 0.04411342]],
  40. [[ 0.18659571],
  41. [ 0.02209355],
  42. [ 0.83529269]]])
  43. numpy.random.randint(low, high=None, size=None, dtype='l')
  44. 返回随机整数,左闭右开[low,high)
  45. np.random.randint(low=1,high=10,size=8)
  46. Out[10]: array([4, 2, 6, 7, 2, 4, 3, 8])
  47. #high为空的话,直接[0,low)
  48. np.random.randint(10,size=5)
  49. Out[11]: array([1, 3, 7, 9, 9])
  50. np.random.randint(low=1,high=10,size=(2,3))
  51. Out[12]:
  52. array([[8, 3, 6],
  53. [4, 1, 9]])
  54. numpy.random.random_integers(low, high=None, size=None)
  55. 返回随机整数,闭区间[low,high]
  56. 这个和random.randint类似,已经不推荐使用了
  57. np.random.random_integers(low=1,high=5,size=5)
  58. __main__:1: DeprecationWarning: This function is deprecated. Please call randint(1, 5 + 1) instead
  59. Out[13]: array([3, 2, 2, 4, 5])
  60. numpy.random.random_sample(size=None)
  61. numpy.random.random(size=None)
  62. numpy.random.ranf(size=None)
  63. numpy.random.sample(size=None)
  64. 返回随机的浮点值,左闭右开区间[0.0, 1.0)
  65. np.random.random_sample(8)
  66. Out[14]:
  67. array([ 0.70353035, 0.79018004, 0.50390916, 0.46261548, 0.85556642,
  68. 0.68129238, 0.07098945, 0.65927063])
  69. np.random.random_sample([2,3])
  70. Out[16]:
  71. array([[ 0.37546444, 0.50352846, 0.3496647 ],
  72. [ 0.02849239, 0.6035842 , 0.32514876]])

文件存取

csv文件 逗号分割 只能 一维二维

  1. #写入文件
  2. np.savetxt(frame,array,fmt='%.18e',delimiter=None)
  3. #默认科学记数法保留18位小数 分割字符串
  4. a=np.arange(10).reshape(5,2)
  5. np.savetxt('a.csv',a,fmt='%d',delimiter=',')
  6. #默认保存在 C User lenovo
  7. #读取文件
  8. np.loadtxt(frame,dtype=np.float,delimiter=None,unpack=False)#读入属性写入同一个变量

多维数据
tofile

  1. a.tofile(frame,sep='',format='%s')
  2. a=np.arange(100).reshape(5,10,2)
  3. a.tofile("b.dat",sep=',',format='%d')
  4. #sep:数据分割字符串,不指定:写入为二进制
  5. #。dat
  6. #format:数据的格式
  7. #读取文件,读取时需要知道存入文件的数组的维度和数据类型
  8. np.fromfile(frame,dtype=float,count=-1,sep='')
  9. c=np.fromfile('b.dat',dtype=np.int,sep=",").reshape(5,10,2)
  10. #count:读入元素个数,-1表示读入整个文件

多维的便捷文件存取

  1. np.save(fname,array)
  2. #frame:文件名,以.npy为拓展名,压缩拓展名为.npz
  3. #array:数组变量
  4. np.load(fname)

统计函数

  1. sum(a,axis=None) 求和,none默认全部
  2. mean(a,axis=None) 期望
  3. average(a,axis=None,weights=None) 加权平均值
  4. std(a,axis=None) 标准差
  5. var(a,axis=None) 方差
  6. argmin(a) argmax(a) 得到下标(扁平化一维)
  7. unravel_index(index,shape) 根据shape将一维下标index转换成多维下标
  8. ptp(a) 计算数组中最大值和最小值的差
  9. median(a) 计算中位数
  10. In [1]: import numpy as np
  11. In [2]: a=np.arange(15).reshape(3,5)
  12. In [3]: a
  13. Out[3]:
  14. array([[ 0, 1, 2, 3, 4],
  15. [ 5, 6, 7, 8, 9],
  16. [10, 11, 12, 13, 14]])
  17. In [4]: np.average(a,axis=0,weights=[10,5,1])#axis=0代表往跨行(down),而axis=1代表跨列(across)
  18. Out[4]: array([2.1875, 3.1875, 4.1875, 5.1875, 6.1875])
  19. In [5]: np.unravel_index(np.argmax(a),a.shape)
  20. Out[5]: (2, 4)

梯度函数

  1. np.gradient(f) #计算数组f中元素的梯度,当f为多维时,返回每个维度梯度

草图.png
最外层表示列,其次是行
图像或声音的边缘

多维梯度.png

图像的手绘效果

图像的数组表示

RGB色彩模式
0-255
PIL库
pillow 图像处理库
图像表示
一个由像素组成的二维矩阵,每一个元素是一个RBG值

  1. from PIL import Image
  2. import numpy as np
  3. im=np.array(Image.open("D:/360MoveData/Users/lenovo/Desktop/grand.png"))
  4. print(im.shape,im.dtype)
  5. (353, 780, 4) uint8 图像是一个三维数组,维度分别是高度,宽度,像素的RGB

图像的变换

  1. from PIL import Image
  2. import numpy as np
  3. a=np.array(Image.open("M:/NOW/pythontest/grand.png"))
  4. print(a,a.shape,a.dtype)
  5. b=[255,255,255,255]-a
  6. im=Image.fromarray(b.astype('uint8'))
  7. im.save("M:/NOW/pythontest/grand2.png")

打开图像;对RGB像素运算;保存为文件

  1. from PIL import Image
  2. import numpy as np
  3. a=np.array(Image.open("M:/NOW/pythontest/grand.png").convert('L'))#convert('L')生成灰度值图片
  4. print(a,a.shape,a.dtype)
  5. b=255-a
  6. im=Image.fromarray(b.astype('uint8'))
  7. im.save("M:/NOW/pythontest/grand2.png")
  1. from PIL import Image
  2. import numpy as np
  3. a=np.array(Image.open("M:/NOW/pythontest/grand.png").convert('L'))#convert('L')生成灰度值图片
  4. b=(100/255)*a+150#区间变换 颜色比较淡的灰度
  5. c=255*(a/255)**2#像素平方 加深灰度
  6. im=Image.fromarray(b.astype('uint8'))
  7. im.save("M:/NOW/pythontest/grand2.png")
  8. im=Image.fromarray(c.astype('uint8'))
  9. im.save("M:/NOW/pythontest/grand3.png")

手绘实例

特征
黑白灰 边界线条粗 相同相近色彩趋于白色 略有光源效果
利用像素之间的梯度值和虚拟深度值对图像进行重构
根据灰度变化模拟人类视觉的明暗程度

  1. depth=10 #预设深度值为10 取值范围0-100
  2. grad=np.gradient(a)
  3. grad_x,grad_y=grad #提取xy方向的梯度值
  4. grad_x=grad_x*depth/100
  5. grad_y=grad_y*depth/100 #根据深度调整xy的梯度值
  6. '梯度归一化'
  7. A=np.sqrt(grad_x**2+grad_y**2+1.) #构造三维归一化坐标系
  8. uni_x=grad_x/A
  9. uni_y=grad_y/A
  10. uni_z=1./A
  11. b=255*(dx*uni_x+dy*uni_y+dz*uni_z) #梯度与光源相互作用,将梯度转化为灰度

草图.png

  1. vec_el=np.pi/2.2
  2. vel_az=np.pi/4.
  3. dx=np.cos(vec_el)*np.cos(vel_az)
  4. dy=np.cos(vec_el)*np.sin(vel_az)
  5. dz=np.sin(vec_el) #单位光线在坐标轴上的坐标 在此视为光源对三方向的影响程度

图像生成(避免数据越界)

  1. b=b.clip(0,255)
  2. im=Image.fromarray(b.astype('uint8'))
  3. im.save('')