如何使用 Java OpenCV 對兩張圖片執行按位與運算?


可以使用 org.opencv.core.Core 類的 bitwise_and() 方法計算兩幅影像之間的按位與運算。

此方法接受三個表示源矩陣、目標矩陣和結果矩陣的 Mat 物件,計算源矩陣中每幅影像的按位與運算,並將結果儲存在目標矩陣中。

示例

在以下 Java 示例中,我們將一張影像轉換為二進位制和灰度,並計算結果的按位與運算。

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class BitwiseAndExample {
   public static void main(String args[]) throws Exception {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading the Image
      String file ="D://images//elephant.jpg";
      Mat src = Imgcodecs.imread(file, Imgcodecs.IMREAD_GRAYSCALE );
      HighGui.imshow("Grayscale Image", src);
      //Creating an empty matrix to store the results
      Mat dst = new Mat(src.rows(), src.cols(), src.type());
      Mat threshold = new Mat(src.rows(), src.cols(), src.type());
      Mat gray = new Mat(src.rows(), src.cols(), src.type());
      //Converting the gray scale image to binary image
      Imgproc.threshold(src, threshold, 100, 255, Imgproc.THRESH_BINARY_INV);
      HighGui.imshow("Binary Image", threshold);
      //Applying bitwise and operation
      Core.bitwise_and(src, threshold, dst);
      HighGui.imshow("Bitwise And operation", dst);
      HighGui.waitKey();
   }
}

輸入影像

輸出

執行上述程式時,會生成以下視窗 −

灰度影像 

二進位制影像 

按位與 

更新於: 2020 年 4 月 10 日

555 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.