您可以使用org.opencv.imgproc.imgproc类的fitellipse()方法在形状上适配一个椭圆。该方法接受一个matofpoint2f类的对象,计算适合给定点集的椭圆,并返回一个rotatedrect对象。
使用此方法,您可以在图像中绘制可能的对象周围的椭圆。要这样做,
使用Imgproc类的imread()方法读取图像。
使用Imgproc类的cvtColor()方法将其转换为灰度图像。
使用Imgproc类的threshold()方法将灰度图像转换为二进制图像。
使用Imgproc类的findContours()方法在图像中查找轮廓。
立即学习“Java免费学习笔记(深入)”;
现在,将每个轮廓值作为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在图像中适应椭圆来围绕可能的对象?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号