# Using custom color palette with kmeans color clustering algorithm

**URL:** <https://forum.opencv.org/t/using-custom-color-palette-with-kmeans-color-clustering-algorithm/16904>\
**Category:** Android/Java\
**Tags:** color, kmeans\
**Created:** [March 20, 2024, 9:56pm UTC](https://forum.opencv.org/t/using-custom-color-palette-with-kmeans-color-clustering-algorithm/16904 "2024-03-20T21:56:53Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![tndstn](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/tndstn/32/9943_2.png) [@tndstn](https://forum.opencv.org/u/tndstn)\
**Post date:** [March 20, 2024, 9:56pm UTC](https://forum.opencv.org/t/using-custom-color-palette-with-kmeans-color-clustering-algorithm/16904/1 "2024-03-20T21:56:53Z")

</div>

```
         bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), 
          data.getData());
            ny = new Mat();
            Utils.bitmapToMat(bitmap, ny);

       Mat bgrImage = new Mat();
        Imgproc.cvtColor(ny, bgrImage, Imgproc.COLOR_RGB2BGR);
        bgrImage.convertTo(bgrImage, CvType.CV_32F, 1.0 / 255.0);

        // Convert the image to grayscale canny ımage
         Mat gres = new Mat();
         Imgproc.cvtColor(ny, gres, Imgproc.COLOR_BGR2GRAY);

        // Compute median intensity
        double medianIntensity = Core.mean(gres).val[0];

        // Compute initial lower and upper thresholds
         double lowerThreshold = 0.8 * medianIntensity;
         double upperThreshold = 1.6 * medianIntensity;

        // Apply Canny edge detection with the computed thresholds
         Mat edges = new Mat();
         Imgproc.Canny(gres, edges, lowerThreshold, upperThreshold);

        // Find contours
        List<MatOfPoint> contours = new ArrayList<>();
        Mat hierarchy = new Mat();
        Imgproc.findContours(edges, contours, hierarchy, 
        Imgproc.THRESH_BINARY, Imgproc.CHAIN_APPROX_SIMPLE);

        // Reshape the image for k-means clustering
        Mat reshapedImage = bgrImage.reshape(1, bgrImage.rows() * 
         bgrImage.cols());

        // Perform k-means clustering
        Mat labels = new Mat();
        int K = 10;
        Mat centers = new Mat(K, reshapedImage.cols(), reshapedImage.type());

        TermCriteria criteria = new 
           TermCriteria(TermCriteria.EPTermCriteria.MAX_ITER, 10, 2.0);
        Core.kmeans(reshapedImage, K, labels, criteria, 1, 
         Core.KMEANS_PP_CENTERS, centers);

        // Reconstruct the clustered image
        Mat rec = new Mat(bgrImage.rows() * bgrImage.cols(), 3, CvType.CV_32F);
        for (int i = 0; i < reshapedImage.rows(); i++) {
            int j = (int) labels.get(i, 0)[0];
            centers.row(j).copyTo(rec.row(i));
        }

        // Reshape the reconstructed image to original size/type
        rec = rec.reshape(3, bgrImage.rows());
        rec.convertTo(rec, CvType.CV_8U, 255);
        Imgproc.cvtColor(rec, rec, Imgproc.COLOR_BGR2RGB);

        Mat biletra = new Mat();
        Imgproc.bilateralFilter(rec, biletra, 50, 50, 50, Core.BORDER_DEFAULT);
        Imgproc.drawContours(biletra,contours,-1 ,new Scalar (1,1,1),1);

        // Convert the processed image to Bitmap and display it
        Bitmap resultBitmap = Bitmap.createBitmap(rec.cols(), rec.rows(), 
        Bitmap.Config.ARGB_8888);
        Utils.matToBitmap(biletra, resultBitmap);
        anaekran.setImageBitmap(resultBitmap);

```

this is the code ı am using for color quantization it works but ı want to add custom color palettes and apply quantizaiton to the colors according to custom palettes is it possible with opencv

---

<div class="post-metadata">

**Author:** ![berak](https://avatars.discourse-cdn.com/v4/letter/b/85f322/32.png) [@berak](https://forum.opencv.org/u/berak)\
**Post date:** [March 21, 2024, 5:40am UTC](https://forum.opencv.org/t/using-custom-color-palette-with-kmeans-color-clustering-algorithm/16904/2 "2024-03-21T05:40:31Z")

</div>

just saying, using kmeans for quantization comes with some drawbacks:

- it’s local. the centers depend on the image content. a different image will give different centers
- the centers (or labels) are in random order. you might have label[2] == red in one image and green in another

> but ı want to add custom color palettes

have a look at [color maps in opencv](https://docs.opencv.org/3.4/d3/d50/group __imgproc__ colormap.html) and [lookup tables](https://docs.opencv.org/4.x/d2/de8/group __core__ array.html#gab55b8d062b7f5587720ede032d34156f)

---

<div class="post-metadata">

**Author:** ![tndstn](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/tndstn/32/9943_2.png) [@tndstn](https://forum.opencv.org/u/tndstn)\
**Post date:** [March 21, 2024, 6:21pm UTC](https://forum.opencv.org/t/using-custom-color-palette-with-kmeans-color-clustering-algorithm/16904/3 "2024-03-21T18:21:39Z")

</div>

so basiclly ı have to create custom colormaps and then ı have to apply colormap to the final output if didnt get this wrong

---

<div class="post-metadata">

**Author:** ![berak](https://avatars.discourse-cdn.com/v4/letter/b/85f322/32.png) [@berak](https://forum.opencv.org/u/berak)\
**Post date:** [March 22, 2024, 8:53am UTC](https://forum.opencv.org/t/using-custom-color-palette-with-kmeans-color-clustering-algorithm/16904/4 "2024-03-22T08:53:20Z")

</div>

> [@berak](#):
>
> but ı want to add custom color palettes

there are no _real_ palette images in opencv  
(this is a _computer-vision_ library)

> [@tndstn](#):
>
> so basiclly ı have to

btw, you never mentioned, what you want to achieve here

---

<div class="post-metadata">

**Author:** ![tndstn](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/tndstn/32/9943_2.png) [@tndstn](https://forum.opencv.org/u/tndstn)\
**Post date:** [March 22, 2024, 12:14pm UTC](https://forum.opencv.org/t/using-custom-color-palette-with-kmeans-color-clustering-algorithm/16904/5 "2024-03-22T12:14:18Z")

</div>

[Pallete Shader by GreenF0x](https://greenf0x.itch.io/pallete-shader) actually this is what i am trying to achieve as you can see you can rearrenge the colors of a image with a color palette and i assumed this application achieves this by applying custom palettes to kmeans algorithm which seems like not possible
