# 05-Scipy

### 一.Scipy简介

-Scipy依赖于Numpy
-Scipy提供了真正的矩阵
-Scipy包含的功能：最优化、线性代数、积分、插值、拟合、特殊函数、快速傅里叶变换、信号处理、图像处理、常微分方程求解器等
-Scipy是高端科学计算工具包
-Scipy由一些特定功能的子模块组成

Scipy.png

### 二.高数积分

##### 2.3 绘制圆
``````f = lambda x : (1 - x**2)**0.5
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1,1,1000)
plt.figure(figsize = (4,4))
plt.plot(x,f(x),'-',x,-f(x),'-',color = 'r')

plt.show()
``````

``````from scipy import integrate
def g(x):
return (1- x**2)**0.5
print(pi_2,err)
``````

### 三.Scipy文件输入/输出

##### 3.1 输入
``````from scipy import io as spio
import numpy as np
a = np.ones((3,3))
#mat文件是标准的二进制文件
spio.savemat('./data/file.mat',mdict={'a':a})
``````
• 读取图片
``````#读取图片
from scipy import misc
``````
##### 3.2 输出
``````#读取保存的文件
data['a']
``````
• 保存图片
``````#保存图片
misc.imsave('./data/save.png',arr=data)
``````
##### 3.3 scipy.misc
``````模糊，轮廓，细节，edge_enhance，edge_enhance_more， 浮雕，find_edges，光滑，smooth_more，锐化
# 滤镜
# 'blur', 'contour', 'detail', 'edge_enhance', 'edge_enhance_more',
# 'emboss', 'find_edges', 'smooth', 'smooth_more', 'sharpen'.
cat_filter = misc.imfilter(cat, 'sharpen' )
plt.figure(figsize=(12,9))
plt.imshow(cat_filter)
``````

### 四.图片处理ndimage

##### 4.1 使用Scipy中的ndimage/misc进行处理
• 导包提取数据处理数据
``````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')
``````

##### 4.2 图片过滤
• 导包处理滤波
``````from scipy import misc,ndimage
import numpy as np
import matplotlib.pyplot as plt
face = 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 signal
wiener_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()
``````

### 五.pandas绘图函数

##### 5.1 线型图
• 简单的Series图标示例
``````import numpy as np
import pandas as pd
from pandas import Series,DataFrame
import matplotlib.pyplot as plt
np.random.seed(0)
s = Series(np.random.randn(10).cumsum(),index = np.arange(0,100,10))
s.plot()
plt.show(s.plot())
``````
Series线型图.png
• 简单的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())
``````
DataFrame线型图.png
##### 5.2 柱状图
• 水平和垂直柱状图
``````fig,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))
``````

##### 5.3 直方图和密度图
• random随机数百分比的直方图
``````a = np.random.random(10)
b = a/a.sum()
s = Series(b)
plt.show(s.hist(bins = 100)) #bins直方图的柱数
``````

• random随机数百分比的密度图
``````a = np.random.random(10)
b = a/a.sum()
s = Series(b)
plt.show(s.plot(kind = 'kde'))
``````

• 带有密度估计的规格化直方图
``````%matplotlib inline
comp1 = 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',normed = True)

p2 = values.plot(kind = 'kde',style = '--',color = 'r')
``````

##### 5.4 散布图
• 一张简单散布图
``````df = DataFrame(DataFrame({'A': np.random.randn(1000), 'B': np.random.randn(1000), 'C': np.random.randn(1000) , 'D': np.random.randn(1000)})

df.plot('A','B',kind = 'scatter',title = 'x Vs y')
``````

• 散布图矩阵
``````import numpy as np
import pandas as pd
from pandas import Series,DataFrame
%matplotlib inline
df = DataFrame(np.random.randn(200).reshape(50,4),columns = ['A','B','C','D'])
pd.plotting.scatter_matrix(df,diagonal = 'kde',color = 'k')
``````

### 推荐阅读更多精彩内容

• Scipy scipy包含致力于科学计算中常见问题的各个工具箱。它的不同子模块相应于不同的应用。像插值，积分，优化...
Aieru阅读 32,711评论 3 58
• 通过傅里叶变换实现图片降噪 scipy.fftpack模块用来计算快速傅里叶变换速度比传统傅里叶变换更快，是对之前...
仙灵儿阅读 1,172评论 0 0
• 资料来源：https://github.com/BrambleXu/pydata-notebook 信息可视化（也...
林清猫耳阅读 1,264评论 0 3
• 本章节以及后续章节的源码，当然也可以从我的github下载，在源码中我自己加了一些中文注释。 这两天没更新，好好反...
owolf阅读 739评论 0 4
• 这辈子有没有人说过最触动你心的一句话？ 有没有人说过让你一辈子也忘不掉的伤心话？
熊爱玲阅读 48评论 0 0