Given some arbitrary input color palette, how can I quantize an image to that given color palette?
While there are a lot of stack overflow solutions using kmeans, I want to be able to do something similar with a preset palette specifically in opencv. For example, this might include using a clustering technique where the k is fixed and the centroids are predetermined by the palette such that each pixel gets assigned to the nearest color in the palette.
For example, I would like to quantize a picture to the nearest colors in white, black, blue, green and red.
My BGR palette would look something like this:
palette = [
[0,0,0],
[255,0,0],
[0,255,0],
[0,0,255],
[255,255,255]
]
Given some input picture, I would like to have each pixel in the picture assigned to the closest item in the above palette.
So the end result would look something like the following:
import cv2
palette = [
[0,0,0],
[255,0,0],
[0,255,0],
[0,0,255],
[255,255,255]
]
def quantize_to_palette(image, palette):
# do something
# return the same image with all colors quantized to the nearest palette item
return
input = cv2.imread('input.jpg')
output = quantize_to_palette(image=input, palette=palette)
cv2.imwrite('output.jpg', output)