1

Using the small reproducible example below, I create mask that I would then like to programatically determine the min and max x and y indices of where the mask is false (i.e., where the values are not masked). In this and the larger 'real-world' example, the masked values will always be spatially continuous - there are no 'islands' in the mask. The goal is to use the programatically determined indices to zoom into the non-masked values with imshow. I attempt to depict what I'm seeking to do in the image at the end of the post.

import numpy as np
import matplotlib.pyplot as plt

# Generate a large array
arr1 = np.random.rand(100,100)

# Generate a smaller array that will help 
# set the mask used below
arr2 = np.random.rand(20,10) + 1

# Insert the smaller array into the larger 
# array for demonstration purposes
arr1[60:80,10:20] = arr2

# boost a few values neighboring the inserted array for demonstration purposes
arr1[59,12] += 2
arr1[70:75,20] += 2
arr1[80,13:16] += 2
arr1[64:72,9] += 2

# For demonstration, plot arr1
fig, ax = plt.subplots(figsize=(20, 15))
im = ax.imshow(arr1)
plt.show()

# Generate a mask with an example condition
mask = arr1 < 1

Using the mask, how does one determine what the values of x_min, x_max, y_min, & y_max in the following line of code should be

im = ax.imshow(arr1[y_min:y_max, x_min:x_max])

such that the imshow would be zoomed in to where the red box is on the following figure? As long as I don't have my wires crossed, I think the answer for this small example would be y_min=59, y_max=80, x_min=9, & x_max=20 small_examp

user2256085
  • 483
  • 4
  • 15
  • You can work with `arr1[y_min:y_max, x_min:x_max]` as with any other array, e.g. `x = arr1[y_min:y_max, x_min:x_max]; x.min()` – Joe Apr 17 '20 at 05:38
  • Does this answer your question? [min function in numpy array](https://stackoverflow.com/questions/14611703/min-function-in-numpy-array) – Joe Apr 17 '20 at 05:40

1 Answers1

1

The following code should work:

y, x = np.where(~mask)  # ~ negates the boolean array
x_min = x.min()
x_max = x.max()
y_min = y.min()
y_max = y.max()
plt.imshow(arr1[y_min:y_max+1, x_min:x_max+1])

Plot from above code

Erik André
  • 528
  • 4
  • 13