简体   繁体   中英

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

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM