public static void main(String[] args) {
System.load("F:\\opencv\\x64\\opencv_java401.dll");
Mat src = Imgcodecs.imread("C:\\Users\\beawan\\Desktop\\test\\test.jpg");
Mat gray = new Mat();
Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
Mat th = new Mat();
Imgproc.threshold(gray, th, 120, 255, Imgproc.THRESH_BINARY);
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Imgproc.findContours(th, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
MatOfPoint2f mt2f = new MatOfPoint2f(contours.get(0).toArray()); //测试图片设定只有一个轮廓
RotatedRect rotatedRect = Imgproc.minAreaRect(mt2f);
Mat result = new Mat();
Imgproc.boxPoints(rotatedRect, result);
System.out.println(result.dump());
System.out.println("-----------------------");
System.out.println(result.get(0, 0)[0]);
System.out.println(result.get(1, 0)[0]);
System.out.println(result.get(2, 0)[0]);
System.out.println(result.get(3, 0)[0]);
System.out.println("-----------------------");
System.out.println(result.get(0, 1)[0]);
System.out.println(result.get(1, 1)[0]);
System.out.println(result.get(2, 1)[0]);
System.out.println(result.get(3, 1)[0]);
Point point1 = new Point(result.get(0, 0)[0], result.get(0, 1)[0]);
Point point2 = new Point(result.get(1, 0)[0], result.get(1, 1)[0]);
Point point3 = new Point(result.get(2, 0)[0], result.get(2, 1)[0]);
Point point4 = new Point(result.get(3, 0)[0], result.get(3, 1)[0]);
Imgproc.circle(src, point1, 5, new Scalar(255, 0, 0), -1);
Imgproc.circle(src, point2, 5, new Scalar(0, 255, 0), -1);
Imgproc.circle(src, point3, 5, new Scalar(0, 0, 255), -1);
Imgproc.circle(src, point4, 5, new Scalar(255, 255, 0), -1);
Imgcodecs.imwrite("C:\\Users\\beawan\\Desktop\\test\\test2.jpg", src);
}
输出:
[581.08801, 905.73328;
275.4473, 422.90952;
389.79187, 350.52625;
695.43262, 833.34998]
-----------------------
581.0880126953125
275.4472961425781
389.7918701171875
695.4326171875
-----------------------
905.7332763671875
422.9095153808594
350.5262451171875
833.3499755859375
测试图片:
输出图片