Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

findcontours in java not giving desired results

Hello All,

Today is my first day at OpenCV. I recently got fascinated with OCR and found OCV to be best and can do more than usual it. So after setting up my development environment I started to code. OCV version 2.4.5 JDK 1.7 Eclipse

I got the code the test code working. Somehow my contours are not getting matched. Not sure if I am missing something

import org.opencv.imgproc.*;

import org.opencv.core.; import org.opencv.highgui.; import java.util.*;

public class Test{

public static void main(String args[]){
    // Load the library

    System.loadLibrary("opencv_java245");

    // Consider the image for processing
    Mat image = Highgui.imread("C:/Users/patiprad/Desktop/IwQY6.png", Imgproc.COLOR_BGR2GRAY);
    Mat imageHSV = new Mat(image.size(), Core.DEPTH_MASK_8U);
    Mat imageBlurr = new Mat(image.size(), Core.DEPTH_MASK_8U);
    Mat imageA = new Mat(image.size(), Core.DEPTH_MASK_ALL);
    Imgproc.cvtColor(image, imageHSV, Imgproc.COLOR_BGR2GRAY);
    Imgproc.GaussianBlur(imageHSV, imageBlurr, new Size(5,5), 0);
    Imgproc.adaptiveThreshold(imageBlurr, imageA, 255,Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY,7, 5);

    Highgui.imwrite("C:/Users/patiprad/Desktop/test1.png",imageBlurr);

    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();    
    Imgproc.findContours(imageA, contours, new Mat(), Imgproc.RETR_LIST,Imgproc.CHAIN_APPROX_SIMPLE);
    //Imgproc.drawContours(imageBlurr, contours, 1, new Scalar(0,0,255));
    for(int i=0; i< contours.size();i++){
        System.out.println(Imgproc.contourArea(contours.get(i)));
        if (Imgproc.contourArea(contours.get(i)) > 50 ){
            Rect rect = Imgproc.boundingRect(contours.get(i));
            System.out.println(rect.height);
            if (rect.height > 28){
            //System.out.println(rect.x +","+rect.y+","+rect.height+","+rect.width);
            Core.rectangle(image, new Point(rect.x,rect.height), new Point(rect.y,rect.width),new Scalar(0,0,255));
            }
        }
    }
    Highgui.imwrite("C:/Users/patiprad/Desktop/test2.png",image);
}

}

Certainly am missing some basics here. Please find the result of the code.

Result.png Input.png