Skip to content
Advertisement

Python / numpy: Remove empty (zeroes) border of 3D array

I have a 3D numpy array. This can be thought of as an image (to be exact it’s values of field points). I want to remove the border (0 values, note that there are negative values possible) in all dimensions. The restriction is that the dimension remains the same for all molecules, eg. I only want to remove the border so far as that the “largest” entry in that dimension is still within the border. So the whole data set (small, size of it is not an issue) needs to be taken into account.

Example in 2D:

JavaScript

Here the top row, and left and right most columns should be removed. Over the whole data set, they only contain 0 values.

The result would be below:

JavaScript

Since I’m not a numpy expert I’m having trouble defining an algorithm to achieve my need. I will need to find the min and max index in each dimension which is not 0 and then use that to trim the array.

Similar to this but in 3D and the cropping must take into account the whole data set.

How can I achieve this?

UPDATE 13th Feb 2019:

So I have tried 3 answers here (one which seems to have been removed which was using zip),Martins and norok2s answer. The output dimensions are the same so I assume all of them work.

I choose Martins solution because I can easily extract the bounding box to apply it to test set.

UPDATE Feb 25th:

If anyone still is observing this I would like to have further input. As said these aren’t actually images but “field values” meaning float and not greyscale images (uint8) which means I need to use at least float16 and this simply needs too much memory. (I have 48gb available but that’s not enough even for 50% of the training set).

Advertisement

Answer

Try this: – its a main algorithm. I dont understand exactly which sides you want extract from your examples, but the below algorithm should be very easy for you to modify according to your needs

Note: This algorithm extracts CUBE where all zero value borders are ‘deleted’. So on each side of cube is some value != 0

JavaScript

Case 1:

JavaScript

Case 2: # error case – only zeros – resulting 3D has no dimensions -> error

JavaScript

EDIT: Because my solution didnt get enough love and understanding, I will provide example to 4th dimensionl body, where 3 Dimensions are free for image and 4th dimension is where images are stored

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement