{"id":1063,"date":"2019-10-06T16:44:58","date_gmt":"2019-10-06T16:44:58","guid":{"rendered":"https:\/\/muthu.co\/?p=1063"},"modified":"2021-05-24T02:50:13","modified_gmt":"2021-05-24T02:50:13","slug":"reducing-the-number-of-colors-of-an-image-using-median-cut-algorithm","status":"publish","type":"post","link":"http:\/\/write.muthu.co\/reducing-the-number-of-colors-of-an-image-using-median-cut-algorithm\/","title":{"rendered":"Reducing the number of colors of an image using Median Cut algorithm"},"content":{"rendered":"\n
In my previous post, I talked about the <\/span><\/span>Uniform Quantization algorithm, <\/span><\/a>which was a simple way of reducing the colors in the image<\/span><\/span>. <\/span>Though it’s easy to <\/span><\/span>implement<\/span><\/span>, it doesn’t always yield good results when there are many colors belonging to the same region<\/span><\/span>. Also, a lot of color regions will not have any colors mapped to them resulting in color map entries get wasted.<\/span><\/p>\n\n\n\n In this post, I will talk about the Median Cut algorithm for color quantization. The main idea is to recursively<\/span> sort the pixels by color space and divide it along the median. The implementation can be found here.<\/a><\/span><\/p>\n\n\n\n For example, In your image, if the blue channel has the greatest range, then a pixel with an RGB value of (32, 8, 16) is less than a pixel with an RGB value of (1, 2, 24), because 16 < 24. Sort the pixels along blue channel. After the bucket has been sorted, move the upper half of the pixels into a new bucket. Repeat the process on both buckets, giving you 4 buckets, then repeat on all 4 buckets, giving you 8 buckets, then repeat on all 8, giving you 16 buckets. Average the pixels in each bucket and you have a palette of 16 colors.<\/p>\n\n\n\n Since the number of buckets doubles with each iteration, this algorithm can only generate a palette with a number of colors that is a power of two.<\/p>\n\n\n\nAlgorithm<\/h2>\n\n\n\n
Implementation<\/h2>\n\n\n\n