Python:从 3D 数组中提取 2D 数组

jde*_*nge 2 python arrays opencv numpy

我有一个 3D numpy 数组(1L、420L、580L),第二维和第三维是我想使用 openCV 显示的灰度图像。如何从 3D 数组中提取 2D 数组?

我创建了一个简短的例程来执行此操作,但我敢打赌有更好的方法。

# helper function to remove 1st dimension
def pull_image(in_array):

    rows = in_array.shape[1]    # vertical
    cols = in_array.shape[2]    # horizontal

    out_array = np.zeros((rows, cols), np.uint8)    # create new array to hold image data

    for r in xrange(rows):
        for c in xrange(cols):            
            out_array[r, c] = in_array[:, r, c]
    return out_array
Run Code Online (Sandbox Code Playgroud)

Aar*_*ron 5

如果你总是只有第一个维度 == 1,那么你可以简单地重塑数组......

if in_array.shape[0] == 1:
    return in_array.reshape(in_array.shape[1:])
Run Code Online (Sandbox Code Playgroud)

否则,您可以使用 numpy 的高级列表切片...

else:
    return in_array[0,:,:]
Run Code Online (Sandbox Code Playgroud)