How to save an image in OpenCV using C++

In this tutorial, we will learn how to save an image in OpenCV using C++.

To begin with, first, we should understand what is OpenCV. It is an open-source library used for image processing and various computer vision algorithms. It has a large number of inbuilt functions which are used to implement various image processing algorithms, which in turn makes advanced applications easy to use and more efficient.

OpenCV consists of a matrix class called Mat, with the help of this we store the image in the form of a matrix and then read the image using imread() function.

imwrite() function to save an image to a specified destination

OpenCV provides with imwrite() function to save an image to a specified destination. After we have read the image from the location we will use imwrite() function to save the image.

Code for saving the image.

//including the required header files
#include<iostream>
#include <highlevelmonitorconfigurationapi.h>
#include <opencv2\opencv.hpp>
#include <opencv2\highgui\highgui.hpp>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{

  // Reading the image file from the location
  //creating a matrix
  Mat img = imread("C:/codespeedy/build/Debug/image.jpg");

  //if image is not present
  if (img.empty()) {
    cout << "Cannot open the image or image is not present" << endl;

    
    cin.get();
    return -1;
  }
  // writing the image to the location where we want to save the image
  //using imwrite function to save the image to the desired location
  bool check = imwrite("C:/new_path/image.jpg", img);
  if (check == false) {
    cout << "Saving the image, FAILED" << endl;

    cin.get();
    return -1;
  }
  cout << " Image saved successfully " << endl;
  //Image has been saved to the desired location

  return 0;
}

Code Explanation-

Mat img = imread("C:/codespeedy/build/Debug/image.jpg");

1) Here we are reading the image from the given location.

bool check = imwrite("C:/new_path/image.jpg", img);

  
  if (check == false) {
    cout << "Saving the image, FAILED" << endl;

    cin.get();
    return -1;
  }

2. After reading the image which is stored using Mat class we are saving the image using imwrite() function. So, “image.jpg” will be saved to the“new_path” folder on the storage device. Also, if the image does not get saved successfully an error will be thrown.

cout << " Image saved successfully " << endl;
//Image has been saved to the desired location

3. If the image gets saved successfully, the message –“Image saved successfully” will be shown.

Output:

Image saved sucessfully

Now, we have learned to save the image in OpenCV using C++.

Also read: How to Detect and Decode QR Code from an image in C++ with OpenCV

 

One response to “How to save an image in OpenCV using C++”

  1. Vaibhav Chawla says:

    Very Informative. Thanks for writing this article.

Leave a Reply

Your email address will not be published.