Goals
In this tutorial you will learn how to:
- Load an image using cv::imread
- Transform an image from BGR to Grayscale format by using cv::cvtColor
- Save your transformed image in a file on disk (using cv::imwrite )
Code
Here it is:
#include <opencv2/opencv.hpp>
#include "string"
using namespace cv;
int main( int argc, char** argv )
{
String imageName = "Color_Image.jpg";
Mat image;
image = imread( imageName, 1 );
Mat gray_image;
cvtColor( image, gray_image, COLOR_BGR2GRAY );
imwrite( "Gray_Image.jpg", gray_image );
namedWindow( imageName, WINDOW_AUTOSIZE );
imshow( imageName, image );
imshow( "Gray image", gray_image );
waitKey(0);
return 0;
}
Explanation
- We begin by loading an image using cv::imread , located in the path given by imageName. For this example, assume you are loading a BGR image.
- Now we are going to convert our image from BGR to Grayscale format. OpenCV has a really nice function to do this kind of transformations:cvtColor( image, gray_image, COLOR_BGR2GRAY );
- a source image (image)
- a destination image (gray_image), in which we will save the converted image.
- an additional parameter that indicates what kind of transformation will be performed. In this case we use COLOR_BGR2GRAY (because of cv::imread has BGR default channel order in case of color images).
- So now we have our new gray_image and want to save it on disk (otherwise it will get lost after the program ends). To save it, we will use a function analagous to cv::imread : cv::imwriteimwrite( "Gray_Image.jpg", gray_image );
- Finally, let's check out the images. We create two windows and use them to show the original image as well as the new one:namedWindow( imageName, WINDOW_AUTOSIZE );imshow( imageName, image );imshow( "Gray image", gray_image );
- Add the waitKey(0) function call for the program to wait forever for an user key press.
Result
When you run your program you should get something like this:
And if you check in your folder (in my case images), you should have a newly .jpg file named Gray_Image.jpg:
Congratulations, you are done with this tutorial!
No comments:
Post a Comment