opencv Using Cascade Classifiers In Java Getting a static image, detecting items on it, and outputting the results.


Please note that this example uses OpenCV 3.1.

import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

public class Classifier {
    private CascadeClassifier diceCascade = new
    private Mat image;
    private String loc = "path/to/image.png";
    private String output = "path/to/output.png";

    public void detImg() {
        Mat image = Imgcodecs.imread(loc); // Reads the image
        MatOfRect diceDetections = new MatOfRect(); // Output container
        diceCascade.detectMultiScale(image, diceDetections); // Performs the detection
        // Draw a bounding box around each detection.
        for (Rect rect : diceDetections.toArray()) {
            Imgproc.rectangle(image, new Point(rect.x, rect.y),
                new Point(rect.x + rect.width, rect.y + rect.height),
                new Scalar(0, 255, 0));
        // Save the visualized detection.
        Imgcodecs.imwrite(output, image);

The Rect[] returned by diceDetections.toArray() can be iterated over. Each Rect inside the array will have four main properties: x, y, width, and height. x and y defines the rectangle's top-left position, and width and height returns an int of the width and height of the rectangle. This is used when drawing rectangles onto images. The Imgproc.rectangle function's minimal required parameters are as follows:

Imgproc.rectangle(Mat image, Point start, Point end, Scalar color);

Both Point are used for the positions of the top-left corner and the lower-right corner. These positions are both absolute to the image provided as the first parameter, not to each other. Thus, you must add both the rectangle's x or y position in addition to the width or height to properly define the end Point.

Note that the Point class used in these parameters are not Java's standard library's Point class. You must import OpenCV's Point class instead!