Change pixel RGB values individually according to a threshold in Python

I would like to change the RGB values of an image according to a threshold. For example I would like a value in an image to become 0 if it's less than 0.5 and to become 1 if it's equal or greater than 0.5.

Here's an example: A pixel of values [0.3, 0.6, 0.9] should become [0, 1, 1]. I would like this to happen for ALL pixels. This would essentially make my image to use only 8 solid colors, which are the combinations of 0s and 1s in the RGB channel: namely pure red [1,0,0], pure green [0,1,0], pure yellow [1, 1, 0] , etc.

This is how I use the conditional:

from matplotlib import image


folder_dir = "..."
img = image.imread(folder_dir + "\\" + "my_image.png")
output = img.copy()
output[output >= 0.5] = 1
output[output < 0.5] = 0 

plt.imshow(output), plt.axis('off')

According to my knowledge this seems to work, but the areas between different colors in the output image seem to be covered with "mean-valued" colors, for example if there is a large area of red and a large area of white, then there is slight pinkish line between them. The problem gets even more complicated with high frequency multi-colored images where new colors are emerging.

Both input and output images are PNG.

What am I doing wrong?

🔴 No definitive solution yet

📌 Solution 1

It is highly likely that the image pixel intensity is between 0 to 255 so you might want to do something like:

output[output >= 127] = 255
output[output < 127] = 0