首页 > 解决方案 > 使用 numpy 和 opencv 在 python 中裁剪基于 3D 图像的 om 2D 蒙版

问题描述

假设您有一个 3D 图像(numpy 数组),例如:

arr = np.random.random((4,4,3))

此外,您还有一个形状为 (4,4) 的 2D 蒙版,例如:

mask = np.array([[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]])

如何使用 numpy 和/或 opencv 将形状为 (4,4) 的 2D 蒙版应用于形状为 (4,4,3) 的 3D 数组并裁剪出不为零的图像?

标签: pythonarraysnumpy

解决方案


这是否有助于回答您的问题?:

arr = np.random.random((4,4,3))
mask = np.array([[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]])
#[[0 1 1 0]
# [0 1 1 0]
# [0 1 1 0]
# [0 1 1 0]]
#mask array
masked_arr = mask[...,None]*arr
#crop edges
true_points = np.argwhere(masked_arr)
top_left = true_points.min(axis=0)
bottom_right = true_points.max(axis=0)
cropped_arr = masked_arr[top_left[0]:bottom_right[0]+1,top_left[1]:bottom_right[1]+1]

#cropped_arr.shape (4,2,3)

推荐阅读