1

In a three-dimensional numpy array [row x col x ch], padded with NaNs, e.g.,

>>> a = np.ones((5, 5, 3))
>>> a[0, :, 0] = np.nan
>>> a[:, 0:2, :] = np.nan
>>> a[4, 4, 0] = np.nan

>>> a[:, :, 0]
array([[nan, nan, nan, nan, nan],
       [nan, nan,  1.,  1.,  1.],
       [nan, nan,  1.,  1.,  1.],
       [nan, nan,  1.,  1.,  1.],
       [nan, nan,  1.,  1., nan]])
>>> a.shape
(5, 5, 3)

how do I crop all rows and columns containing NaNs in any channel from the border?

In my example, the result I want to have is an array

>>> a_cropped[:, :, 0]
array([[1., 1.],
       [1., 1.],
       [1., 1.]])
>>> a_cropped.shape
(3, 2, 3)

This is related to this question. However, I am perfectly fine with having only the rectangular area in the center that can unambiguously been extracted.

I assume I first have to strip bordering rows and columns one after another in order not to remove "valid" areas.

Context: Rotating an image and removing NaN-padded areas outside of the valid image area, illustrated in the following figure as black pixels. Rotated image

LL_
  • 173
  • 1
  • 1
  • 7
  • No, rows/columns at the borders containing NaNs in any channel should be removed. I edited my question to clarify that. In the case of an image, rotated using standard libraries like OpenCV, missing values at the borders should contain NaNs in each of the three channels anyways. – LL_ Jun 11 '18 at 16:17
  • It is easier to figure out what size border to remove by computing the valid size given the angle of rotation. Note that finding rows and columns with NaN values is a non-trivial task because the two are related -- you can remove fewer columns if you remove more rows, and vice versa. You'd end up with a sort of optimization problem to find the *largest* rectangle that doesn't contain NaN values. – Cris Luengo Jun 11 '18 at 17:13
  • The angle is actually known. Since I'm interested in a fast, rather than an optimal solution I thought there might be a way to safely extract the center rectangle. The optimization problem is very well explained in the other question I linked, so I might fallback to this. – LL_ Jun 12 '18 at 06:11
  • If you know the angle of rotation, then do follow the top-voted result in the question you linked. I don’t see why you wouldn’t do that. It’s simple geometry, and will be much faster than detecting NaNs and trying to figure out what rows and columns to remove. – Cris Luengo Jun 12 '18 at 12:32

0 Answers0