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