In this blog post we will learn how to convert an image to a greyscale image using OpenCV. OpenCv is amazing computer vision library. I am posting this article for computer vision beginners. Converting a color image (RGB image) into greyscale image is a very simple task if we use opencv library.

How to convert an image to a greyscale image using OpenCV

How to convert an image to a greyscale image using OpenCv

Following are the 3 steps to convert an image into greyscale image.

  • Read image with opencv API imread.
  • convert color image to greyscale image by using cvtColor( source_image, destination_image, CV_BGR2GRAY );
  • Save the converted image to disk by¬† imwrite( “/location”,¬†destination_image );
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main(int argc, char** argv)
	char* color_image = argv[1];

	Mat image;
	image = imread(color_image, 1);

	if (argc != 2 || ! {
		cout<<" No image data \n ";
		return -1;

	Mat gray_image;
	cvtColor(image, gray_image, CV_BGR2GRAY);

	imwrite("./myimage.jpg", gray_image);

	namedWindow("color image", CV_WINDOW_AUTOSIZE);
	namedWindow("grey image", CV_WINDOW_AUTOSIZE);

	imshow("color image", image);
	imshow("grey image", gray_image);


	return 0;

Compile the above code from terminal:

 g++ image.cpp -oimage `pkg-config --cflags --libs opencv`

You can use other tools like eclipse,visualc++ to compile the above code but you need to set environments of opencv into these tools.

Run executable image

boum@boum-Del-N5050:~$ ./image /path/source_image.jpg 

Your output would be as below and a new image named myimage.jpg would be created. you can see myimage.jpg into the current working directory.


Related Contents to follow