Jonathan
Jonathan

Reputation: 1936

Pythonic way of indexing 2d array with list of coordinates

I have coordinates of class numpy.ndarray and of dimensions (200,2). Basically the output from regionprops.

I want to index a image matrix (also an ndarray) of dim img.shape = (1000,1000). I want to be able to do something like

for prop in region:
    img[prop.coords] = 0

However, what happens is, it doesn't see the coordinates as row, column pairs. But rather, each number as a row number and sets that entire row to 0.

How can I fix this?

I tried reshaping the array but that doesn't seem to work either. The only other think I can think of is to convert those indices into a matrix, where the matrix is same size as image dimensions and those coordinates are 1 and all the other coordinate values are 0. Then, index using this matrix. However, this doesn't seem any more efficient than just brute forcing it using a for loop.

Upvotes: 3

Views: 1772

Answers (2)

yann
yann

Reputation: 662

for prop in region:
    (min_row, min_col, max_row, max_col) = prop['bboxtuple']
    img[min_row:max_row, min_col:max_col] = 0

Upvotes: 0

Tonechas
Tonechas

Reputation: 13723

You have to supply the coordinates as a tuple in order to invoke basic indexing:

for prop in region:
    img[tuple(prop.coords.T)] = 0

Upvotes: 6

Related Questions