Reputation: 2504
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?
Upvotes: 0
Views: 239
Reputation: 284612
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)
Upvotes: 3