How to make a grayscale image in C++ using OpenCV

In this tutorial, we will learn how to convert a given image (RGB) to Grayscale using OpenCV in C++.

We access an image existing already on our machine and then convert it to a grayscale image using header files of OpenCV.

To convert an image to its GrayScale in C++ with OpenCV

Also Read:

In the code snippet given below, first, we enter the location of our image in the machine we are working with.

The snippet provided here is in visual studio but you can use any of the compilers after installing OpenCV and linking required directories.

After it we name the tabs having a grayscale and original colored image as per our wish. Then we read the image.

We use function cvtcolor() to convert the image to it’s Grayscale equivalent.

This function does require changes to the Red, Green, Blue variants of color.

Imshow() function is used to show the converted image and the previous one as well.

Also, note that we auto-size the image so as to overcome any size fit issues.

Original Image:

color image to grayscale image in C++ OpenCV


using namespace cv;
int main()
string file_name="D/bcup/DSC_0195.jpg";//all these three strings are part of CV and not the C++ library
cv::string window_original="original_image";
cv::string window_gray="gray_image";
cv::mat img = cv::imread(file_name);//It returns a matrix object

cv::mat graymat;
return 0;

Grayscale Image:

make grayscale image using OpenCV in C++


Also read:

Hope you have learned to convert an image to grayscale in C++.

Leave a Reply

Your email address will not be published. Required fields are marked *