Scikit-image - 寫入影像



寫入或儲存影像在影像處理和計算機視覺任務中起著至關重要的作用。在執行影像處理操作(如裁剪、調整大小、旋轉或應用各種濾鏡)時,需要儲存影像。

寫入影像指的是將影像儲存或儲存為磁碟或記憶體中外部檔案的過程。在此過程中,我們通常指定所需的格式(例如 JPEG、PNG、TIFF 等)並提供檔名或路徑。

在 scikit-image 庫中,io 模組提供了一個名為 imsave() 的函式,專門用於將影像寫入和儲存為外部檔案。此函式可用於儲存影像操作的結果。

io.imsave() 方法

透過使用imsave()方法,可以將影像寫入具有所需檔案格式、檔名和所需位置的外部檔案。以下是此方法的語法:

skimage.io.imsave(fname, arr, plugin=None, check_contrast=True, **plugin_args)

該函式採用以下引數:

  • fname - 表示將儲存影像的檔名或路徑的字串。檔案的格式從檔名的副檔名獲取。
  • arr - 形狀為 (M,N) 或 (M,N,3) 或 (M,N,4) 的 NumPy 陣列,包含要儲存的影像資料。
  • plugin (可選) - 指定用於儲存影像的外掛的字串。如果未提供 plugin 引數,則該函式將自動嘗試不同的外掛,從 imageio 開始,直到找到合適的外掛。但是,如果檔名 (fname) 具有".tiff"副檔名,則預設情況下將使用 tifffile 外掛。
  • check_contrast (可選) - 一個布林值,指示是否檢查影像的對比度並列印警告。預設值為 True。
  • **plugin_args (可選) - 傳遞給指定外掛的其他關鍵字引數。

示例 1

以下示例使用imsave()方法將隨機資料的陣列寫入外部影像檔案 (.jpg)。

import numpy as np
from skimage import io
# Generate an image with random numbers
image_data = np.random.randint(0, 256, size=(256, 256, 3), dtype=np.uint8)
# Save the random image as a JPG file
io.imsave('Output/Random_image.jpg', image_data)
print("The image was saved successfully.")

輸出

The image was saved successfully.

如果我們導航到儲存影像的目錄,我們將能夠觀察到儲存的"Random_image.jpg"影像,如下所示:

Writing Images

示例 2

以下示例使用 imsave() 方法將影像陣列寫入 TIFF 檔案 (.tiff)。

import numpy as np
from skimage import io
# Read an image
image_data = io.imread('Images/logo-w.png')
print("The input image properties:")
print('Type:', type(image_data))
print('Shape:', image_data.shape)
# Save the image as a tiff file
io.imsave('Output/logo.tiff', image_data)
print("The image was saved successfully...")

輸出

The input image properties:
Type: < class 'numpy.ndarray' >
Shape: (225, 225, 4)
The image was saved successfully...

下圖表示儲存到影像儲存目錄中的 "logo.tiff" 檔案。

Writing Images

示例 3

以下示例演示瞭如何使用 imsave() 方法將影像儲存為具有低質量的 JPEG 檔案 (.jpeg)。

import numpy as np
from skimage import io
# Read an image
image = io.imread('Images/Flower1.jpg')
# Save the image as a JPEG file
io.imsave('Output/flower.jpeg', image, plugin='pil', quality=10)
# Display the image array properties
print("The input image properties:")
print('Type:', type(image))
print('Shape:', image.shape)
print("The image was saved successfully...")

輸出

The input image properties:
Type: < class 'numpy.ndarray'>
Shape: (4000, 6000, 3)
The image was saved successfully...

以下影像分別表示輸入 (Flower1.jpg) 和儲存 (flower.jpeg) 檔案在各自目錄中的詳細資訊。

輸入檔案

Writing Images

儲存的檔案

Writing Images
廣告

© . All rights reserved.