个性化阅读
专注于IT技术分析

C++ OpenCV如何保存图像?代码实现详细指南

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

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

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

// c++ code explaining how to
// save an image to a defined
// location in OpenCV
  
// loading library files
#include <highlevelmonitorconfigurationapi.h>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\opencv.hpp>
  
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;
}

输入:

OpenCV |保存图像1

输出:

OpenCV |保存图像2

说明:

// 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;

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


赞(0)
未经允许不得转载:srcmini » C++ OpenCV如何保存图像?代码实现详细指南

评论 抢沙发

评论前必须登录!