1. 程式人生 > >python中PIL庫的常用操作

python中PIL庫的常用操作

Python 中的影象處理(PIL(Python Imaging Library))

## Image是PIL中最重要的模組
from PIL import Image
import matplotlib.pyplot as plt
%matplotlib inline
## 影象讀取、顯示
# 讀取
img = Image.open('cat.jpg') # 建立一個PIL影象物件
print type(img) # PIL影象物件
print img.format,img.size,img.mode

# 顯示(為顯示方便,這裡呼叫plt.imshow顯示)
plt.imshow(img)
# img.show()
<class 'PIL.JpegImagePlugin.JpegImageFile'>
JPEG (480, 360) RGB
<matplotlib.image.AxesImage at 0x7fce074f3210>

這裡寫圖片描述

## 轉換成灰度影象
img_gray = img.convert('L')

# 顯示
plt.figure
plt.imshow(img_gray)
plt.gray()

# 儲存
img_gray.save('img_gray.jpg') # 儲存灰度圖(預設當前路徑)

這裡寫圖片描述

## 轉換成指定大小的縮圖
img = Image.open('cat.jpg'
) img_thumbnail = img.thumbnail((32,24)) print img.size plt.imshow(img)
(32, 24)
<matplotlib.image.AxesImage at 0x7fce05b004d0>

這裡寫圖片描述

## 複製和貼上影象區域
img = Image.open('cat.jpg')

# 獲取制定位置區域的影象 
box = (100,100,400,400)
region = img.crop(box)
plt.subplot(121)
plt.imshow(img)
plt.subplot(122)
plt.imshow(region)
<matplotlib.image.AxesImage at 0x7fce05a00710>

這裡寫圖片描述

## 調整影象尺寸和影象旋轉
img = Image.open('cat.jpg')

# 調整尺寸
img_resize = img.resize((128,128))
plt.subplot(121)
plt.imshow(img_resize)

# 旋轉
img_rotate = img.rotate(45)
plt.subplot(122)
plt.imshow(img_rotate)
<matplotlib.image.AxesImage at 0x7fce058a4bd0>

這裡寫圖片描述

PIL結合OS模組使用

## 獲取指定路徑下所有jpg格式的檔名,返回檔名列表
import os
def getJpgList(path):
    # os.listdir(path): 返回path下所有的目錄和檔案
    # string.endswith(str,start_index = 0,end_index = end): 判斷字串sring是否以指定的字尾str結果,返回True或False
    jpgList =[f for f in os.listdir(path) if f.endswith('.jpg')]

    return jpgList

getJpgList('/home/meringue/Documents/PythonFile/imageProcessNotes/')
['img_gray.jpg',
 'fish-bike.jpg',
 'building.jpg',
 'cat.jpg',
 'cat_thumb.jpg',
 'lena.jpg']
## 批量轉換影象格式
def convertJPG2PNG(path):
    filelist = getJpgList(path)

    print 'converting...'
    for filename in filelist:
    # os.path.splitext(filename): 分離檔名和副檔名
        outfile = os.path.splitext(filename)[0] + '.png'

        if filename != outfile: # 判斷轉換前後文件名是否相同
            try:
            # 讀取轉換前檔案,並儲存一份以outfile命名的新檔案
                Image.open(filename).save(outfile)       
                print '%s has been converted to %s successfully' %(filename,outfile)

            except IOError: # 如果出現‘IOError’型別錯誤,執行下面操作
                print 'cannot convert', filename

convertJPG2PNG('/home/meringue/Documents/PythonFile/imageProcessNotes/')
converting...
img_gray.jpg has been converted to img_gray.png successfully
fish-bike.jpg has been converted to fish-bike.png successfully
building.jpg has been converted to building.png successfully
cat.jpg has been converted to cat.png successfully
cat_thumb.jpg has been converted to cat_thumb.png successfully
lena.jpg has been converted to lena.png successfully