0

Having an image I want to reduce it to x colors and save it in a png file.

I choose to do this using k-means (which is already available in OpenCV). On a full resolution image it takes more then a minute so I resize the image to something much smaller and I get the color palette.

What would be the best way to replace the colors in the original image with the ones in the palette?

One simple implementation I did was to take each pixel in the image and calculate the euclidian distance between that pixel the one in the palette, and then choose the color in the palette that is closest. The visual aspect of this is ok, but it takes more than 30 seconds for palette size grater than 30.

I understand that the way to go is to use Octree or some form of k-nearest neighbors algorithm, but to be honest I don't know if I should spent the time to implement something that I think it's already implemented.

Can I use something from OpenCV that suits my scenario? And can I expect that it will it be at least 2 times faster than using the euclidian distance?

C++ examples would be appreciated.

Adi
  • 321
  • 1
  • 17
  • How big is your image? The idea is correct. You probably just need to get a better implementation – Miki Aug 04 '16 at 17:31
  • It's about 4MB (around 2600 by 1600) RGB. – Adi Aug 04 '16 at 18:50
  • Your original image has 2600x1600 pixel dimension but you applied kmeans on much smaller image, how would you like to map this dissimilarity ? – ZdaR Aug 05 '16 at 06:52
  • Yes, I calculated kmeans on a matrix the size of about 300*200 so I can get the colors. Now, using the original image is see which color is the closest to the one in the palette. – Adi Aug 05 '16 at 07:38
  • Are you using the same palette for a lot of images? – Miki Aug 05 '16 at 16:29
  • No, just one image. – Adi Aug 05 '16 at 17:03
  • People often forget that for the purpose of comparison of purely positive values, the "square root" step of the Euclidean distance is completely unnecessary... if `a² > b²` then you can still be sure `a > b`. So that way, Euclidean distance palette matching isn't a heavy operation at all. – Nyerguds Jun 13 '18 at 22:12

0 Answers0