OpenCV 在 Java 中按区域对轮廓进行排序 [英] OpenCV Sorting Contours by Area in Java
本文介绍了OpenCV 在 Java 中按区域对轮廓进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我第一次使用 OpenCV,我无法找出按区域对轮廓进行排序的方法.我正在寻找两个最大的区域.目前我有:
This is my first time working with OpenCV, I am having trouble figuring out a method to sort the contours by area. I am looking for the two largest areas. Currently I have:
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Imgproc.findContours(MatOut, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
推荐答案
For Java 8+
For Java 8+
//finding max area
Optional<MatOfPoint> largest = contours.stream().max(new Comparator<MatOfPoint>() {
public int compare(MatOfPoint c1, MatOfPoint c2) {
return (int) (Imgproc.contourArea(c1)- Imgproc.contourArea(c2));
}
});
// sorting
contours.sort(new Comparator<MatOfPoint>() {
public int compare(MatOfPoint c1, MatOfPoint c2) {
return (int) (Imgproc.contourArea(c1)- Imgproc.contourArea(c2));
}
});
对于 Java 7,使用 Collections.sort 和相同的比较器并获取第一个元素.
For Java 7 use Collections.sort with same comparator and get the first element.
这篇关于OpenCV 在 Java 中按区域对轮廓进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文