获取静态图像检测项目并输出结果

请注意,此示例使用 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
        CascadeClassifier("res/newMethod/diceCascade.xml");
    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);
    
    }
}

diceDetections.toArray() 返回的 Rect[] 可以迭代。阵列中的每个 Rect 将具有四个主要属性:xywidthheightxy 定义矩形的左上角位置,widthheight 返回矩形宽度和高度的 int。在将矩形绘制到图像上时使用此选项。Imgproc.rectangle 函数的最小必需参数如下:

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

Point 用于左上角和右下角的位置。这些位置对于作为第一参数提供的图像是绝对的,而不是彼此。因此,除了 widthheight 之外,你还必须添加矩形的 xy 位置才能正确定义 end Point。

请注意,这些参数中使用的 Point不是 Java 的标准库的 Point 类。你必须导入 OpenCV 的 Point 类!