如何使用Java OpenCV庫繪製圖像輪廓?


輪廓不過是連線特定形狀邊界上所有點的線。使用它你可以:

  • 查詢物體的形狀。

  • 計算物體的面積。

  • 檢測物體。

  • 識別物體。

你可以使用 **findContours()** 方法找到影像中各種形狀、物體的輪廓。同樣,你可以繪製

你可以使用 **drawContours()** 方法繪製找到的影像輪廓,此方法接受以下引數:

  • 一個空的 Mat 物件來儲存結果影像。

  • 一個包含找到的輪廓的列表物件。

  • 一個整數,指定要繪製的輪廓(負值表示繪製所有輪廓)。

  • 一個 Scalar 物件,指定輪廓的顏色。

  • 一個整數,指定輪廓的粗細。

示例

import java.util.ArrayList;
import java.util.List;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class DrawingContours {
   public static void main(String args[]) throws Exception {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      String file ="D:\Images\shapes.jpg";
      Mat src = Imgcodecs.imread(file);
      //Converting the source image to binary
      Mat gray = new Mat(src.rows(), src.cols(), src.type());
      Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
      Mat binary = new Mat(src.rows(), src.cols(), src.type(), new Scalar(0));
      Imgproc.threshold(gray, binary, 100, 255, Imgproc.THRESH_BINARY_INV);
      //Finding Contours
      List<MatOfPoint> contours = new ArrayList<>();
      Mat hierarchey = new Mat();
      Imgproc.findContours(binary, contours, hierarchey, Imgproc.RETR_TREE,
      Imgproc.CHAIN_APPROX_SIMPLE);
      //Drawing the Contours
      Scalar color = new Scalar(0, 0, 255);
      Imgproc.drawContours(src, contours, -1, color, 2, Imgproc.LINE_8,
      hierarchey, 2, new Point() ) ;
      HighGui.imshow("Drawing Contours", src);
      HighGui.waitKey();
   }
}

輸入影像

輸出

執行上述程式後,將生成以下視窗:

更新於:2020年4月10日

2K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告