Home > Back-end >  How to insert new column using numpy and conditionally add values to it
How to insert new column using numpy and conditionally add values to it

Time:02-19

I have a numpy array img(640, 400, 3) It basically contains a pixel array of an image loaded via OpenCV library. Some of the pixels are zero [0, 0, 0] and other are non-zero [r, g, b] values

How do I -

  1. insert another column to make the shape of it (640, 400, 4) to add the alpha values, so that the pixels become [r, g, b, a], where a is the alpha value
  2. In this new column, the alpha value needs to be set based on a condition: if [r, g, b] == 0 then alpha == 0 else alpha == 255. i.e, my new pixels should be either [0, 0, 0, 0] or [r, g, b, 255]

How do I do this in numpy itself, I don't want to use OpenCV to re-read the image to generate the alpha values.

CodePudding user response:

rgb = np.random.uniform(0, 255, (100, 100, 3)).astype("uint")
# example position with [0,0,0]
rgb[0, 0, :] = 0

# mask where condition is satisfied
msk = np.sum(rgb, axis=2)==0

# Prep the alpha layer
nrows, ncols, _ = rgb.shape
alpha = np.ones((nrows, ncols), dtype="uint") * 255

# Make positions that satisfy condition equal to 0
alpha[msk]= 0

# add extra alpha layer
rgba = np.dstack([rgb, alpha])
  • Related