【问题标题】:Python: extract a 2D array from a 3D arrayPython:从 3D 数组中提取 2D 数组
【发布时间】:2016-08-12 12:55:31
【问题描述】:

我有一个 3D numpy 数组(1L、420L、580L),第 2 维和第 3 维是我想使用 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

【问题讨论】:

  • 使用np.squeeze。或者只是提取第一个元素以丢失额外的单例暗淡。

标签: python arrays opencv numpy


【解决方案1】:

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

if in_array.shape[0] == 1:
    return in_array.reshape(in_array.shape[1:])

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

else:
    return in_array[0,:,:]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多