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:
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章