Search code examples
pythonimagematplotlibimread

How to get the coordinates of all blue pixels with matplotlib imread?


I would like to append to a list all of the blue pixels of a jpeg image using matplolib's imshow. When I launch my code, I do not get an RGB code result:'array([89, 67, 28], dtype=uint8), array([51, 53, 16], dtype=uint8),' etc... What is going wrong here?

import matplotlib.pyplot as plt import matplotlib.image as mpimg

control = mpimg.imread('jpeg.jpg')
ys = control.shape[0] #length of image
xs = control.shape[1] # image width
pixelcoords= []
for x in range(xs):
    for y in range(ys):
        # if pixel is blue
        pixelcoords.append(control[x][y])

print(pixelcoords)

Solution

  • When reading an image you will get an numpy array of the dimensions (width x height x [R,G,B, alpha]).

    t = mpimg.imread("path/Test1.PNG")
    

    now you can just access the blue layer by taking everything along the width and height dimension (indicated by the ":") and only the 3rd dimension from the RGB,alpha stack. that gives you a 2D array, where every blue pixel has a nonzero value. to find all the coordinates of nonzero entries you can use the np.nonzero function, which gives you their coordinates as an X and Y array

    X,Y = np.nonzero(t[:,:,2])