1. 程式人生 > >Python(5) Image和Ndarray互相轉換

Python(5) Image和Ndarray互相轉換

import numpy as np
from PIL import Image

img = Image.open(filepath)
img_convert_ndarray = np.array(img)
ndarray_convert_img= Image.fromarray(img_convert_ndarray )


# np.array(object) 這個函式很強大啊,看原始碼裡面給的註釋
# object : array_like
#            An array, any object exposing the array interface, an object whose
#            __array__ method
returns an array, or any (nested) sequence.

而keras裡面也有api來做這樣的轉換

from keras.preprocessing.image import img_to_array, array_to_img

然而檢視原始碼的時候,其實會發現這兩個函式仍然還是用同樣的方式實現
img_to_array() 是使用np.asarray(),而array_to_img是使用Image.fromarray()
多說一句,np.array()是建立一個ndarray,而np.asarray(object)是將一個object轉換成ndarray,但是

np.asarray(a):
    return np.array(a,copy=False)

# 而np.array()裡copy預設為True,那這有什麼區別呢?
import numpy as np

   a = np.array([1, 2])
   b = np.asarray(a)
   c = np.asarray(a)
   print(type(b), type(c), b is c) # True
   e = np.array(a)
   f = np.array(a)
   print(type(e), type(f), e is f) # False

   a = [1
, 2] b = np.asarray(a) c = np.asarray(a) print(type(b), type(c), b is c) # False e = np.array(a) f = np.array(a) print(type(e), type(f), e is f) # False