【问题标题】:numpy with python: convert 3d array to 2dnumpy 与 python:将 3d 数组转换为 2d
【发布时间】:2015-12-26 15:04:58
【问题描述】:

假设我有一个彩色图像,自然会在 python 中用一个 3 维数组来表示,比如形状 (n x m x 3) 并称之为 img。

我想要一个新的二维数组,称它为“narray”以具有形状 (3,nxm),这样该数组的每一行分别包含 R、G 和 B 通道的“扁平化”版本。此外,它应该具有我可以通过类似的方式轻松重建任何原始频道的属性

narray[0,].reshape(img.shape[0:2])    #so this should reconstruct back the R channel.

问题是如何从“img”构造“narray”?简单的 img.reshape(3,-1) 不起作用,因为元素的顺序不适合我。

谢谢

【问题讨论】:

    标签: python arrays numpy image-processing computer-vision


    【解决方案1】:

    您需要使用np.transpose 重新排列尺寸。现在,n x m x 3 将转换为3 x (n*m),因此将最后一个轴发送到前面,并将其余轴的顺序右移(0,1)。最后,重塑具有3 行。因此,实现将是 -

    img.transpose(2,0,1).reshape(3,-1)
    

    示例运行 -

    In [16]: img
    Out[16]: 
    array([[[155,  33, 129],
            [161, 218,   6]],
    
           [[215, 142, 235],
            [143, 249, 164]],
    
           [[221,  71, 229],
            [ 56,  91, 120]],
    
           [[236,   4, 177],
            [171, 105,  40]]])
    
    In [17]: img.transpose(2,0,1).reshape(3,-1)
    Out[17]: 
    array([[155, 161, 215, 143, 221,  56, 236, 171],
           [ 33, 218, 142, 249,  71,  91,   4, 105],
           [129,   6, 235, 164, 229, 120, 177,  40]])
    

    【讨论】:

    【解决方案2】:

    如果你安装了 scikit 模块,那么你可以使用 rgb2grey(或 rgb2gray)将照片从彩色变为灰色(从 3D 到 2D)

    from skimage import io, color
    
    lina_color = io.imread(path+img)
    lina_gray = color.rgb2gray(lina_color)
    
    In [33]: lina_color.shape
    Out[33]: (1920, 1280, 3)
    
    In [34]: lina_gray.shape
    Out[34]: (1920, 1280)
    

    【讨论】:

      【解决方案3】:

      [原始答案]

      假设我们有一个大小为m x n x 3 的数组img 要转换为一个大小为3 x (m*n) 的数组new_img

      初步解决方案:

      new_img = img.reshape((img.shape[0]*img.shape[1]), img.shape[2])
      new_img = new_img.transpose()
      

      [编辑答案]

      缺陷:reshape 从第一个维度开始,对其余部分进行reshape,这个解决方案有可能混合来自第三个维度的值。在图像的情况下,这可能在语义上不正确。

      适应的解决方案:

      # Dimensions: [m, n, 3]
      new_img = new_img.transpose()
      # Dimensions: [3, n, m]
      new_img = img.reshape(img.shape[0], (img.shape[1]*img.shape[2]))
      

      严格的解决方案:

      # Dimensions: [m, n, 3]
      new_img = new_img.transpose((2, 0, 1))
      # Dimensions: [3, m, n]
      new_img = img.reshape(img.shape[0], (img.shape[1]*img.shape[2]))
      

      严格是考虑维度顺序的更好方法,而来自Adapted 和Strict 的结果在值(set(new_img[0,...]))方面将相同,但是顺序打乱了。

      【讨论】:

        猜你喜欢
        • 2021-12-29
        • 1970-01-01
        • 2019-10-31
        • 1970-01-01
        • 2017-07-26
        • 1970-01-01
        • 2017-07-27
        • 2011-05-19
        • 2018-04-20
        相关资源
        最近更新 更多