在 Python 中處理影像?
Pillow 是 Python 中最流行且被認為是預設的影像處理庫之一。Pillow 是 Python 影像庫(PIL)的更新版本,支援一系列簡單和高階的影像處理功能。它也是其他 Python 庫(如 sciPy 和 Matplotlib)中簡單影像支援的基礎。
安裝 Pillow
在開始之前,我們需要 Python 和 Pillow。對於 Linux 系統,Pillow 可能已經存在,因為包括 Fedora、Debian/Ubuntu 和 ArchLinux 在內的主要 Linux 發行版都將 Pillow 包含在以前包含 PIL 的軟體包中。
最簡單的安裝方法是使用 pip
pip install pillow
如何載入和顯示影像
首先,我們需要一個測試影像來演示使用 Python Pillow 庫的一些重要功能。
我使用“統一雕像”照片作為示例影像。下載影像並將其儲存到當前工作目錄中。
#Load and show an image with Pillow from PIL import Image #Load the image img = Image.open('statue_of_unity.jpg') #Get basic details about the image print(img.format) print(img.mode) print(img.size) #show the image img.show()
結果
JPEG RGB (400, 260)
在上面,影像使用 Image 類上的 open() 函式直接載入。這將返回一個影像物件,其中包含影像的畫素資料以及有關影像的詳細資訊。
影像上的 format 屬性將報告影像格式(例如 png、jpeg),mode 將報告畫素通道格式(例如 CMYK 或 RGB),而 size 將報告影像以畫素為單位的尺寸(例如 400*260)。
show() 函式將使用作業系統的預設應用程式顯示影像。
將影像轉換為灰度
要將影像轉換為灰度,顯示它然後儲存它非常容易,只需執行以下操作即可
#Import required library from PIL import Image #Read an image & convert it to gray-scale image = Image.open('statue_of_unity.jpg').convert('L') #Display image image.show() #Save image image.save('statue_of_unity_gs.jpg')
結果
執行上述程式後,將在當前工作目錄中建立一個名為“statue_of_unity_gs.jpg”的檔案。
轉換為其他影像型別
將一種型別的影像(jpeg)轉換為另一種型別(例如 png)也非常容易。
from PIL import Image image = Image.open('statue_of_unity.jpg') image.save('statue_of_unity.png')
建立一個新的影像檔案並儲存在我們的預設目錄中。
調整影像大小
我們當前影像檔案的尺寸為 400 * 260px。如果我們想調整它的大小,並使其大小為 440 * 600px,可以透過以下方式實現:
from PIL import Image
image = Image.open('statue_of_unity.jpg') newImage = image.resize((440, 600)) newImage.save('statue_of_unity_440&600.jpg')
一個名為“statue_of_unit_440*600.jpg”的新檔案,大小為 440 * 600px,被建立並儲存在當前工作目錄中。
如您所見,這會將我們的原始影像放大到所需的尺寸,而不是裁剪它,這可能是您不希望看到的。
如果您想裁剪現有的影像,可以使用以下方法:
image.crop(box=None)
旋轉影像
下面的程式載入影像,將其旋轉 45 度,並使用外部檢視器顯示它。
from PIL import Image image = Image.open('statue_of_unity.jpg') image.rotate(45).show()
建立縮圖
下面的程式將建立當前工作目錄中所有 jpeg 影像的 128*128 縮圖。
from PIL import Image import glob, os size = 128, 128 for infile in glob.glob("*.jpg"): file, ext = os.path.splitext(infile) image = Image.open(infile) image.thumbnail(size, Image.ANTIALIAS) image.save(file + ".thumbnail", "JPEG")
結果
將返回我當前目錄(c:\python\python361)中所有 jpeg 檔案的縮圖,包括“statue_of_unity.jpg”影像。