hrithik mahesh
hrithik mahesh

Reputation: 113

How to replace certain percentage of values with other values in image?

I have an RGB image, I have to assign certain percentage of brightest pixels to 255 and certain percentage of darkest pixels to 0 for each channel. Is there a simple way to do this in numpy?

Upvotes: 1

Views: 132

Answers (1)

Ehsan
Ehsan

Reputation: 12417

Here is a way to do it by sorting and finding the threshold and replacing them, however if you are looking for an efficient way, you really do not need to sort your image, you can use np.partition for it (your image is arr and I assume last dimension are for channels. Update 0.05 for desired percentage. For dark points it would be similar solution with minor changes):

b = arr.reshape(-1,arr.shape[-1])
n = int(0.05 * b.shape[0])
threshold = np.sort(b,0)[n]
arr[arr>threshold] = 100

Upvotes: 1

Related Questions