Extracting text OpenCV

后端 未结 10 1963
臣服心动
臣服心动 2020-11-22 08:10

I am trying to find the bounding boxes of text in an image and am currently using this approach:

// calculate the local variances of the grayscale image
Mat          


        
10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 08:30

    Above Code JAVA version: Thanks @William

    public static List detectLetters(Mat img){    
        List boundRect=new ArrayList<>();
    
        Mat img_gray =new Mat(), img_sobel=new Mat(), img_threshold=new Mat(), element=new Mat();
        Imgproc.cvtColor(img, img_gray, Imgproc.COLOR_RGB2GRAY);
        Imgproc.Sobel(img_gray, img_sobel, CvType.CV_8U, 1, 0, 3, 1, 0, Core.BORDER_DEFAULT);
        //at src, Mat dst, double thresh, double maxval, int type
        Imgproc.threshold(img_sobel, img_threshold, 0, 255, 8);
        element=Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(15,5));
        Imgproc.morphologyEx(img_threshold, img_threshold, Imgproc.MORPH_CLOSE, element);
        List contours = new ArrayList();
        Mat hierarchy = new Mat();
        Imgproc.findContours(img_threshold, contours,hierarchy, 0, 1);
    
        List contours_poly = new ArrayList(contours.size());
    
         for( int i = 0; i < contours.size(); i++ ){             
    
             MatOfPoint2f  mMOP2f1=new MatOfPoint2f();
             MatOfPoint2f  mMOP2f2=new MatOfPoint2f();
    
             contours.get(i).convertTo(mMOP2f1, CvType.CV_32FC2);
             Imgproc.approxPolyDP(mMOP2f1, mMOP2f2, 2, true); 
             mMOP2f2.convertTo(contours.get(i), CvType.CV_32S);
    
    
                Rect appRect = Imgproc.boundingRect(contours.get(i));
                if (appRect.width>appRect.height) {
                    boundRect.add(appRect);
                }
         }
    
        return boundRect;
    }
    

    And use this code in practice :

            System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
            Mat img1=Imgcodecs.imread("abc.png");
            List letterBBoxes1=Utils.detectLetters(img1);
    
            for(int i=0; i< letterBBoxes1.size(); i++)
                Imgproc.rectangle(img1,letterBBoxes1.get(i).br(), letterBBoxes1.get(i).tl(),new Scalar(0,255,0),3,8,0);         
            Imgcodecs.imwrite("abc1.png", img1);
    

提交回复
热议问题