簡體   English   中英

numpy.array與img_to_array

[英]numpy.array vs img_to_array

numpy.array(image)img_to_array(image)函數有什么img_to_array(image) img_to_arraykeras.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以將通道放置在第一個軸或最后一個軸上。 此外,它將確保返回的數組是3D數組(例如,如果給定的輸入img是可能表示灰度圖像的2D數組,則它將添加另一個尺寸為1的軸使其成為3D數組)。

請注意,盡管在文檔字符串中已經提到輸入圖像是PIL圖像實例,但是它也可以與numpy數組甚至Python列表一起使用(因為輸入首先被轉換為numpy數組: x = np.asarray(img, dtype=dtype) )。

據我在一些示例中看到的, img_to_array()是圖像類的方法。 該類不代表數組,而是更抽象的東西,但是圖像本質上是數組。 這可能就是為什么numpy.array(image)會有類似結果的numpy.array(image)

請注意,由於方法具有更多信息(稱為“上下文”),因此它們應更加有效和可靠。 例如,當涉及到表示而不是RGB時,opencv2正在處理BGR圖像。 起初可能會造成混淆,但是使用適當的cv2庫,您甚至不必真正考慮它(取決於您打算做什么)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM