dubbbdan
dubbbdan

Reputation: 2740

Numpy: Select all rows and columns from an array

I was hoping I would solve this before I finished the post, but here it goes:

I have an array array1 with a shape (4808L, 5135L) and I am trying to select a rectangular subset of the array. Specifically, I am trying to select the all values in rows 4460:4807 and all the values in columns 2718:2967.

To start I create a mask of the same shape as array1 like:

mask = np.zeros(array1.shape[:2], dtype = "uint8")
mask[array1== 399] = 255

Then I am trying to find the index of the points where mask = 255:

true_points = np.argwhere(mask)
top_left = true_points.min(axis=0)
# take the largest points and use them as the bottom right of your crop
bottom_right = true_points.max(axis=0)
cmask = mask[top_left[0]:bottom_right[0]+1, top_left[1]:bottom_right[1]+1]

Where: top_left = array([4460, 2718], dtype=int64) bottom_right = array([4807, 2967], dtype=int64)

cmask looks correct. Then using top_left and bottom_right I am trying to subset array1 using:

crop_array = array1[top_left[0]:bottom_right[0]+1, top_left[1]:bottom_right[1]+1]

This results in a crop_array have the same shape of cmask, but the values are populated incorrectly. Since cmask[0][0] = 0 I would expect crop_array[0][0] to be equal to zero as well.

How do I poulate crop_array with the values from array1 while retaining the structure of the cmask?

Thanks in advance.

Upvotes: 1

Views: 2768

Answers (1)

Arex
Arex

Reputation: 62

If I understood your question correctly, you're looking for the .copy() method. An example matching your indices and variables:

import numpy as np

array1 = np.random.rand(4808,5135)
crop_array = array1[4417:,2718:2967].copy()

assert np.all(np.equal(array1[4417:,2718:2967], crop_array)) == True, (
    'Equality Failed'
)

Upvotes: 2

Related Questions