Thursday, September 12, 2013

How to convert a color image to grayscale (OpenCV)

Converting a color image ( 3-Channel image ) to grayscale image ( 1-channel ) using Opencv.

Steps:
1.0 convert_to_grayscale.cpp
    1.1. Create two Mat object ( img, gray_img ).
    1.2. Load image img using imread.
    1.3. Convert using cvtColor function .
    1.4. Save it to Gray_image.jpg
    1.5. Show it on open window.
2.0 CMakeLists.txt
3.0 Compiling and Executing

Download code from here

convert_to_grayscale.cpp

Include headers
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
1.1. Create two Mat object ( img, gray_img ).

  Mat img, gray_img;                           
  char* imgname =argv[1];

1.2. Load image img using imread. 
img = imread(argv[1],1);                    
  if(!img.data)
  {
   cout<<"Image data not found";
   return -1;
  }

1.3. Convert using cvtColor function .
cvtColor(img,gray_img,CV_BGR2GRAY);    
1.4. Save it to Gray_image.jpg
 imwrite("../convert_to_grayscale/Gray_image.jpg", gray_img);    
1.5. Show it on open window.
  namedWindow(imgname,CV_WINDOW_AUTOSIZE);
  namedWindow("Gray image", CV_WINDOW_AUTOSIZE);
  imshow(imgname, img);                             
  imshow("Gray Image", gray_img);
  waitKey(0);
  
  return 0;
}
2.0 CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
project( convert_to_grayscale )
find_package( OpenCV REQUIRED )
add_executable( convert_to_grayscale convert_to_grayscale.cpp )
target_link_libraries( convert_to_grayscale ${OpenCV_LIBS} )
3.0 Compiling and Executing
cd  /home/lokender/Desktop/convert_to_grayscale/
cmake /home/lokender/Desktop/convert_to_grayscale/
make
./convert_to_grayscale loki.jpeg
OUTPUT:














Hope you enjoy this post. Don't Forget to share this post.