TheProgramMAN123
TheProgramMAN123

Reputation: 487

How to get coordinate of only one item in numpy array

So this is my code. I don't want to get all the coordinates of pixel values below 210 because I want to perform some operation on them and possibly adjust the condition depending on outcome of that operation.

filename = "/home/User/PycharmProjects/Test/files/1366-000082.png"

image = Image.open(filename)

image_data = np.asarray(image, dtype='int64')

def get_image_data():
     for row in image_data:
         for cell in row:
             if condition:
                 # I need only coordinate of cell here

So again I am aware of the argwhere function. But that only gets me all the coordinates. But I might want to change that condition somewhere in the loop.

Is this even possible?

Otherwise I have to use Pillow, but then the loop will be 10x slower.

Upvotes: 0

Views: 260

Answers (2)

nick nick
nick nick

Reputation: 129

You can use enumerate() to get value indexes:

def get_image_data():
    for row_number, row in enumerate(image_data):
        for column_number, cell in enumerate(row):
            if condition:
                # I need only coordinate of cell here
                print(row_number, column_number)

and, maybe you should pass image_data to get_image_data method

Upvotes: 1

Nicholas Smith
Nicholas Smith

Reputation: 13

Have you looked at using a mask? It should make your life much simpler and faster as with the built in functions of a numpy array you wouldn't have to loop through the entire thing.

As an example for you:

A = np.random.randint(1, 500, (100,100)) Mask = A < 210

This would then give you a matrix of True/False values that you could essentially query and adjust the entries as you want. I know you don't want to deal with all of the coordinates, but this would be much faster than looping through your pixel values.

Hopefully that helps you

Upvotes: 0

Related Questions