gpt4 book ai didi

python - numpy.array 与 img_to_array

转载 作者:太空宇宙 更新时间:2023-11-04 09:36:01 25 4
gpt4 key购买 nike

numpy.array(image)img_to_array(image) 函数有什么区别? img_to_array 位于 keras.preprocessing.image 包内。我想将它与图像一起用作此函数的输入。

最佳答案

嗯,看img_to_array的源码就可以轻松找到答案。 :

def img_to_array(img, data_format='channels_last', dtype='float32'):
"""Converts a PIL Image instance to a Numpy array.
# Arguments
img: PIL Image instance.
data_format: Image data format,
either "channels_first" or "channels_last".
dtype: Dtype to use for the returned array.
# Returns
A 3D Numpy array.
# Raises
ValueError: if invalid `img` or `data_format` is passed.
"""
if data_format not in {'channels_first', 'channels_last'}:
raise ValueError('Unknown data_format: %s' % data_format)
# Numpy array x has format (height, width, channel)
# or (channel, height, width)
# but original PIL image has format (width, height, channel)
x = np.asarray(img, dtype=dtype)
if len(x.shape) == 3:
if data_format == 'channels_first':
x = x.transpose(2, 0, 1)
elif len(x.shape) == 2:
if data_format == 'channels_first':
x = x.reshape((1, x.shape[0], x.shape[1]))
else:
x = x.reshape((x.shape[0], x.shape[1], 1))
else:
raise ValueError('Unsupported image shape: %s' % (x.shape,))
return x

因此,主要区别在于您可以将数据格式参数传递给 img_to_array 以将 channel 置于第一个轴或最后一个轴。此外,它将确保返回的数组是一个 3D 数组(例如,如果给定的输入 img 是一个可能代表灰度图像的 2D 数组,那么它将添加另一个维度为 1 的轴使它成为一个 3D 数组)。

请注意,虽然在文档字符串中已经提到输入图像是 PIL 图像实例,但它也适用于 numpy 数组甚至 Python 列表(因为输入首先被转换为 numpy 数组:x = np.asarray(img, dtype=dtype)).

关于python - numpy.array 与 img_to_array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53718409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com