c++ - 如何计算二值图像上的白色物体?

标签 c++ opencv image-processing codeblocks

我正在尝试计算图像中的对象。我使用日志照片,并使用一些步骤来获取二进制图像。 enter image description here

这是我的代码:

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <features2d.hpp>
using namespace cv;
using namespace std;
int main(int argc, char *argv[])
{
    //load image
    Mat img = imread("kayu.jpg", CV_LOAD_IMAGE_COLOR);
    if(img.empty())
       return -1;
    //namedWindow( "kayu", CV_WINDOW_AUTOSIZE );
    imshow("kayu", img);

    //convert to b/w
    Mat bw;
    cvtColor(img, bw, CV_BGR2GRAY);
    imshow("bw1", bw);

    threshold(bw, bw, 40, 255, CV_THRESH_BINARY);
    imshow("bw", bw);

    //distance transform & normalisasi
    Mat dist;
    distanceTransform(bw, dist, CV_DIST_L2, 3);
    normalize(dist, dist, 0, 2., NORM_MINMAX);
    imshow("dist", dist);

    //threshold to draw line
    threshold(dist, dist, .5, 1., CV_THRESH_BINARY);
    imshow("dist2", dist);

    //dist = bw;
    //dilasi
    Mat dilation, erotion, element;
    int dilation_type = MORPH_ELLIPSE;
    int dilation_size = 17;

    element = getStructuringElement(dilation_type, Size(2*dilation_size + 1, 2*dilation_size+1), Point(dilation_size, dilation_size ));
    erode(dist, erotion, element);
    int erotionCount = 0;
    for(int i=0; i<erotionCount; i++){
        erode(erotion, erotion, element);
    }
    imshow("erotion", erotion);

    dilate(erotion, dilation, element);
    imshow("dilation", dilation);
    waitKey(0);
    return 0;
}

如您所见,我使用腐 eclipse 和膨胀来获得更好的原木圆形对象。我的问题是,我一直在数对象。我尝试了 SimpleBlobDetector 但一无所获,因为当我尝试将“扩张”步骤的结果转换为 CV_8U 时,白色对象消失了。我在使用 findContours() 时也遇到了错误。它说了一些关于图像 channel 的事情。我不能在这里显示错误,因为那一步太多了,我已经从我的代码中删除了它。

顺便说一句,最后,我得到了 1 个图像 channel 。 enter image description here 我可以只用它来计数,还是我必须转换它,最好的方法是什么?

最佳答案

两个简单的步骤:

  1. 找到二值化图像的轮廓。
  2. 获取等高线的数量。

代码:

int count_trees(const cv::Mat& bin_image){
    cv::Mat img;
    if(bin_image.channels()>1){
        cv::cvtColor(bin_image,img,cv::COLOR_BGR2GRAY);
    }
    else{
         img=bin_image.clone();;
    }
    if(img.type()!=CV_8UC1){
        img*=255.f; //This could be stupid, but I do not have an environment to try it
        img.convertTo(img,CV_8UC1);
    }

    std::vector<std::vector<cv::Point>> contours
    std::vector<Vec4i> hierarchy;
    cv::findContours( img, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
    return contours.size();
}

关于c++ - 如何计算二值图像上的白色物体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37540305/

相关文章:

c++ - 自定义命令行参数

c++ - 函数中未定义的参数

python - 在固定 block 中分割图像

android - 找不到ID为 'com.android.application'的插件

java - 卷积模糊滤镜不起作用并使图像变亮

java - 我将 matlab 代码构建到 Java 项目中,现在在运行调用该 matlab 函数的 java 代码行时遇到错误

c++ - 浮点值作为 C++ 数组中的索引

c++ - 定义在类内和类外的友元函数查找规则的区别

python - 是否可以从 python (cv2) 访问 OpenCV OCL (OpenCL) 方法?

python - 如何在 OpenCV 中找到二进制骨架图像的端点?