简体   繁体   中英

Replacing pixel np.array values in Python

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.

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]]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM