Converting a color image ( 3-Channel image ) to grayscale image ( 1-channel ) using Opencv.
Steps:
1.0 convert_to_grayscale.cppSteps:
3.0 Compiling and Executing
Download code from
convert_to_grayscale.cpp
Include headers
1.1. Create two Mat object ( img, gray_img ).#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)
{
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 .
1.4. Save it to Gray_image.jpgcvtColor(img,gray_img,CV_BGR2GRAY);
1.5. Show it on open window.imwrite("../convert_to_grayscale/Gray_image.jpg", gray_img);
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.txtcmake_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
OUTPUT:cd /home/lokender/Desktop/convert_to_grayscale/
cmake
/home/lokender/Desktop/convert_to_grayscale/
make
./convert_to_grayscale loki.jpeg
Hope you enjoy this post. Don't Forget to share this post.