如何使用分水岭图像分割获得特定对象的像素计数[opencv]

yqhsw0fo  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(200)

我试图得到的总像素数的叶子是分段使用分水岭算法(刚才看到它在网上)。问题是,每当我使用mat::total()时,它都会从原始图像返回相同的像素计数。
我想如果我遵循这个网站的教程中的步骤,我可以使用垫子从背景中减去叶子图像。
我真的需要得到的对象像素计数,因为我将使用它也得到不同的颜色从该叶(例如,得到黄色像素(计数)从叶)。
请参考我的代码,帮助我找到我应该解决的错误。

private Mat getSureLeaf(Mat originalMat) {
    //Step 1: GrayScale
    /* IMAGE SEGMENTATION USING WATERSHED ALGORITHM */
    //Create a Mat Object using originalPicture as is:
    /* OTSU'S BINARIZATION */
    Mat grayscaleMat = new Mat();
    //check if i dont need to load_image as grayscale, if cvtColor does does work or vice versa:
    Imgproc.cvtColor(originalMat, grayscaleMat, Imgproc.COLOR_BGR2GRAY);
    Imgproc.threshold(grayscaleMat, grayscaleMat, 0, 255, Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU);

    Mat foregroundMat = new Mat();
    Imgproc.erode(grayscaleMat, foregroundMat, new Mat(),new Point(-1,-1),2);

    Mat backgroundMat = new Mat();
    Imgproc.dilate(grayscaleMat, backgroundMat, new Mat(), new Point(-1,-1), 3);
    Imgproc.threshold(backgroundMat, backgroundMat, 1,128, Imgproc.THRESH_BINARY_INV);

    //Markers image:
    Mat markersMat = new Mat(grayscaleMat.size(), CvType.CV_8U, new Scalar(0));
    Core.add(foregroundMat, backgroundMat, markersMat);

    Mat finalMat = markersMat;
    finalMat.convertTo(markersMat, CvType.CV_32S);
    Imgproc.watershed(originalMat, finalMat);
    //then return as CV_8U:
    // finalMat.convertTo(finalMat, CvType.CV_8U);

    leafMatPixCount = finalMat.total();
    Log.i(TAG, "Leaf Mat Pixel Count: " + leafMatPixCount);

return finalMat;
}

这是我的日志:

09-04 17:47:00.027 10392-10392/com.estaris.module_colordetection I/MainActivity: Original Pixel Count: 252480
09-04 17:47:00.090 10392-10392/com.estaris.module_colordetection I/MainActivity: Leaf Mat Pixel Count: 252480

ps:我希望分水岭函数已经从背景中扣除了对象。我非常感谢您的意见和建议。提前谢谢你。
更新:
此截图显示了原始图像和finalmat的图像。finalmat的背景显示灰色区域,所以我假设它被排除在白色遮罩之外(前景,如果我做得对的话)。
再次,我的问题是:finalmat真的把背景从叶子分割出来了吗,因为它显示叶子是白色的,背景是灰色的?如果是这样,我如何使用finalmat来计算从背景中排除的叶子本身的像素数(教程声称是这样做的)?
我真的需要从背景中排除叶子,这样我就可以用它来计算叶子的绿色和黄色,还有更多。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题