Ask Your Question

Revision history [back]

Detect fixed string in the image

I need to find some fixed string in an image, there is a lot of string in the image and all of them digital print on it, but we need to find some string like this "asdf6543210" in the image. In my JAVA (Android) code, I can detect all strings in the image include this string, but how do I know this? Here's my code:

class Nuova2 {
public Mat analizza(Mat Main, Mat machPatern) {
    Mat rgb = new Mat();

    Imgproc.pyrDown(Main, rgb);

    Mat small = new Mat();
    Imgproc.cvtColor(rgb, rgb, Imgproc.COLOR_RGB2GRAY);
    //Imgproc.cvtColor(rgb, small, Imgproc.COLOR_RGB2GRAY);

    Mat grad = new Mat();

    Mat morphKernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(3, 3));

    Imgproc.morphologyEx(rgb, grad, Imgproc.MORPH_GRADIENT, morphKernel);

    Mat bw = new Mat();

    Imgproc.threshold(grad, bw, 0.0, 255.0, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU);

    Mat connected = new Mat();

    morphKernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(5, 6));

    Imgproc.morphologyEx(bw, connected, Imgproc.MORPH_CLOSE, morphKernel);


    Mat mask = Mat.zeros(bw.size(), CvType.CV_8UC1);

    List<MatOfPoint> contours = new ArrayList<MatOfPoint>();

    Mat hierarchy = new Mat();

    Imgproc.findContours(connected, contours, hierarchy, Imgproc.RETR_CCOMP, Imgproc.CHAIN_APPROX_SIMPLE, new Point(0, 0));

    for (int idx = 0; idx < contours.size(); idx++) {
        org.opencv.core.Rect rect = Imgproc.boundingRect(contours.get(idx));
        Mat maskROI = new Mat(mask, rect);
        Imgproc.drawContours(mask, contours, idx, new Scalar(255, 255, 255), Core.FILLED);

        double r = (double) Core.countNonZero(maskROI) / (rect.width * rect.height);

        if (r > .45 && (rect.height > 8 && rect.width > 8)) {
            Imgproc.rectangle(rgb, rect.br(), new Point(rect.br().x - rect.width, rect.br().y - rect.height), new Scalar(0, 255, 0));
        }

    }
    //String outputfile = "trovato.png";
    //Highgui.imwrite(outputfile,rgb);
    return rgb;
}

}