使用 Python Mahotas 載入影像
Python 以其強大的庫而聞名,這些庫幾乎可以處理任何任務,影像處理也不例外。為此,一個受歡迎的選擇是 Mahotas,一個計算機視覺和影像處理庫。本文探討了如何使用 Python 的 Mahotas 載入影像,並提供了實際示例。
Mahotas 簡介
Mahotas 是一個複雜的庫,包含許多用於影像處理和計算機視覺的方法。Mahotas 非常注重速度和效率,使您可以使用 100 多個功能,包括顏色空間轉換、濾波、形態學、特徵提取等等。本指南重點介紹影像處理中最基本的一個階段——載入影像。
安裝 Mahotas
在開始載入照片之前,我們必須首先確認 Mahotas 是否已安裝。您可以使用 pip 將此包新增到您的 Python 環境中
pip install mahotas
確保您擁有最新版本,以獲得最佳效能並訪問所有功能。
使用 Mahotas 載入影像
mahotas.imread() 函式讀取影像並將其載入到 NumPy 陣列中。它支援多種檔案格式,包括 JPEG、PNG 和 TIFF。
示例 1:基本影像載入
載入影像就像向 imread() 函式提供影像路徑一樣簡單
import mahotas as mh # Load the image image = mh.imread('path_to_image.jpg') # Print the type and dimensions of the image print(type(image)) print(image.shape)
此程式碼載入影像並輸出尺寸(高度、寬度和顏色通道數)、型別(應該是 numpy ndarray)和影像的型別。
示例 2:灰度影像載入
在某些情況下,您可能希望立即將影像載入為灰度。為此,您可以使用 as_grey 引數
import mahotas as mh # Load the image as grayscale image = mh.imread('path_to_image.jpg', as_grey=True) # Print the type and dimensions of the image print(type(image)) print(image.shape)
由於只有一個顏色通道,因此影像現在是一個二維陣列(僅有高度和寬度)。
示例 3:從 URL 載入影像
Mahotas 允許直接從 URL 載入影像。Imread() 無法直接執行此功能,因此我們必須使用其他庫,如 urllib 和 io
import mahotas as mh import urllib.request from io import BytesIO # URL of the image url = 'https://example.com/path_to_image.jpg' # Open URL and load image with urllib.request.urlopen(url) as url: s = url.read() # Convert to BytesIO object and read image image = mh.imread(BytesIO(s)) # Print the type and dimensions of the image print(type(image)) print(image.shape)
藉助此程式碼,您可以快速將網路上的影像載入到 numpy ndarray 中,以便進一步處理。
結論
影像處理的第一步是載入影像,而 Python 的 Mahotas 包使此過程變得簡單。無論您是在處理本地檔案還是網路照片,彩色還是灰度,Mahotas 都能為您提供所需的工具。
透過熟練掌握影像載入,您已經在掌握 Python 的影像處理能力方面取得了進步。然而,旅程並沒有到此結束;Mahotas 擁有豐富的工具可供您進一步修改和分析您的照片。