1 Scipy簡介
Scipy依賴於Numpy
Scipy提供了真正的矩陣
Scipy包含的功能:最優化、線性代數、積分、插值、擬合、特殊函數、快速傅里葉變換、信號處理、圖像處理、常微分方程求解器等
Scipy是高端科學計算工具包
Scipy由一些特定功能的子模塊組成
2 圖片消噪:傅里葉變換
#模塊用來計算快速傅里葉變換
import scipy.fftpack as fftpack
import 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')
3 圖片灰度處理
最大值法: R=G=B=max(R,G,B) 這種方法灰度亮度比較高
data2 = data.mean(axis = 2)
平均值法: R=G=B=(R+G+B)/3 這種方法灰度圖像比較柔和
加權平均值 : R=G=B=(w1R+w2G+w3*B) 根據不同的權重得到不同底色的圖片
data3 = np.dot(data,[0.299,0.587,0.114])
4 Matplotlib中的繪圖技巧
單條曲線
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()
5 scipy積分求圓周率
繪制圓
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')
使用Scipy.integrate.quad()來進行計算
#integrate.quad(函數,區間端點) ,返回值為面積與精度
from scipy import integrate
def g(x):
return (1- x**2)**0.5
area,err = integrate.quad(g,-1,1)
print(area,err)
6 scipy文件的輸入與輸出
保存二進制文件
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
data = 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)
7 使用ndimage處理圖片
導包提取數據處理數據
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,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()
8 pandas繪圖函數
線型圖
#采用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())
#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())
柱狀圖
#水平與垂直柱狀圖Series
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))
直方圖與密度圖
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 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',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 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')