Skip to content Skip to sidebar Skip to footer

Reduce Image To N Colors In Opencv Python

I can only ever find examples in C/C++ and they never seem to map well to the OpenCV API. I'm loading video frames (both from files and from a webcam) and want to reduce them to 16

Solution 1:

I think the following could be faster than kmeans, specially with a k = 16.

  1. Convert the color image to gray
  2. Contrast stretch this gray image to so that resulting image gray levels are between 0 and 255 (use normalize with NORM_MINMAX)
  3. Calculate the histogram of this stretched gray image using 16 as the number of bins (calcHist)
  4. Now you can modify these 16 values of the histogram. For example you can sort and assign ranks (say 0 to 15), or assign 16 uniformly distributed values between 0 and 255 (I think these could give you a consistent output for a video)
  5. Backproject this histogram onto the stretched gray image (calcBackProject)
  6. Apply a color-map to this backprojected image (you might want to scale the backprojected image befor applying a colormap using applyColorMap)

Tip for kmeans: If you are using kmeans for video, you can use the cluster centers from the previous frame as the initial positions in kmeans for the current frame. That way, it'll take less time to converge, so kmeans in the subsequent frames will most probably run faster.

Solution 2:

You can speed up your processing by applying the k-means on a downscaled version of your image. This will give you the cluster centroids. You can then quantify each pixel of the original image by picking the closest centroid.

Post a Comment for "Reduce Image To N Colors In Opencv Python"