Advertisement
Cai_B

Extracting Main colour from an image

Apr 23rd, 2024 (edited)
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.24 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <iostream>
  3. #include "opencv2/core.hpp"
  4. #include "opencv2/highgui.hpp"
  5. #include "opencv2/imgproc.hpp"
  6.  
  7. using namespace cv;
  8. using namespace std;
  9.  
  10. int main()
  11. {
  12.   // namedWindow("Colour dominant in the Image:");
  13.  
  14.   Mat BitwiseImage;
  15.   Mat inputImage = imread("RedApple.bmp"); // Image is read in
  16.   string dominantColour;
  17.    
  18.   if (inputImage.empty())
  19.   {
  20.     cout<< "Can't find the image" <<endl;
  21.     return -1;
  22.   }
  23.  
  24.   Mat imageInHSV;
  25.   cvtColor(inputImage, imageInHSV, COLOR_BGR2HSV);
  26.  
  27.   // Different grayscale images  are created isolating RED/GREEN and BLUE pixels
  28.   Mat blueColourMask, greenColourMask, redColourMaskLow, redColourMaskHigh;
  29.   inRange(imageInHSV, Scalar(100, 50, 50), Scalar(140, 255, 255), blueColourMask);
  30.   inRange(imageInHSV, Scalar(35, 70, 50), Scalar(85, 255, 255), greenColourMask);
  31.   inRange(imageInHSV, Scalar(0, 50, 50), Scalar(10, 255, 255), redColourMaskLow);
  32.   inRange(imageInHSV, Scalar(170, 50, 50), Scalar(179, 255, 255), redColourMaskHigh);
  33.  
  34.   // Number of corresponding pixels of each colour are counted in each mask
  35.   int bluePixelCount = countNonZero(blueColourMask);
  36.   int greenPixelCount = countNonZero(greenColourMask);
  37.   int redPixelCountLow = countNonZero(redColourMaskLow);
  38.   int redPixelCountHigh = countNonZero(redColourMaskHigh);
  39.   int totalRedPixelCount = redPixelCountLow + redPixelCountHigh;
  40.  
  41.  
  42.   //Mask with the most pixels that aren't zero is the dominant colour
  43.   if (bluePixelCount >= greenPixelCount && bluePixelCount >= totalRedPixelCount)
  44.   {
  45.     dominantColour = "Blue";
  46.     bitwise_and(inputImage, inputImage, BitwiseImage, blueColourMask);
  47.   }
  48.   else if (greenPixelCount >= bluePixelCount && greenPixelCount >= totalRedPixelCount)
  49.   {
  50.     dominantColour = "Green";
  51.     bitwise_and(inputImage, inputImage, BitwiseImage, greenColourMask);
  52.   }
  53.   else
  54.   {
  55.     dominantColour = "Red";
  56.     bitwise_or(redColourMaskLow, redColourMaskHigh, redColourMaskLow);
  57.     bitwise_and(inputImage, inputImage, BitwiseImage, redColourMaskLow);
  58.   }
  59.  
  60.   cout << "Colour Dominant: " << dominantColour <<endl;
  61.  
  62.   imshow("Dominant Colour", inputImage);
  63.   imshow("Bitwise Operation Performed", BitwiseImage);
  64.  
  65.   waitKey(0);
  66.   destroyAllWindows();
  67.  
  68.   return 0;
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement