Load and Display an Image - 加载并显示图像

Load and Display an Image - 加载并显示图像

OpenCV 4.2.0 - Modules
https://docs.opencv.org/4.2.0/index.html

OpenCV 4.2.0 - Tutorials
https://docs.opencv.org/4.2.0/d9/df8/tutorial_root.html

0. Load and Display an Image

https://docs.opencv.org/4.2.0/db/deb/tutorial_display_image.html
OpenCV modules -> OpenCV Tutorials -> Introduction to OpenCV -> Load and Display an Image

1. Goal

Load an image (using cv::imread) - 加载图像
Create a named OpenCV window (using cv::namedWindow)
Display an image in an OpenCV window (using cv::imshow) - 在 OpenCV 窗口中显示图像

2. Source Code

//============================================================================
// Name        : using namespace cv;
// Author      : Yongqiang Cheng
// Version     : Feb 22, 2020
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
	String imageName("./images/person.jpg"); // by default
	if (argc > 1)
	{
		imageName = argv[1];
	}

	Mat image;
	image = imread(samples::findFile(imageName), IMREAD_COLOR); // Read the file

	if (image.empty())                      // Check for invalid input
	{
		cout << "Could not open or find the image" << std::endl;
		return -1;
	}

	namedWindow("Display window", WINDOW_AUTOSIZE); // Create a window for display.
	imshow("Display window", image);                // Show our image inside it.
	waitKey(0); // Wait for a keystroke in the window

	return 0;
}

21:23:09 **** Build of configuration Debug for project DisplayImage ****
make all 
Building file: ../src/DisplayImage.cpp
Invoking: GCC C++ Compiler
g++ -std=c++0x -I/usr/local/include -I/usr/local/include/opencv4 -I/usr/local/include/opencv4/opencv2 -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/DisplayImage.d" -MT"src/DisplayImage.o" -o "src/DisplayImage.o" "../src/DisplayImage.cpp"
Finished building: ../src/DisplayImage.cpp
 
Building target: DisplayImage
Invoking: GCC C++ Linker
g++ -L/usr/local/lib -o "DisplayImage"  ./src/DisplayImage.o   -lopencv_core -lopencv_video -lopencv_ml -lopencv_imgproc -lopencv_img_hash -lopencv_flann -lopencv_features2d -lopencv_calib3d -lopencv_dnn -lopencv_dnn_objdetect -lopencv_cvv -lopencv_text -lopencv_datasets -lopencv_aruco -lopencv_bgsegm -lopencv_shape -lopencv_imgcodecs -lopencv_videoio -lopencv_highgui -lopencv_bioinspired
Finished building target: DisplayImage
 

21:23:10 Build Finished (took 1s.632ms)

在这里插入图片描述

3. Explanation

In OpenCV 2 we have multiple modules. Each one takes care of a different area or approach towards image processing. You could already observe this in the structure of the user guide of these tutorials itself. Before you use any of them you first need to include the header files where the content of each individual module is declared.
在 OpenCV 2 中,我们有多个模块。每个模块负责图像处理的不同区域或方法。您可能已经在这些教程本身的用户指南的结构中看到了这一点。在使用其中的任何一个之前,首先需要包括声明每个单独模块的内容的头文件。

You’ll almost always end up using the:

  • core section, as here are defined the basic building blocks of the library - 如此处所定义,是库的基本构建块
  • highgui module, as this contains the functions for input and output operations - 因为它包含输入和输出操作的功能
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>

We also include the iostream to facilitate console line output and input. To avoid data structure and function name conflicts with other libraries, OpenCV has its own namespace: cv. To avoid the need appending prior each of these the cv:: keyword you can import the namespace in the whole file by using the lines:
我们还包括 iostream,以方便控制台行的输出和输入。为了避免数据结构和函数名称与其他库冲突,OpenCV 有自己的命名空间:cv。为了避免在每个 cv:: 关键字之前附加前缀,您可以使用以下行将名称空间导入整个文件:

using namespace cv;
using namespace std;

This is true for the STL library too (used for console I/O). Now, let’s analyze the main function. We start up assuring that we acquire a valid image name argument from the command line. Otherwise take a picture by default: person.jpg.
STL 库也是如此 (用于控制台 I/O)。现在,让我们分析主要功能。我们开始确保从命令行获取有效的图像名称参数。否则默认情况下获取图像:person.jpg

    String imageName( "person.jpg" ); // by default
    if( argc > 1)
    {
        imageName = argv[1];
}

Then create a Mat object that will store the data of the loaded image.
然后创建一个 Mat 对象,该对象将存储加载的图像的数据。

Mat image;

Now we call the cv::imread function which loads the image name specified by the first argument (argv[1]). The second argument specifies the format in what we want the image. This may be:
现在我们调用 cv::imread 函数,该函数加载第一个参数 (argv[1]) 指定的图像名称。第二个参数指定所需图像的格式。这可能是:

  • IMREAD_UNCHANGED (<0) loads the image as is (including the alpha channel if present)
  • IMREAD_GRAYSCALE (0) loads the image as an intensity one
  • IMREAD_COLOR (>0) loads the image in the RGB format
image = imread( samples::findFile( imageName ), IMREAD_COLOR ); // Read the file
intensity [ɪnˈtensəti]:n. 强度,强烈,亮度,紧张

OpenCV offers support for the image formats Windows bitmap (bmp), portable image formats (pbm, pgm, ppm) and Sun raster (sr, ras). With help of plugins (you need to specify to use them if you build yourself the library, nevertheless in the packages we ship present by default) you may also load image formats like JPEG (jpeg, jpg, jpe), JPEG 2000 (jp2 - codenamed in the CMake as Jasper), TIFF files (tiff, tif) and portable network graphics (png). Furthermore, OpenEXR is also a possibility.
OpenCV 支持 Windows 位图 (bmp),可移植图像格式 (pbm, pgm, ppm) 和 Sun 栅格 (sr, ras) 图像格式。借助插件 (如果您自己构建库,则需要指定使用它们,但是默认情况下在我们提供的软件包中),您还可以加载图像格式,例如 JPEG (jpeg, jpg, jpe),JPEG 2000 (jp2 - 在 CMake 中代号为 Jasper),TIFF 文件 (tiff, tif) 和便携式网络图形 (png)。此外,OpenEXR 也有可能。

After checking that the image data was loaded correctly, we want to display our image, so we create an OpenCV window using the cv::namedWindow function. These are automatically managed by OpenCV once you create them. For this you need to specify its name and how it should handle the change of the image it contains from a size point of view. It may be:
在检查了图像数据是否正确加载之后,我们要显示图像,因此我们使用 cv::namedWindow 函数创建一个 OpenCV 窗口。创建它们后,这些文件将由 OpenCV 自动管理。为此,您需要指定其名称以及从大小的角度来看应如何处理其中包含的图像的更改。可能是:

  • WINDOW_AUTOSIZE is the only supported one if you do not use the Qt backend. In this case the window size will take up the size of the image it shows. No resize permitted!
    如果您不使用 Qt 后端,则仅支持 WINDOW_AUTOSIZE。在这种情况下,窗口大小将占据其显示图像的大小。不允许调整大小!

  • WINDOW_NORMAL on Qt you may use this to allow window resize. The image will resize itself according to the current window size. By using the | operator you also need to specify if you would like the image to keep its aspect ratio (WINDOW_KEEPRATIO) or not (WINDOW_FREERATIO).
    您可以在 Qt 上使用 WINDOW_NORMAL 来调整窗口大小。图像将根据当前窗口大小调整其大小。通过使用 | 运算符,还需要指定是否要保持图像的宽高比(WINDOW_KEEPRATIO) or not (WINDOW_FREERATIO)。

namedWindow( "Display window", WINDOW_AUTOSIZE ); // Create a window for display.

Finally, to update the content of the OpenCV window with a new image use the cv::imshow function. Specify the OpenCV window name to update and the image to use during this operation:
最后,要使用新图像更新 OpenCV 窗口的内容,请使用 cv::imshow 函数。指定要更新的 OpenCV 窗口名称以及此操作期间要使用的图像:

    imshow( "Display window", image );                // Show our image inside it.

Because we want our window to be displayed until the user presses a key (otherwise the program would end far too quickly), we use the cv::waitKey function whose only parameter is just how long should it wait for a user input (measured in milliseconds). Zero means to wait forever.
因为我们希望在用户按下某个键之前一直显示窗口 (否则程序会以太快的速度结束),所以我们使用 cv::waitKey 函数,其唯一的参数就是等待用户输入的时间 (以毫秒)。零意味着永远等待。

    waitKey(0); // Wait for a keystroke in the window

4. Result

  • Compile your code and then run the executable giving an image path as argument. If you’re on Windows the executable will of course contain an exe extension too. Of course assure the image file is near your program file.
    编译代码,然后运行给出图像路径作为参数的可执行文件。如果您使用的是 Windows,则可执行文件当然也会包含 exe 扩展名。当然,请确保图像文件位于程序文件附近。
./DisplayImage ../images/person.jpg
  • You should get a nice window as the one shown below:
发布了454 篇原创文章 · 获赞 1733 · 访问量 103万+

猜你喜欢

转载自blog.csdn.net/chengyq116/article/details/104450447