I have a sample image:
and I use different thresholding methods in order to count the number of pixels.
First Method is simple thresholding since on the source image I only have a one colored object against a white background.
Mat image = imread("/$image_path", IMREAD_GRAYSCALE);
Mat binary_image;
threshold(image, binary_image, 120, 255, THRESH_BINARY);
int TotalNumberOfPixels = binary_image.rows * binary_image.cols;
int PixelCount = TotalNumberOfPixels - cv::countNonZero(binary_image);
return PixelCount;
The second method is assuming I have an image with multiple colored objects (ie multiple colored marks) hence I need to filter and apply a red mask. I did it via:
Mat image2 = imread("/$image_path", IMREAD_COLOR);
Mat blurred, edge;
Mat bgrInv = ~image2;
Mat hsvIm;
Mat maskRed;
cvtColor(bgrInv, hsvIm, COLOR_BGR2HSV);
inRange(hsvIm, Scalar(80, 70, 239), Scalar(100, 255, 255), maskRed);
imshow("Mask", maskRed);
//blur(maskRed, blurred, Size(3, 3));
//Canny(blurred, edge, 75, 200, 3);
cout << "Pixel Count: " << countNonZero(maskRed)<< endl;
The output for both methods are:
Method 1: 406
Method 2: 155
I will be operating on a colored image hence I was using the second method at first. But I do not know if it will be "accurate" or correct.
Here is the sample template that I am working on. Its basically a survey type template with minor colored blocks. With red circles as mark placeholders for easier pre/post processing.