简体   繁体   中英

Replacing pixels in matplot image

I have two images as NDArray's

  1. The original image
  2. A prediction mask.

I would like to 'white out' the areas where the mask is not 6 for example

To keep things simple I've paste them below as tiny 3x3 images with each cell being the the RGB value of the pixel

Original

[
    [1,1,1], [1,5,1], [1,1,1]
    [3,3,3], [3,3,3], [3,3,3]
    [1,1,1], [5,2,1], [1,1,1]
]

The Prediction

[
    [0, 0, 0]
    [6, 6, 6]
    [1, 2, 3]
]

To do this I am just looping through the prediction and replacing cells in the original with [0,0,0] to white out the ones I don't want

for rowIndex, predictedPointRow in enumerate(predict):
    for colIndex, predPoint in enumerate(predictedPointRow):
        if predPoint is not 6:
            img[rowIndex][colIndex] = [0, 0, 0]

This is painfully slow however. Is there a better way to do it?

Thanks,

You could do something like

img = np.array([[[1,1,1], [1,5,1], [1,1,1]],[[3,3,3], [3,3,3], [3,3,3]],[[1,1,1], [5,2,1], [1,1,1]]])
predict = np.array([[0,0,0],[6,6,6],[1,2,3]])
img[predict!=6] = [0,0,0]

You can make use of Boolean or “mask” index arrays :

mask = (predict != 6)   # create a 2D boolean array, which can be used for indexing
img[mask] = [0,0,0]

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