Crop 3D image based om 2D mask in python using numpy and opencv

Viewed 394

Lets say you have a 3D image (numpy array) such as:

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

Also, you have a 2D mask with shape (4,4) such as:

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

How do you apply the 2D mask with shape (4,4) to the 3D array with shape (4,4,3) and crops out the image where it is not zero, using numpy and/or opencv?

1 Answers

Does this help answer your question?:

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)
Related