Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert new column using numpy and conditionally add values to it

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading