首頁  >  文章  >  Java  >  如何使用OpenCV Java在影像中適應橢圓來圍繞可能的物件?

如何使用OpenCV Java在影像中適應橢圓來圍繞可能的物件?

WBOY
WBOY轉載
2023-08-28 14:37:05563瀏覽

您可以使用org.opencv.imgproc.Imgproc類別的fitEllipse()方法在形狀上適合一個橢圓形。此方法接受一個MatOfPoint2f類別的對象,計算適合給定點集的橢圓,並傳回一個RotatedRect對象。

使用此方法,您可以在圖像中繪製可能的物件周圍的橢圓。要這樣做,

  • 使用Imgproc類別的imread()方法讀取映像。

  • 使用Imgproc類別的cvtColor()方法將其轉換為灰階影像。

  • 使用Imgproc類別的threshold()方法將灰階影像轉換為二進位影像。

  • 使用Imgproc類別的findContours()方法在影像中尋找輪廓。

  • 現在,將每個輪廓值作為MatOfPoint2f傳遞給fitEllipse()方法,取得可能輪廓的RotatedRec對象。

  • 最後,使用ellipse()方法在可能的形狀周圍繪製橢圓。

注意 − 要適配橢圓,物件應至少包含五個點。

範例

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.MatOfPoint2f;
import org.opencv.core.RotatedRect;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class FitEllipseExample {
   public static void main(String args[]) throws Exception {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading the contents of the image
      String file ="D:\Images\javafx_graphical.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);
      //Empty rectangle
      RotatedRect[] rec = new RotatedRect[contours.size()];
      for (int i = 0; i < contours.size(); i++) {
         rec[i] = new RotatedRect();
         if (contours.get(i).rows() > 5) {
            rec[i] = Imgproc.fitEllipse(new MatOfPoint2f(contours.get(i).toArray()));
         }
         Scalar color_elli = new Scalar(190, 0, 0);
         Imgproc.ellipse(src, rec[i], color_elli, 5);
      }
      HighGui.imshow("Contours operation", src);
      HighGui.waitKey();
   }
}

 

輸入圖像

 如何使用OpenCV Java在图像中适应椭圆来围绕可能的对象? 

如何使用OpenCV Java在图像中适应椭圆来围绕可能的对象?

############################################## ##########################

以上是如何使用OpenCV Java在影像中適應橢圓來圍繞可能的物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除