1. Keras圖像處理API
Keras深度學習庫提供了用於處理圖像數據的實用程序。主要API是ImageDataGenerator類,該類結合了數據加載,準備和擴充。Keras提供了用於加載,轉換和保存圖像數據的功能。這些函數在utils.py函數中,並通過image.py模塊公開。Keras中的所有圖像處理都需要安裝Pillow庫。
2. 使用Keras加載圖像
Keras 提供了 load_img()
函數,用於從文件中加載圖像作爲PIL圖像對象。
# 導入API
from tensorflow.keras.preprocessing.image import load_img
# 讀取單張圖片
img = load_img('cat.jpg')
# 打印圖片詳情
print(type(img))
print(img.format)
print(img.mode)
print(img.size)
img.show()
輸出:
<class 'PIL.JpegImagePlugin.JpegImageFile'>
JPEG
RGB
(4928, 3264)
load_img()
函數提供額外的加載圖像參數,如 color_mode
參數,可以指定圖像模式(默認爲rgb);target_size
參數允許指定圖像的高度和寬度,用元組格式指定,並在加載後自動調整圖像大小。
3. 使用Keras轉換圖像
Keras提供了 img_to_array()
函數,用於將已加載的PIL格式的圖像轉換爲NumPy數組,以用於深度學習模型處理。該API還提供了 array_to_img()
函數,用於將NumPy像素數據數組轉換爲PIL圖像。如果在圖像爲陣列格式時修改了像素數據,然後可以保存或查看像素數據。
下面的示例加載測試圖像,將其轉換爲NumPy數組,然後將其轉換回PIL圖像。
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array, array_to_img
# 讀取單張圖片
img = load_img('cat.jpg')
print(type(img))
# convert to numpy array
img_array = img_to_array(img)
print(img_array.dtype)
print(img_array.shape)
# convert back to image
img_pil = array_to_img(img_array)
print(type(img))
輸出:
<class 'PIL.JpegImagePlugin.JpegImageFile'>
float32
(3264, 4928, 3)
<class 'PIL.JpegImagePlugin.JpegImageFile'>
可以看到像素值從無符號整數轉換爲32位浮點值,轉換後的數組格式爲 [height,width,channels]
。最後,圖像被轉換回PIL格式。
4. 使用Kearas保存圖像
Keras API還提供了 save_img()
函數以將圖像保存到文件。該函數採用保存圖像的路徑,並以NumPy數組格式保存圖像數據。文件格式是從文件名推斷出來的,但也可以通過 file_format
參數指定。
下面的示例以灰度格式加載照片圖像,將其轉換爲NumPy數組,然後將其保存爲新文件名。
from keras.preprocessing.image import load_img, save_img, img_to_array
# 以灰度格式加載圖片
img = load_img('cat.jpg', grayscale=True)
# 轉換爲numpy數組
img_array = img_to_array(img)
# 保存新圖像
save_img('cat_grayscale.jpg', img_array)
# 加載新保存的灰度圖
img = load_img('cat_grayscale.jpg')
print(type(img))
print(img.format)
print(img.mode)
print(img.size)
img.show()
輸出:
<class 'PIL.Image.Image'>
None
RGB
(4928, 3264)
https://machinelearningmastery.com/how-to-load-convert-and-save-images-with-the-keras-api/