Wednesday, 20 January 2016

RGB to GrayScale Conversion

In OpenCV we can convert an RGB image into Grayscale by two ways:
1.  By using cvtColor function.

2.  By using imread function, where the first parameter specifies the image name while the second parameter specifies the format in which we need to add the image.
Thus there can be various formats like:
a. CV_LOAD_IMAGE_UNCHANGED (<0) :loads the image as is (including the alpha channel if present).
b. CV_LOAD_IMAGE_GRAYSCALE ( 0) :loads the image as an intensity one.
c. CV_LOAD_IMAGE_COLOR (>0) :loads the image in the RGB format.



//Opencv C++ Code for RGB to GreyScale Conversion
#include "opencv2/core/core.hpp"  
#include "opencv2/highgui/highgui.hpp"  
#include "iostream"  
 
  using namespace std;  
  using namespace cv;  
 
  int main() 
  {  
   Mat image;  
   //Reading the color image  
   image = imread("C:\\Users\\arjun\\Desktop\\image003.png", CV_LOAD_IMAGE_COLOR); 
 
   //If image not found  
   if (!image.data) 
     {  
      cout << "No image data \n";  
      return -1;  
     }  
 
   //Converting the Image into GrayScale and Storing it in a Matrix 'img_gray'
   Mat img_gray;
   img_gray = imread("C:\\Users\\arjun\\Desktop\\image003.png",CV_LOAD_IMAGE_GRAYSCALE);
    
    
   //Display the original image  
   namedWindow("Display Original Image",CV_WINDOW_AUTOSIZE);  
   imshow("Display Original Image", image);  
 
   //Display the grayscale image 
   namedWindow("Display Grayscale Image",CV_WINDOW_AUTOSIZE); 
   imshow("Display Grayscale Image", img_gray);  
 
   //Save the grayscale image with a name 'gray.jpg'
   imwrite("C:\\Users\\arjun\\Desktop\\gray.jpg",img_gray);
 
   waitKey(0);  
   return 0;  
  } 


Input:



Output:


No comments:

Post a Comment