📜  OpenCV |保存图像

📅  最后修改于: 2021-05-30 02:39:02             🧑  作者: Mango

本文旨在学习如何使用OpenCv在CPP中将映像从一个位置保存到系统上的任何其他所需位置。使用OpenCV,我们可以生成具有任何颜色的空白图像。

因此,让我们深入研究它并以完整的解释来理解该概念。

代码:用于将图像保存到OpenCV中任何位置的C++代码。

// c++ code explaining how to
// save an image to a defined
// location in OpenCV
  
// loading library files
#include 
#include 
#include 
  
using namespace cv;
using namespace std;
  
int main(int argc, char** argv)
{
  
    // Reading the image file from a given location in system
    Mat img = imread("..path\\abcd.jpg");
  
    // if there is no image
    // or in case of error
    if (img.empty()) {
        cout << "Can not open or image is not present" << endl;
  
        // wait for any key to be pressed
        cin.get();
        return -1;
    }
  
    // You can make any changes
    // like blurring, transformation
  
    // writing the image to a defined location as JPEG
    bool check = imwrite("..path\\MyImage.jpg", img);
  
    // if the image is not saved
    if (check == false) {
        cout << "Mission - Saving the image, FAILED" << endl;
  
        // wait for any key to be pressed
        cin.get();
        return -1;
    }
  
    cout << "Successfully saved the image. " << endl;
  
    // Naming the window
    String geek_window = "MY SAVED IMAGE";
  
    // Creating a window
    namedWindow(geek_window);
  
    // Showing the image in the defined window
    imshow(geek_window, img);
  
    // waiting for any key to be pressed
    waitKey(0);
  
    // destroying the creating window
    destroyWindow(geek_window);
  
    return 0;
}

输入 :

输出 :

解释 :

// Reading the image file from a given location in system
Mat img = imread("..path\\abcd.jpg");
  
// if there is no image
// or in case of error
if (img.empty()) {
    cout << "Can not open or image is not present" << endl;
  
    // wait for any key to be pressed
    cin.get();
    return -1;
}

这部分代码从我们给它的路径中读取图像。并且它会处理任何错误(如果发生)。如果在此路径上没有图像,则将显示“无法打开或图像不存在”消息,按任意键,窗口将退出。

// writing the image to a defined location as JPEG
bool check = imwrite("..path\\MyImage.jpg", img);
  
// if the image is not saved
if (check == false) {
    cout << "Mission - Saving the image, FAILED" << endl;
  
    // wait for any key to be pressed
    cin.get();
    return -1;
}
  
cout << "Successfully saved the image. " << endl;

这部分代码将图像写入定义的路径,如果未成功,它将生成“任务-保存图像,失败”消息,并按任意键,窗口将退出。其余代码将创建窗口并在其中显示图像。它将一直在窗口中显示图像,直到按下该键为止。最终,该窗口将被销毁。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”