find the farest white pixel from the top or the nearest from the bottom and get pixel co-ordinates

Viewed 38

IndexError: index 1 is out of bounds for axis 1 with size 0 I tried changing the target to a tuple, list etc. I cannot find what's the issue. img_bottom is a binary image

def find_farest_white(img, target):
    nonzero = np.argwhere(img>0)
    distances = np.sqrt((nonzero[:,1] - TARGET[0]) ** 2 + (nonzero[:,0] - TARGET[1]) ** 2)
    farest_index = np.argmax(distances)
    return nonzero[farest_index]

TARGET=(0,0)

EDGEB=[]
#for i in range(img_bottom.shape[0]):
for j in range(0,img_bottom.shape[1]):
    for i in range(0,img_bottom.shape[0]):
        IMG=img_bottom[i,j]
        edge=find_farest_white(IMG,TARGET)
        EDGEB.append(edge)
        i+=1
    j+=1

But I'm getting this error

"
IndexError                                Traceback (most recent call last)
<ipython-input-356-0118c2f70139> in <module>
      4     for i in range(0,img_bottom.shape[0]):
      5         IMG=img_bottom[i,j]
----> 6         edge=find_farest_white(IMG,TARGET)
      7         EDGEB.append(edge)
      8         i+=1

<ipython-input-353-ebd36711b415> in find_farest_white(img, target)
      1 def find_farest_white(img, target):
      2     nonzero = np.argwhere(img>0)
----> 3     distances = np.sqrt((nonzero[:,1] - TARGET[0]) ** 2 + (nonzero[:,0] - TARGET[1]) ** 2)
      4     farest_index = np.argmax(distances)
      5     return nonzero[farest_index]

IndexError: index 1 is out of bounds for axis 1 with size 0 "
1 Answers

Check that image is a 2-dimensional array when you pass it in to find_farest_white. The following (copied directly from your code but with my own array image) works just fine:

TARGET = (0,0)
image = np.eye(5)
def find_farest_white(img):
    nonzero = np.argwhere(img>0)
    distances = np.sqrt((nonzero[:,1] - TARGET[0]) ** 2 + (nonzero[:,0] - TARGET[1]) ** 2)
    farest_index = np.argmax(distances)
    return nonzero[farest_index]
find_farest_white(image)
>>> array([4, 4])
Related