OpenCV findContours 返回結果的順序

筆記

在做 OCR 的時候遇到了個坑,在使用了 findContours 查找文字區域的時候,發現返回的文字是倒序的,有時還是無序emmm。

找了很久才發現是這個函數的問題,它的實現算法並不是想當然的從左到右查找標記序號的(從整體來看)。所以要想輸出有序結果必須自己實現,如得到區域質心 Centroid ,可參考這篇詳解 http://opencvpython.blogspot.com/2012/06/contours-3-extraction.html

而對單行 OCR 文字區域,可以直接在 boudingRect 獲取的 Rect 基礎上,利用它們的 x 座標從左到右排序,這樣就可以了

備註

findContours 函數具體用法參考這裏 Java Code Examples for org.opencv.imgproc.Imgproc.findContours()

public List<Mat> findOrderContours(Mat m) {
        List<MatOfPoint> contours = new ArrayList<>();
        Imgproc.findContours(m, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
        List<Integer> axisX = new ArrayList<>(contours.size());
        List<Mat> orderContours = new ArrayList<>(contours.size());
        for (MatOfPoint matOfPoint : contours) {
            Rect cntRect = Imgproc.boundingRect(matOfPoint);
            // 插入排序
            int index;
            for (index = 0; index < axisX.size(); index++) {
                if (axisX.get(index) > cntRect.x)
                    break;
            }
            axisX.add(index, digitRect.x);
            orderContours.add(index, new Mat(m, cntRect).clone());
        }
        return orderContours;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章