I am new to openCV and Python and a have a question concerning it. I am trying to find the amount of blue pixels of a picture so i can use them as a threshold in order to compare other pictures with it. I have tried looking through the documentation but i couldn't find anything helpful yet.
Can anyone give a hint or some help?
BLUE_MAX = np.array([0, 0, 200], np.uint8)
BLUE_MIN = np.array([50, 50, 255], np.uint8)
dst = cv.inRange(img, BLUE_VALUE_MIN, BLUE_VALUE_MAX)
no_blue = cv.countNonZero(dst)
print('The number of blue pixels is: ' + str(no_blue))
-So based on your recommendation I built the following function but all I get when I run it is a blank picture.
Counting Pixels As we know that each pixel in a coloured image ranges from [0-255] all-inclusive, the pixel value for the black color being 0 and that for the white color is 255.
The number of pixels is calculated by multiplying the horizontal and vertical pixel measurements. For example, HD has 1,920 horizontal pixels and 1,080 vertical pixels, which totals 2,073,600. It's normally shown as 1920 x 1080 or just as 1080p.
The total number of pixels will be its width multiplied by its height.
For counting blue pixel in a RGB image you can simply do the following
You can refer below C++ code for how to do it
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
Mat src,dst;
src = imread("rgb1.jpg",1);
inRange(src, Scalar(200,0,0), Scalar(255,50,50), dst); //In range with approximate blue range
cout<<"No of blue pixels---->"<<countNonZero(dst)<<endl;
imshow("src",src);
imshow("out",out);
waitKey(0);
return 0;
}
Here is the working python code
import cv2
import numpy as np
img = cv2.imread("bgr.png")
BLUE_MIN = np.array([0, 0, 200], np.uint8)
BLUE_MAX = np.array([50, 50, 255], np.uint8)
dst = cv2.inRange(img, BLUE_MIN, BLUE_MAX)
no_blue = cv2.countNonZero(dst)
print('The number of blue pixels is: ' + str(no_blue))
cv2.namedWindow("opencv")
cv2.imshow("opencv",img)
cv2.waitKey(0)
Hope this is what you looking for.....
As @ kigurai commented below OpenCV consider image in BGR order and I gave wrong order for BLUE_MIN and BLUE_MAX array. So in the above code the lines
BLUE_MIN = np.array([0, 0, 200], np.uint8)
BLUE_MAX = np.array([50, 50, 255], np.uint8)
should changed to
BLUE_MIN = np.array([200, 0, 0], np.uint8) // minimum value of blue pixel in BGR order
BLUE_MAX = np.array([255, 50, 50], np.uint8)// maximum value of blue pixel in BGR order
If you are looking for blue pixels in a photographed image, I recommend converting to HSV colour space first and then look for the color range for blue. This way, you can ignore the brightness component.
See this question for colour ranges in HSV color space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With