如何使用C++在OpenCV中加载和显示图像?


在本主题中,我们将确定如何使用C++中的OpenCV加载和显示图像。以下是在OpenCV中加载和显示图像所需的功能。

  • Mat: Mat不是函数。它是一种数据结构,一种变量类型。就像C++中的int、char、string变量类型一样,Mat是OpenCV的变量,它创建了一个矩阵数据结构来加载其中的图像。在这个程序中,我们写了'Mat myImage;'。这意味着我们正在声明一个名为'myImage'的矩阵变量。
  • namedWindow(): 它分配一些内存并创建一个窗口以显示图像。它就像一个相框。在OpenCV中,我们必须将函数设为'namedWindow("窗口名称",flag)'
  • 3. imread(): 此函数从定义的位置读取图像。此程序从“C:”驱动器读取图像。要使用此函数,您必须将其编写为'imread("图像位置/带有扩展名的图像名称", flag)'。
  • imshow(): 此函数在定义的窗口中显示图像。要使用此函数,您必须将其编写为'imshow("窗口名称", 矩阵名称)'
  • waitKey(): 这是OpenCV的重要函数。为了处理图像并执行操作,我们必须让系统花费一些时间。如果不这样做,我们将不会

此函数在关闭程序之前等待一段时间。如果您使用waitKey(10000),它将在10秒后关闭程序。如果您编写waitKey(0),它将获得所需的输出。此函数将使我们能够为系统提供所需的操作时间。等待用户的按键。当用户从键盘上按下任何键时,程序将停止。此函数必须写成'waitKey(毫秒数)'。

  • destroyWindows(): 此函数关闭所有窗口。当我们创建窗口时,我们会分配一些内存。destroyWindow()函数将该内存释放回系统。

以下程序演示了如何使用OpenCV库加载和显示图像。

示例

#include<iostream>
#include<opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
int main() {
   Mat myImage;//declaring a matrix named myImage//
   namedWindow("PhotoFrame");//declaring the window to show the image//
   myImage = imread("lakshmi.jpg");//loading the image named lakshme in the matrix//
   if (myImage.empty()) {//If the image is not loaded, show an error message//
      cout << "Couldn't load the image." << endl;
      system("pause");//pause the system and wait for users to press any key//
      return-1;
   }
   imshow("PhotoFrame", myImage);//display the image which is stored in the 'myImage' in the "myWindow" window//  
   destroyWindow("Photoframe");//close the window and release allocate memory//
   waitKey(0);//wait till user press any key
   return 0;
}

执行上述程序后,我们将获得以下输出:

输出

更新于: 2021年3月10日

3K+ 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.