Android 手機拍攝圖片,畫面包含紅/綠/藍三色的三角形、圓形、矩形,需識別「指定顏色 + 指定形狀」的個數。
findContours(OpenCV)或 ConnectedComponents,獲得各連通區域。approxPolyDP),按頂點數判斷:3→三角形,4→矩形,>8→圓形(或用圓度 4π*Area/Perimeter² 判斷)。Map<String, Integer> 記錄「顏色_形狀」計數。org.opencv:opencv:4.x)Mat src = Imgcodecs.imread(path);
Mat hsv = new Mat();
Imgproc.cvtColor(src, hsv, Imgproc.COLOR_BGR2HSV);
for (ColorDef color : colors) {
Mat mask = new Mat();
Core.inRange(hsv, color.lower, color.upper, mask);
List<MatOfPoint> contours = new ArrayList<>();
Imgproc.findContours(mask, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
for (MatOfPoint cnt : contours) {
MatOfPoint2f approx = new MatOfPoint2f();
Imgproc.approxPolyDP(new MatOfPoint2f(cnt.toArray()), approx, 0.02 * Imgproc.arcLength(new MatOfPoint2f(cnt.toArray()), true), true);
int vertices = approx.toArray().length;
String shape = classify(vertices, cnt); // 三角形/矩形/圓形
counter.increment(color.name + "_" + shape);
}
}