OpenCV - 讀取影像



org.opencv.imgcodecs 包中的 Imgcodecs 類提供了讀取和寫入影像的方法。使用 OpenCV,您可以讀取影像並將其儲存在矩陣中(如果需要,可以在矩陣上執行變換)。之後,您可以將處理後的矩陣寫入檔案。

Imgcodecs 類的 read() 方法用於使用 OpenCV 讀取影像。以下是此方法的語法。

imread(filename)

它接受一個引數 (filename),一個 String 型別的變數,表示要讀取的檔案的路徑。

以下是使用 OpenCV 庫在 Java 中讀取影像的步驟。

步驟 1:載入 OpenCV 本地庫

使用 load() 方法載入 OpenCV 本地庫,如下所示。

//Loading the core library 
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

步驟 2:例項化 Imgcodecs 類

例項化 Imgcodecs 類。

//Instantiating the Imgcodecs class 
Imgcodecs imageCodecs = new Imgcodecs();

步驟 3:讀取影像

使用 imread() 方法讀取影像。此方法接受一個字串引數,表示影像的路徑,並返回讀取的影像作為 Mat 物件。

//Reading the Image from the file  
Mat matrix = imageCodecs.imread(Path of the image);

示例

以下程式程式碼展示瞭如何使用 OpenCV 庫讀取影像

import org.opencv.core.Core; 
import org.opencv.core.Mat;  
import org.opencv.imgcodecs.Imgcodecs;
 
public class ReadingImages {
   public static void main(String args[]) { 
      //Loading the OpenCV core library  
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); 
     
      //Instantiating the Imagecodecs class 
      Imgcodecs imageCodecs = new Imgcodecs(); 
     
      //Reading the Image from the file  
      String file ="C:/EXAMPLES/OpenCV/sample.jpg"; 
      Mat matrix = imageCodecs.imread(file); 
     
      System.out.println("Image Loaded");     
   } 
}

執行上述程式後,OpenCV 載入指定的影像並顯示以下輸出:

Image Loaded
廣告

© . All rights reserved.