Home > front end >  How to filter out and replace elements from a 3 dimensional nd.array
How to filter out and replace elements from a 3 dimensional nd.array

Time:11-01

I am trying to use PIL and numpy to map the colors of an image to a scalar value. The parts of the image I need to analyze are in greyscale but the parts that are to be ignored are in green (0,255,0). I am trying to replace all the green (0,255,0) elements in the array with (np.nan,np.nan,np.nan) but I am struggling to do it reliably. Here is what I have tried so far. Any suggestions?

imnp = np.asarray(Image.open(image_path))

# convert data to float to allow for data manipulation... 
# not sure if I need to do this?

imnp_fl = imnp.astype(float)

imnp_fl[imnp_fl==[0,255,0]] = np.nan

The last line above, results in an array where to me, it looks like there are a lot of false positives and more np.nan elements than expected. Possible because the last line is evaluating as True in an "any" type situation instead of an "all" type situation? I suppose I could use loops like:

scope_x = imnp_fl.shape[1]
scope_y = imnp_fl.shape[0]
print(scope_x, scope_y)
ctrx = 0
ctry = 0
while ctry < scope_y:
    while ctrx < scope_x:
        if (imnp_fl[ctry,ctrx] == [0,255,0]).all():
            imnp_fl[ctry,ctrx] = [np.nan,np.nan,np.nan]
        ctrx = ctrx   1
    ctrx = 0
    ctry = ctry   1

This gives me something that looks like what I want. Is there a faster/better way to do this?

CodePudding user response:

If you want to replace all (perfectly) green pixels with white, use:

im[np.all(im==(0,255,0), axis=2)] = [255, 255, 255]

The np.all(..., axis=2) is essentially making the AND condition you were looking for across all elements of the depth (i.e. colour) axis.

  • Related