szymanski
szymanski

Reputation: 51

How to print the location/index of an item inside of a 2d array in python?

I want to identify a straight line in a picture (black/white, 0/1) and locate it so i already turned the picture into an 2d array with numpy and identified the line through calculating the average of the cell (a cell is a row in the 2d array, see source below). Now i would like to return the index (not the value) or at least the location of the cells which are not white.

I found a way to do so in a 1d array but going though the cells is faster than iterate though each pixel value. Till now i have something like this:

for cell in img_array:                              # the array is 2d and the values are 0 or 1
    cal_average(cell)                               # selfmade function to calculate the average
    if not cal_average(cell) == 1 :                 # condition to find the line
        print('line found, it is here:', location)  # not working outcome

Hope you know something. Thanks in advance!

Sources which i want to merge:

How to get item's position in a list?

Iterating through a multidimensional array in Python

Upvotes: 0

Views: 954

Answers (1)

Hisan
Hisan

Reputation: 2645

If I have understood the question right, you want to print the index (x and y coords) of an element within a 2d array.

I would use numpy for its convenience and efficiency for array operations.

import numpy as np  # import numpy 
arr = np.array([[5,4,3],
        [7,6,1],
        [10,34,7]
                ]) # example array

xs, ys = np.where(arr == 7) # criteria to search (can be modified to other operators like !=, <, > etc..
# xs, ys are the x and y coordinates of the indexes where the item was found. x[0], y[0] would be the the first point and so on...

for x,y in zip(xs,ys):
    print("Found at:",x,y) # loop through to print values 

Output:

Found at: 1 0

Found at: 2 2

Upvotes: 2

Related Questions