Search code examples
pythonloopsnumpyimage-processingiteration

Python - Find First and Last white pixels coordinates


I need help in python coding a loop that goes through all the pixels in an image. I need to find all the white pixels and save the coordinates of the first detected pixel and the last. The image is a thresholded image (only white and black pixels). I did a nested loop but I don't know how to do the evaluation.


Solution

  • You could do it with nested loops, if you wanted, but that will be slow and clunky. I'd recommend using the optimized methods built in to numpy

    Assuming your image is a 2d numpy array with black values as 0 and white values at 255, like this:

    image = np.random.choice([0,255], size=(10,10), p=[0.8, 0.2])
    
    >>> image
    array([[  0,   0, 255,   0,   0,   0,   0,   0,   0,   0],
           [  0,   0,   0,   0,   0,   0,   0,   0, 255,   0],
           [  0,   0,   0, 255,   0,   0,   0,   0,   0,   0],
           [  0, 255,   0, 255, 255,   0,   0,   0, 255, 255],
           [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
           [255,   0,   0,   0, 255,   0,   0,   0,   0,   0],
           [  0, 255, 255,   0,   0,   0,   0,   0,   0,   0],
           [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0],
           [255,   0,   0,   0,   0,   0,   0,   0,   0,   0],
           [255, 255,   0,   0, 255, 255, 255, 255,   0, 255]])
    

    You can find the first and last coordinates of white values (values equal to 255) like this:

    white_pixels = np.array(np.where(image == 255))
    first_white_pixel = white_pixels[:,0]
    last_white_pixel = white_pixels[:,-1]
    

    Resulting in this:

    >>> first_white_pixel
    array([0, 2])
    >>> last_white_pixel
    array([9, 9])
    

    or, as a one liner:

    first_white_pixel, last_white_pixel = np.array(np.where(image == 255))[:,[0,-1]].T