1. PIL安裝
2. 基本操作
(1) 讀取圖像:img = Image.open(filepath)
(2) 圖像信息:img.size; img.format
(3) 顯示圖像:方法一:Image.show(img),用windows; 方法二:用Image.imshow(img)
(4) 保存圖像:save(FilePath,'format')
(5) 圖像操作:rotate/resize/濾波/針對像素的操作(卷積等)
注:濾波主要是Filter矩陣不同~
3. 程序及運行結果
# coding=gbk
#-------------------------讀取圖片信息------------------------#
from PIL import Image
FilePath = 'C:/Users/Administrator/Desktop/'
img = Image.open(FilePath+'Dog.jpg') # 打開圖片
Size = img.size # 重要信息
print(img.format,Size) # 圖片信息
#---------------------用matplotlib顯示圖像-------------------#
import matplotlib.pyplot as plt
plt.figure(1)
plt.imshow(img,cmap='jet') # 可以嘗試其他的colormap
# help(plt.imshow)
#----------------------用Image進行處理並顯示------------------#
# img.show() # 顯示旋轉後的圖像
img_45 = img.rotate(45) # 旋轉45°
img_45.save(FilePath+'Dog-rotate-45.png',"png")
# img_45.show() # 顯示圖像
grey = img.convert('L') # 轉化爲灰度圖像
grey.save(FilePath+'Dog-grey.png',"png")
# grey.show() # 顯示灰度圖像
#------------濾波------------
from PIL import ImageFilter # 不同的核函數(kernel function)
plt.figure()
img_BLUR = img.filter(ImageFilter.BLUR)
plt.imshow(img_BLUR) # 均值濾波
img_BLUR.save(FilePath+'Dog-BLUR.png',"png") # 保存
plt.figure()
img_ENDGE = img.filter(ImageFilter.FIND_EDGES)
plt.imshow(img_ENDGE) # 邊緣檢測
img_ENDGE.save(FilePath+'Dog-FIND_EDGES.png',"png") # 保存
plt.show() # 顯示所有
#----------像素操作-----------
for i in range(Size[0]): # 像素操作
for j in range(Size[1]):
img.getpixel((i,j))
運行結果:
JPEG (650, 461) # 圖片類型和size
原圖:
旋轉45度:
灰度圖:
均值濾波:
邊緣檢測:
代碼下載:http://download.csdn.net/download/qq_24694761/10216540
(溫馨提示:運行時需要修改圖片路徑)
總結:操作過程與matlab有很多相似之處,總體來說並不難掌握。