0

I have a 3D NumPy array which is essentially image data in RGBA format like so:

[
  [
    [233 228 230 120]
    [233 228 230 0]
    [232 227 229 212]
    ...
  ]
  ...
]

In the example above the last (4th) column represents alpha channel. As I can't have semi-transparent pixels (value other than 0 or 255), I need to threshold that column. Any value below 255 should become 0.

What I have is the line below.

image[...,3][image[...,3] < 255] = 0

It does work but I wanted to ask if there is something shorter and more elegant that would do the job. Thanks.

1
  • can you post your image shape? Commented Dec 15, 2020 at 21:40

2 Answers 2

1

Edit: @Lior Cohen was indeed right! Apologies.

# if your channels are in the last axis, this should work
image[:,:,3][image[:,:,3] < 255] = 0

# another alternative, but not as elegant as what @Lior proposed
image[:,:,3] = np.where(image[:,:,3] < 255, 0, 255)
Sign up to request clarification or add additional context in comments.

2 Comments

I think this will truncate the RGB to 0 and not only the alpha
@LiorCohen you were right! I overlooked it. Your answer should be accepted.
1

Two More options that are based on the /255 operator which will cut integer lower than 255 to 0.

  1. image[...,3] = image[...,3] // 255 * 255
    
  2. image[...,3] //= 255
    image[...,3] *= 255
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.