title: How to count the pixels of a certain color with OpenCV?
body: <p>I'm trying to calculate the percentage of pixels in a certain color range in a picture.</p>
  
  <p>I'm pretty new to OpenCV and python in general. What I've done is using the <code>cv2.inRange()</code> function to create a mask which I have as output. Right now I'm trying to do this with GRB color values between (0, 0, 130) and (80, 80, 255) and consider "red" every pixel whose color is in this range. So the output I get has two colors: black and red. 
  I used then this numpy function to get the number of non zero pixels which at this point I expected to be the number of red pixels: <code>red_pixel = np.count_nonzero(output)</code>.</p>
  
  <p>Here is the full code:</p>
  
  <pre><code>import cv2 
  import numpy as np
  
  img_name = input("What's the name of the picture? ")
  
  
  img = cv2.imread(img_name)
  
  # boundaries for the color red
  boundaries = [
      ([0, 0, 130], [80, 80, 255])
      ]
  
  for(lower, upper) in boundaries:
      # creates numpy array from boundaries
      lower = np.array(lower, dtype = "uint8")
      upper = np.array(upper, dtype = "uint8")
  
      # finds colors in boundaries a applies a mask
      mask = cv2.inRange(img, lower, upper)
      output = cv2.bitwise_and(img, img, mask = mask)
  
      # saves the image
      cv2.imwrite('2'+img_name, output)
  
  tot_pixel = output.size
  red_pixel = np.count_nonzero(output)
  percentage = round(red_pixel * 100 / tot_pixel, 2)
  
  print("Red pixels: " + str(red_pixel))
  print("Total pixels: " + str(tot_pixel))
  print("Percentage of red pixels: " + str(percentage) + "%")
  </code></pre>
  
  <p>I tested my code with four different pictures:</p>
  
  <p><a href="https://i.stack.imgur.com/KPgsq.jpg" rel="nofollow noreferrer">sea.jpg</a>
  which I'd expect to contain 0% of red. I run the program, as output I get a completely black image and the percentage is 0.00. Which is fine.</p>
  
  <p>I tried then this one:</p>
  
  <p><a href="https://i.stack.imgur.com/zDtc0.jpg" rel="nofollow noreferrer">sample.jpg</a>
  I run the program and what I get for the percentage is 13.76 which I don't know if it's correct but could still be.</p>
  
  <p>I tried a completely red image then: <a href="https://i.stack.imgur.com/vGXYy.jpg" rel="nofollow noreferrer">total-red.jpg</a>
  and I get 100.00 which is correct.</p>
  
  <p>The strange thing happens when I try with this image:
  <a href="https://i.stack.imgur.com/RWAxb.png" rel="nofollow noreferrer">almost-red.png</a></p>
  
  <p>What I get running the program is this output:
  <a href="https://i.stack.imgur.com/3VK3e.png" rel="nofollow noreferrer">2almost-red.png</a>
  which is what I expected. The percentage of non zero pixels though, is 33.07%
  and I have no idea why.</p>
  
  <p>Could you please help me figure out what I'm doing wrong and how I could correct the program? Thank you very much.</p>