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

WBOY
WBOY 转载
2023-08-28 14:37:05 188浏览

您可以使用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,如有侵犯,请联系admin@php.cn删除