本文共 5855 字,大约阅读时间需要 19 分钟。
Scipy依赖于NumpyScipy提供了真正的矩阵Scipy包含的功能:最优化、线性代数、积分、插值、拟合、特殊函数、快速傅里叶变换、信号处理、图像处理、常微分方程求解器等Scipy是高端科学计算工具包Scipy由一些特定功能的子模块组成
#模块用来计算快速傅里叶变换import scipy.fftpack as fftpackimport matplotlib.pyplot as plt%matplotlib inline#读取图片data = plt.imread('moonlanding.png')#data2 = fftpack.fft2(data)data3 = np.where(np.abs(data2)>8e2,0,data2)data4 = fftpack.ifft2(data3)data5 = np.real(data4)plt.figure(figsize=(12,9))plt.imshow(data5,cmap = 'gray')
最大值法: R=G=B=max(R,G,B) 这种方法灰度亮度比较高
data2 = data.mean(axis = 2)
平均值法: R=G=B=(R+G+B)/3 这种方法灰度图像比较柔和
加权平均值 : R=G=B=(w1*R+w2*G+w3*B) 根据不同的权重得到不同底色的图片
data3 = np.dot(data,[0.299,0.587,0.114])
单条曲线
x = np.arange(0.0,6.0,0.01)plt.plot(x, x**2)plt.show()
多条曲线
x = np.arange(1, 5,0.01)plt.plot(x, x**2)plt.plot(x, x**3.0)plt.plot(x, x*3.0)plt.show()x = np.arange(1, 5)plt.plot(x, x*1.5, x, x*3.0, x, x/3.0)plt.show()
标题与标签
plt.plot([1, 3, 2, 4])plt.xlabel('This is the X axis')plt.ylabel('This is the Y axis')plt.show()plt.plot([1, 3, 2, 4])plt.title('Simple plot')plt.show()
根据线型绘制图片
numpy.random.randn(d0, d1, …, dn)
是从标准正态分布中返回一个或多个样本值。
numpy.random.rand(d0, d1, …, dn)
的随机样本位于[0, 1)中。
numpy.random.standard_normal(size=None)
:随机一个浮点数或N维浮点数组,标准正态分布随机样本
cumsum
:计算轴向元素累加和,返回由中间结果组成的数组 , 重点就是返回值是“由中间结果组成的数组”
plt.plot(np.random.randn(1000).cumsum(), linestyle = ':',marker = '.', label='one')plt.plot(np.random.randn(1000).cumsum(), 'r--', label='two') plt.plot(np.random.randn(1000).cumsum(), 'b.', label='three')plt.legend(loc='best') # loc='best'plt.show()
绘制圆
f = lambda x : (1 - x**2)**0.5import numpy as npimport matplotlib.pyplot as pltx = np.linspace(-1,1,1000)plt.figure(figsize = (4,4))plt.plot(x,f(x),'-',x,-f(x),'-',color = 'r')
使用Scipy.integrate.quad()来进行计算
#integrate.quad(函数,区间端点) ,返回值为面积与精度from scipy import integratedef g(x): return (1- x**2)**0.5area,err = integrate.quad(g,-1,1)print(area,err)
保存二进制文件
from scipy import io as spioimport numpy as npa = np.ones((3,3))#mat文件是标准的二进制文件spio.savemat('./data/file.mat',mdict={ 'a':a})
读取图片
from scipy import miscdata = misc.imread('./data/moon.png')
读取保存的文件
data = spio.loadmat('./data/file.mat')data['a']
保存图片
#模糊,轮廓,细节,edge_enhance,edge_enhance_more, 浮雕,find_edges,光滑,smooth_more,锐化misc.imsave('./data/save.png',arr=data)
导包提取数据处理数据
misc.face(gray=True,cmap='gray')
读取图片并可以进行灰度预处理
ndimage.rotate(图片,角度)
旋转图片
ndimage.zoom(图片,比例)
缩放图片
face[0:400,450:900]
切割图片,一维从0-400,二维从450-900
from scipy import misc,ndimage#原始图片face = misc.face(gray=True)#移动图片坐标shifted_face = ndimage.shift(face, (50, 50))#移动图片坐标,并且指定模式shifted_face2 = ndimage.shift(face, (-200, 0), mode='wrap')#旋转图片rotated_face = ndimage.rotate(face, -30)#切割图片cropped_face = face[10:-10, 50:-50]#对图片进行缩放zoomed_face = ndimage.zoom(face, 0.5)faces = [shifted_face,shifted_face2,rotated_face,cropped_face,zoomed_face]
绘制图片
plt.figure(figsize = (12,12))for i,face in enumerate(faces): plt.subplot(1,5,i+1) plt.imshow(face,cmap = plt.cm.gray) plt.axis('off')
图片的过滤
#导包处理滤波from scipy import misc,ndimageimport numpy as npimport matplotlib.pyplot as pltface = misc.face(gray=True)face = face[:512, -512:] # 做成正方形#图片加噪noisy_face = np.copy(face).astype(np.float)#噪声图片noisy_face += face.std() * 0.5 * np.random.standard_normal(face.shape)#高斯过滤blurred_face = ndimage.gaussian_filter(noisy_face, sigma=1)#中值滤波median_face = ndimage.median_filter(noisy_face, size=5)#signal中维纳滤波from scipy import signalwiener_face = signal.wiener(noisy_face, (5, 5))titles = ['noisy','gaussian','median','wiener']faces = [noisy_face,blurred_face,median_face,wiener_face]
绘制图片
plt.figure(figsize=(12,12))plt.subplot(141)plt.imshow(noisy_face,cmap = 'gray')plt.title('noisy')plt.subplot(142)plt.imshow(blurred_face,cmap = 'gray')plt.title('gaussian')plt.subplot(143)plt.imshow(median_face,cmap = 'gray')plt.title('median')plt.subplot(144)plt.imshow(wiener_face,cmap = 'gray')plt.title('wiener')plt.show()
线型图
#采用Series做法import numpy as npimport pandas as pdfrom pandas import Series,DataFrameimport matplotlib.pyplot as pltnp.random.seed(0)s = Series(np.random.randn(10).cumsum(),index = np.arange(0,100,10))s.plot()plt.show(s.plot())
#DataFrame图标实例np.random.seed(0)df = DataFrame(np.random.randn(10,4).cumsum(0), columns= ['A','B','C','D'], index = np.arange(0,100,10))plt.show(df.plot())
柱状图
#水平与垂直柱状图Seriesfig,axes = plt.subplots(2,1)data = Series(np.random.rand(16),index = list('abcdefghijklmnop'))data.plot(kind = 'bar',ax = axes[0],color = 'b',alpha = 0.9)data.plot(kind = 'barh',ax = axes[1],color = 'b',alpha = 0.9)
#DataFrame柱状图df = DataFrame(np.random.rand(6,4), index = ['one','two','three','four','five','six'], columns = pd.Index(['A','B','C','D'],name = 'Genus'))plt.show(df.plot(kind = 'bar'))df = DataFrame(np.random.rand(6,4), index = ['one','two','three','four','five','six'], columns = pd.Index(['A','B','C','D'],name = 'Genus'))plt.show(df.plot(kind = 'bar',stacked = True))
直方图与密度图
a = np.random.random(10)b = a/a.sum()s = Series(b)plt.show(s.hist(bins = 100)) #bins直方图的柱数
#密度图a = np.random.random(10)b = a/a.sum()s = Series(b)plt.show(s.plot(kind = 'kde'))
带有密度估计的规格化直方图
%matplotlib inlinecomp1 = np.random.normal(0,1,size = 200)comp2 = np.random.normal(10,2,size = 200)values = Series(np.concatenate([comp1,comp2]))p1 = values.hist(bins = 100,alpha = 0.3,color = 'k',density = True)p2 = values.plot(kind = 'kde',style = '--',color = 'r')
散布图
#简单的散布图df = DataFrame(np.random.randint(0,100,size = 100).reshape(50,2),columns = ['A','B'])df.plot('A','B',kind = 'scatter',title = 'x Vs y')
散步矩阵图
import numpy as npimport pandas as pdfrom pandas import Series,DataFrame%matplotlib inlinedf = DataFrame(np.random.randn(200).reshape(50,4),columns = ['A','B','C','D'])pd.plotting.scatter_matrix(df,diagonal = 'kde',color = 'k')
转载地址:http://mizdx.baihongyu.com/