如何使用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; }
執行上述程式後,我們將獲得以下輸出:
輸出
廣告