Android基于opencv进行图像识别并找出中心点和轮廓

代码:

Bitmap bitmapNew = bitmap.copy(Bitmap.Config.ARGB_8888, true);

//opencvプリプロセッサ
if (!OpenCVLoader.initDebug()) {
    Log.d("--------opencv--------", "OpenCVLoader error");
}
//Mat変換
Mat src = new Mat(bitmapNew.getHeight(), bitmapNew.getWidth(), CvType.CV_8UC4);
Utils.bitmapToMat(bitmapNew, src);
//グレー化
Imgproc.cvtColor(src, src, Imgproc.COLOR_RGB2GRAY);
//Gaussian Filters
Imgproc.GaussianBlur(src, src, new Size(1, 1), 0, 0);
//二値化
Imgproc.threshold(src, src, 0.0, 255.0,
        Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU);
//ビット反転
Mat hierarchy = Mat.zeros(new Size(1, 1), CvType.CV_8UC1);
Core.bitwise_not(src, src);
// 輪郭抽出
List contours = new ArrayList();
Imgproc.findContours(src, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_TC89_L1);

Mat dst = Mat.zeros(new Size(src.width(), src.height()), CvType.CV_8UC3);

// 輪郭を描画 (Yellow)
Scalar color = new Scalar(255, 255, 0);
Imgproc.drawContours(dst, contours, -1, color, 1);

List list = new ArrayList();
Rect box = null;
for (int i = 0; i < contours.size(); i++) {

    // 小さい輪郭を除去 (ノイズ除去)
    if (Imgproc.contourArea(contours.get(i)) < dst.size().area() / (1000)) {
        continue;
    }

    MatOfPoint ptmat = contours.get(i);

    // 輪郭の重心を描画 (Red)
    color = new Scalar(255, 0, 0);
    MatOfPoint2f ptmat2 = new MatOfPoint2f(ptmat.toArray());
    RotatedRect bbox = Imgproc.minAreaRect(ptmat2);
    box = bbox.boundingRect();
    Imgproc.circle(dst, bbox.center, 5, color, -1);
    list.add(bbox.center);

    // 輪郭を囲む四角形を描画 (Green)
    color = new Scalar(0, 255, 0);
    Imgproc.rectangle(dst, box.tl(), box.br(), color, 2);
}
Utils.matToBitmap(dst, bitmapNew);

如果想使用上述代码,还需要在build.gradle中的dependencies中添加

implementation 'com.quickbirdstudios:opencv:3.4.1'

 

你可能感兴趣的:(Android,android,opencv)