python - numpy efficient array multiplication

I have a three dimensional array img of shape [1200,1600,3] and a two dimensional array labels of shape [1200,1600]. The first array is from an image, the second one is from labels in the image. Location [i,j] in the img array corresponds to an image pixel. I want to create a new array of the same dimension as the img array, such that for the pixels with label 0, the original array is unchanged, but all other pixels are whitened (255,255,255).

The code I am using is:

 import numpy as np

 newimg=np.zeros((img.shape[0],img.shape[1],img.shape[2]))
 for i in range(0,img.shape[0]):
     for j in range(0,img.shape[1]):
          if labels[i][j]==0:
             newimg[i][j]=img[i][j]
     else:
         newimg[i][j]=np.array([255,255,255])

Is there a faster way of doing this?

1 Answer

  1. Randolph- Reply

    2019-11-13

    Generally speaking, you'd do something similar to:

    newimg = img.copy()
    newimg[labels != 0, :] = 255
    

    or alternatively:

    newimg = np.where(labels[..., None] != 0, img, 255)
    

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>