如何使用 Java OpenCV 庫將彩色影像轉換為灰度影像?


Imgproc 類中的 cvtColor() 方法將影像的顏色從一種更改/轉換為另一種。此方法接受三個引數 −

  • src − 表示源的 Matrix 物件。

  • dst − 表示目標的 Matrix 物件。

  • code − 表示目標影像顏色的整數值。

若要將彩色影像轉換為灰度影像,你需將 Imgproc.COLOR_RGB2GRAY 傳遞為該方法的第三個引數。

示例

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class ColorToGrayscale {
   public static void main(String args[]) throws Exception {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading the image
      Mat src = Imgcodecs.imread("spiderman.jpg");
      //Creating the empty destination matrix
      Mat dst = new Mat();
      //Converting the image to grey scale
      Imgproc.cvtColor(src, dst, Imgproc.COLOR_RGB2GRAY);
      //Instantiating the Imagecodecs class
      Imgcodecs imageCodecs = new Imgcodecs();
      //Writing the image
      imageCodecs.imwrite("colortogreyscale.jpg", dst);
      System.out.println("Image Saved");
   }
}

輸入

輸出

更新於:08-Apr-2020

1K+ 瀏覽

啟動你的 職業

完成課程並獲得認證

開始
廣告