title: Extracting the Percentage of color (Red,blue,green,yellow,orange) in an image in Opencv?
body: <p>I have to differentiate between 5 types of images which could have mostly either red,green, blue, orange or yellow color with some white or black color. I have to find which color is prominent in the image.</p>
  
  <p>The source of images is Webcam, so the actual color also depends upon the illumination and distance of the image from webcam. An example of my image can be seen here:</p>
  
  <p><a href="http://ian-albert.com/hazmat_placards/placard-2-flammable-gas.png" rel="nofollow">http://ian-albert.com/hazmat_placards/placard-2-flammable-gas.png</a></p>
  
  <p>I am trying to calculate the percentage based upon "Hue" values. I am specifying some range for each color. My ranges are:</p>
  
  <p><strong>Red:</strong> 0-10<br>
  <strong>Green:</strong> 50-65</p>
  
  <p><strong>Yellow:</strong> 18-21</p>
  
  <p><strong>Blue:</strong> 100-115</p>
  
  <p><strong>PROBLEM:</strong> Even though the image displayed is not Red still i am getting high % for red color.</p>
  
  <p>My code is following:</p>
  
  <pre><code>int findRect::checkByHSV(int svmResult, Mat detectedSquare)
  {
  
      Mat hsv_img;
      cvtColor(detectedSquare,hsv_img,CV_BGR2HSV);
  
      Vec3b pixel;
      float totalPixel=0; // to count the total number of pixels in an image---to get the Percentage later
      float totalClass[6];// because we want to test for 5 classes+ a garbage class.{{ Class-0 -&gt; Garbage, Class-1-&gt;Orange, Class-2-&gt;Green, Class-3-&gt;Red, 
                          //  Class-4-&gt;Blue, Class-5-&gt;Yellow }} 
  
      for(int i=0; i&lt;hsv_img.rows; i++)
      {
          for (int j=0; j&lt;hsv_img.cols; j++)
          {
  
              totalPixel++;
              pixel= hsv_img.at&lt;Vec3b&gt;(i,j);
  
              if(  pixel[0]&gt;0 &amp;&amp;  pixel[0]&lt;1  )           totalClass[1]++;    // Class-1-&gt;Orange
              else if (  pixel[0]&gt;50 &amp;&amp;  pixel[0]&lt;65  )   totalClass[2]++;    // To check Green class-2 //svmResult==2 &amp;&amp; 
              else if (  pixel[0]&gt;0 &amp;&amp;  pixel[0]&lt;10  )        totalClass[3]++;    // Class-3-&gt;Red
              else if (  pixel[0]&gt;100 &amp;&amp;  pixel[0]&lt;115  )     totalClass[4]++;    // Class-4-&gt;Blue
              else if (  pixel[0]&gt;18 &amp;&amp;  pixel[0]&lt;21  )       totalClass[5]++;    // Class-5-&gt;Yellow
          }
  
      }
  
      float percentage[5];
      totalClass[0]=0; //Putting zero to the Garbage class
  
      for (int i=0; i&lt;=5; i++)
      {
          percentage[i] = (totalClass[i] / totalPixel )*100;
      }
  
      cout&lt;&lt;"\n Organge: "&lt;&lt;percentage[1]&lt;&lt;"  Green: "&lt;&lt;percentage[2]&lt;&lt;"  Red: "&lt;&lt;percentage[3]&lt;&lt;"  Blue: "&lt;&lt;percentage[4]&lt;&lt;"  Yellow: "&lt;&lt;percentage[5]&lt;&lt;"\n \n";
  
      return svmResult;
  }
  </code></pre>