Reputation: 3854
I have a Nd matrix A
with the dimension of (256,256,100). In which,256x256
are height and width, and 100
is the number of images/slice. In the 100
images, they have some images are zero (only background), other images are non-zero (including background and foreground). The background intensity is 0 and foreground intensity is 1. I want to delete/remove zero slices/images from the matrix A. How could I do it in python efficiently?
This is my implementation but I think we can do better
import numpy as np
h, w, c = A.shape
for i in range (c):
A_slice=A[:,:,i]
sum_in= np.sum(A_slice)
if (sum_in==0):
np.delete(A,A_slice)
Update: Sorry I missing one requirement. I have a vector B
with the shape of (100,). It contained the id of each slice from 1 to 100. When we remove the slice in the matrix A, I also want to remove its id/index in the vector B. Thanks
Upvotes: 0
Views: 234
Reputation: 11602
We can compute a boolean mask for "zero" images as
zero_mask = A.sum((0,1)) == 0
To remove corresponding images, we can use
A = A[..., ~zero_mask]
B = B[~zero_mask]
Upvotes: 2