I'm trying to quantize an image keeping all primary colors in place and removing all minor colors such as "anti-aliasing" borders. E.g. the image below ultimately should be quantized to 3 colors whereas the number of actual colors in the original image is more than 30. All "anti-aliasing" border colors should be considered minors and eliminated upon quantization as well as "jpeg artifacts", which add more colors to the image because of over-optimization. Note: a source image could be either png or jpeg. For the quantization itself, I'm using PIL.quantize(...) with K as the number of colors to leave. And it works fairly well and keeps the palette perfectly matching to the original. def color_quantize(path, K): image = cv2.imread(path, cv2.IMREAD_UNCHANGED) img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) im_pil = Image.fromarray(np.uint8(img)) im_pil = im_pil.quantize(K, None, 0, None) return cv2.cvtColor(np.array(im_pil.convert("RGB")), cv2.COLOR_RGB2BGR) Thus, if I knew "K" (the number of primary colors) in advance, then I would use it for im_pil.quantize(...). Basically, I need a way to get that "K" number. Is there any way to determine the number of primary colors? BTW, regarding the "jpeg artifacts" removal, I'm using img = cv2.bilateralFilter(img, 9, 75, 75) at the moment, which works quite well. Continue reading...