獲取靜態影象檢測專案並輸出結果
請注意,此示例使用 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
將具有四個主要屬性:x
,y
,width
和 height
。x
和 y
定義矩形的左上角位置,width
和 height
返回矩形寬度和高度的 int
。在將矩形繪製到影象上時使用此選項。Imgproc.rectangle
函式的最小必需引數如下:
Imgproc.rectangle(Mat image, Point start, Point end, Scalar color);
Point
用於左上角和右下角的位置。這些位置對於作為第一引數提供的影象是絕對的,而不是彼此。因此,除了 width
或 height
之外,你還必須新增矩形的 x
或 y
位置才能正確定義 end
Point。
請注意,這些引數中使用的 Point
類不是 Java 的標準庫的 Point
類。你必須匯入 OpenCV 的 Point
類!