OpenCV read, modify, save image

code show as below:

 1 #include <cv.h>
 2 #include <highgui.h>
 3 
 4 using namespace cv;
 5 
 6 int main( int argc, char** argv )
 7 {
 8  if(argc != 2)
 9  {
10    printf("useage: %s <imagefile>\n ", argv[0]);
11    return -1;
12  }
13  char* imageName = argv[1];
14 
15  Mat image;
16  image = imread( imageName, CV_LOAD_IMAGE_COLOR);
17 
18  if( !image.data )
19  {
20    printf( " No image data \n " );
21    return -1;
22  }
23 
24  Mat gray_image;
25  cvtColor( image, gray_image, CV_BGR2GRAY );
26 
27 
28  imwrite( "../../images/Gray_Image.jpg", gray_image );
29 
30  namedWindow( imageName, CV_WINDOW_AUTOSIZE );
31  namedWindow( "Gray image", CV_WINDOW_AUTOSIZE );
32 
33  imshow( imageName, image );
34  imshow( "Gray image", gray_image );
35 
36  waitKey(0);
37 
38  return 0;
39 }

annotation

  1. First of all:

    • Creating Mat, used to save the image content.
    • Imread using the read image, the image path  imageName  , according to the image reading BGR format.
  2. Next, the RGB format image is converted to grayscale. Opencv in a ready transformation function:

    cvtColor( image, gray_image, CV_BGR2GRAY ); 

    cvtColor parameters are:

    • 源图像 (image) 。
    • 目标图像 (gray_image),用于保存转换图像。
    • 附加参数,用于指定转换的类型,例子中使用参数 CV_BGR2GRAY 。参数的具体定义请参见cvColor函数的API文档。
  3. 然后,使用函数 imwrite 将得到的灰度图像 gray_image 保存到硬盘。程序结束时,该灰度图像将会被释放。

    imwrite( "../../images/Gray_Image.jpg", gray_image ); 

    该函数,将图像写入到指定的文件夹下,程序执行时需保证该文件夹存在。示例中,将得到的灰度图像写到../../images/下,命名为Gray_Image.jpg。

  4. 最后,为了检验图像是否正确,将原始图像和灰度图像分别显示到打开的窗口中:

    namedWindow( imageName, CV_WINDOW_AUTOSIZE ); namedWindow( "Gray image", CV_WINDOW_AUTOSIZE ); imshow( imageName, image ); imshow( "Gray image", gray_image ); 
  5. 结尾的 waitKey(0) 函数,用于等待用户的按键操作来关闭窗口。

Guess you like

Origin www.cnblogs.com/ybqjymy/p/12170881.html