直接列舉幾個常用的函數,可在 http://effbot.org/imagingbook/image.htm 中查看更多相關函數。
from PIL import Image import numpy as np img = Image.open('demo.jpg', 'r') # 打開圖片,保存為Image對象 width, height = img.size # 獲取圖片的大小 new_img = Image.new('RGB', (512, 512), 'red') # 新建Image對象,大小為512×512×3,紅色 Image.new('mode', (width, height), 'color') new_img.putpixel((123, 123), (255, 255, 255)) # 將new_img的(123, 123)處像素顏色改為白色 putpixel((width, height), (r, g, b)) r, g, b = new_img.getpixel((123, 123)) # 獲取new_img的(123, 123)處像素的值 getpixel((width, height)) img = img.convert('L') # 將圖片轉為灰度圖片 img.show() # 顯示圖片 img.save('demo_L.jpg') # 保存圖片 data = img.getdata() # 獲取圖像內容 img_mat = np.matrix(data) # 將Image對象轉為矩陣 new_img = Image.fromarray(img_mat) # 將矩陣轉為Image對象,需要保證矩陣元素類型為uint8,否則會error