0

I have an image as a np.array which has shape (320, 240, 4). I want to replace all the individual pixels that have array value (1, 0, 0, 1) which is red to green which has array value (0, 1, 0, 1). I've tried using np.all() but it's not working though I don't get any errors. Below is my code:

mario = mpimg.imread("mario_big.png")
print(mario.shape) # (320, 240, 4)

mario[np.all(mario == (1, 0, 0, 1), axis=-1)] = (0, 1, 0, 1)
luigi = mario

plt.imshow(luigi)
plt.show()

mario looks like this:

[[[0.        0.        0.        0.       ]
  [0.        0.        0.        0.       ]
  [0.        0.        0.        0.       ]
  ...
  [0.        0.        0.        0.       ]
  [0.        0.        0.        0.       ]
  [0.        0.        0.        0.       ]]

 [[0.        0.        0.        0.       ]
  [0.        0.        0.        0.       ]
  [0.        0.        0.        0.       ]
  ...
  [0.        0.        0.        0.       ]
  [0.        0.        0.        0.       ]
  [0.        0.        0.        0.       ]]

 [[0.        0.        0.        0.       ]
  [0.        0.        0.        0.       ]
  [0.        0.        0.        0.       ]
  ...
  [0.        0.        0.        0.       ]
  [0.        0.        0.        0.       ]
  [0.        0.        0.        0.       ]]

 ...

Please advise.

1 Answers1

0

Your code does work (see this answer):

>>> mario = np.random.randint(0, 2, (3, 2, 4))
array([[[1, 1, 1, 0],
        [1, 0, 0, 1]], ## <-

       [[0, 0, 1, 0],
        [0, 0, 1, 0]],

       [[0, 0, 0, 0],
        [0, 1, 1, 1]]])

>>> mario[np.all(mario == (1, 0, 0, 1), axis=-1)] =  (0, 1, 0, 1)

>>> mario
array([[[1, 1, 1, 0],
        [0, 1, 0, 1]], ## <-

       [[0, 0, 1, 0],
        [0, 0, 1, 0]],

       [[0, 0, 0, 0],
        [0, 1, 1, 1]]])
Ivan
  • 34,531
  • 8
  • 55
  • 100
  • Hmm but my colors are not changing from red to green. –  Aug 23 '21 at 12:56
  • Can you provide the code you use to convert from array to image? – Ivan Aug 23 '21 at 13:02
  • Oh I just did `plt.imshow()`. I added code in question. –  Aug 23 '21 at 13:05
  • I would assume your image is encoded in `[0, 255]`, if that's the case then you should do something like `mario[np.all(mario == (255, 0, 0, 255), axis=-1)] = (0, 255, 0, 255)` instead. – Ivan Aug 23 '21 at 13:09
  • I don't think so. The given image is an RGBA np array with all pixel values between 0 and 1. –  Aug 23 '21 at 13:13
  • Please make sure that's the case by looking at `mario.min()` and `mario.max()`. The `matplotlib.pyplot.imread` function should return a `[0, 255]`-range array, I just checked. – Ivan Aug 23 '21 at 13:18
  • Checked using mario.min() and mario.max() which returns 0 and 1. Could I use np.isclose() here somehow maybe some pixels have extremely small difference? –  Aug 23 '21 at 15:48
  • Could you share the image? – Ivan Aug 23 '21 at 16:07