opencv MatOfPoint2f sort by x coordinate

Chanya Deshani :

I'm using opencv in java for an android project. I have a detected contour as a MatofPoint and I need to get corner points of the contour. Not the bounding rect.

I need to get top left, top right, bottom left bottom right corners of a approximately rectangular contour. So thinking to sort the points and divide the contour points to left and right first and then find the max x, min x and max y min y for each side.

Is there anyway to sot MatOfPoint2f by x coordinate?

I can't use

MatOfPoint2f contour = new MatOfPoint2f(contours.get(i).toArray());
contour.toList().sort();

as it requires API level 24

Sanjay Bhalani :

Try to user Collections.sort method of Java

//sort by y coordinates using the topleft point of every contour's bounding box
Collections.sort(contourList, new Comparator<MatOfPoint>() {
    @Override
    public int compare(MatOfPoint o1, MatOfPoint o2) {
        Rect rect1 = Imgproc.boundingRect(o1);
        Rect rect2 = Imgproc.boundingRect(o2);
        int result = Double.compare(rect1.tl().y, rect2.tl().y);
        return result;
    }
} );


 //sort by x coordinates
 Collections.sort(contourList, new Comparator<MatOfPoint>() {
    @Override
    public int compare(MatOfPoint o1, MatOfPoint o2) {
        Rect rect1 = Imgproc.boundingRect(o1);
        Rect rect2 = Imgproc.boundingRect(o2);
        int result = 0;
        double total = rect1.tl().y/rect2.tl().y;
        if (total>=0.9 && total<=1.4 ){
            result = Double.compare(rect1.tl().x, rect2.tl().x);
        }
        return result;
    }
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=144388&siteId=1