Search code examples
javascriptimage-processingpixel

How to count number of color pixels or find out portion of color in image (js)?


I need to analyze an image and find out how much some specific color is present there using JS. Can anyone help?


Solution

  • I used this reference (stackoverflow)

    Base on the size of the image it can take a long time to solve that, but to give you a glance you can use the code below to pick one pixel form one image and then count all pixels with the same RGB and Alpha the exact color occurrences and portion of the color:

    Html part:

    <img id="my-image" onclick="doit()" src="test.jpg" />
    <div id="colorstat"></div>
    <script>
    

    Javascript Part:

    <scirpt>
    function doit(){
    // convert image to convas
    var img = document.getElementById('my-image');
    var canvas = document.createElement('canvas');
    // Get convas information
    canvas.width = img.width;
    canvas.height = img.height;
    canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
    // Find the click pixel color information
    var currentPixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;
    // show the color information in box
    document.getElementById('colorstat').innerHTML = "Chosed Color specification:" + "<br> R : " + currentPixelData[0] + "  G: " + currentPixelData[1] + " B: " + currentPixelData[2] + " Alpha : " +currentPixelData[3] + "<br>Image size: " + img.width + "x" + img.height + "<br>Waiting ...";
    // Start counting the occurance of the color in all pixels (Could take time)
    setTimeout(function() {
    colorCounter = 0;
    totaltxt = "";
        for (i=0;i<=img.width;i++)
        {
            for (j=0;j<=img.height;j++)
            {
            var PixelData = canvas.getContext('2d').getImageData(j, i, 1, 1).data;
            if(JSON.stringify(PixelData)==JSON.stringify(currentPixelData))
            {colorCounter += 1;}
            }
        }
    document.getElementById('colorstat').innerHTML = "Chosed Color specification:" + "<br> R : " + currentPixelData[0] + "  G: " + currentPixelData[1] + " B: " + currentPixelData[2] + " Alpha : " +currentPixelData[3] + "<br>Image size: " + img.width + "x" + img.height + "<br>Total Repeat: " + colorCounter + "<br> Portion: " + colorCounter/(img.width*img.height)*100 + "%";
    }, 200);
    }
    </script>