Python numpy.array vs img_to_array

Python numpy.array vs img_to_array,python,numpy,image-processing,keras,Python,Numpy,Image Processing,Keras,numpy.array(image)和img\u to\u array(image)函数之间有什么区别img\u to\u数组在keras.preprocessing.image包中。我想将它与图像一起用作此函数的输入。据我所知,img\u to\u array()是图像类的一种方法。该类并不表示数组,而是更抽象的东西,但图像本身就是数组。这可能就是为什么使用numpy.array(image)会得到类似的结果 注意,由于方法有更多的信息(称之为“上下文”),它们应该更高效、更可靠。例如,ope

numpy.array(image)
img\u to\u array(image)
函数之间有什么区别<代码>img\u to\u数组在
keras.preprocessing.image
包中。我想将它与图像一起用作此函数的输入。

据我所知,
img\u to\u array()
是图像类的一种方法。该类并不表示数组,而是更抽象的东西,但图像本身就是数组。这可能就是为什么使用
numpy.array(image)
会得到类似的结果


注意,由于方法有更多的信息(称之为“上下文”),它们应该更高效、更可靠。例如,opencv2在处理BGR图像时使用的是表示,而不是RGB。一开始可能会让人困惑,但使用合适的cv2库,您甚至不必真正考虑它(取决于您打算做什么)

您可以通过查看以下源代码轻松找到答案:

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


请注意,尽管在docstring中提到了输入映像是一个PIL映像实例,但它也可以用于numpy数组甚至Python列表(因为输入首先转换为numpy数组:
x=np.asarray(img,dtype=dtype)
)。

两个函数的输出相同?@nish2288 Yes,返回的值将是相同的。尽管如此,请注意
img_to_array
中的默认数据类型是
'float32'
,而在使用默认数据类型时,则是表示数据所需的最小类型。在这两种情况下,您都可以使用
dtype
参数显式指定所需的数据类型。@今天,对于一幅图像,当我使用
np.array
和[83.77.76.74.69.73.101.117.113]时,我得到了[-44.5-50.5-51.5-53.5-58.5-54.5-26.5-10.5-14.5]。既然我没有改变默认值,你知道为什么吗?PS:这是最后一个过滤器的前10个
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