This article aims to learn how to save an image from one location to any other desired location on your system in CPP using OpenCv. Using OpenCV, we can generate a blank image with any colour one wishes to.
So, let us dig deep into it and understand the concept with the complete explanation.
Code : C++ code for saving an image to any location in OpenCV.
#include <highlevelmonitorconfigurationapi.h>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\opencv.hpp>
using namespace cv;
using namespace std;
int main( int argc, char ** argv)
{
Mat img = imread( "..path\\abcd.jpg" );
if (img.empty()) {
cout << "Can not open or image is not present" << endl;
cin.get();
return -1;
}
bool check = imwrite( "..path\\MyImage.jpg" , img);
if (check == false ) {
cout << "Mission - Saving the image, FAILED" << endl;
cin.get();
return -1;
}
cout << "Successfully saved the image. " << endl;
String geek_window = "MY SAVED IMAGE" ;
namedWindow(geek_window);
imshow(geek_window, img);
waitKey(0);
destroyWindow(geek_window);
return 0;
}
|
Input :

Output :

Explanation :
Mat img = imread( "..path\\abcd.jpg" );
if (img.empty()) {
cout << "Can not open or image is not present" << endl;
cin.get();
return -1;
}
|
This part of the code reads the image from the path we have given to it. And it takes care of any error (if occurs). If there is no image present at this path, then “Can not open or image is not present” message will display and at the press of any key, the window will exit.
bool check = imwrite( "..path\\MyImage.jpg" , img);
if (check == false ) {
cout << "Mission - Saving the image, FAILED" << endl;
cin.get();
return -1;
}
cout << "Successfully saved the image. " << endl;
|
This part of the code write the image to the defined path and if not successful, it will generate “Mission – Saving the image, FAILED” message and at the press of any key, the window will exit. And rest of the code will create the window and display the image in it. It will keep on displaying the image in the window until the key is pressed. Finally, the window will be destroyed.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!