Search code examples
pythonnumpyscikit-image

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.


Solution

  • 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