opencv案例--對象計數(shù)

問題描述

真實案例,農(nóng)業(yè)領(lǐng)域經(jīng)常需要計算對象個數(shù) 或者在其它領(lǐng)域拍照自動計數(shù),可以提供效率,減低成本

解決思路

通過二值分割+形態(tài)學(xué)處理+距離變換+連通區(qū)域計算

結(jié)果展示:

image.png
// ObjectCount.cpp : 此文件包含 "main" 函數(shù)。程序執(zhí)行將在此處開始并結(jié)束。
//問題描述
//真實案例,農(nóng)業(yè)領(lǐng)域經(jīng)常需要計算對象個數(shù) 或者在其它領(lǐng)域拍照自動計數(shù),可以提供效率,減低成本
//解決思路 
//通過二值分割 + 形態(tài)學(xué)處理 + 距離變換 + 連通區(qū)域計算

#include <iostream>
#include <opencv2/opencv.hpp>
#include <math.h>

using namespace cv;
using namespace std;


int main()
{

    Mat gray_src, binary, dst;
    Mat src = imread("D:\\case5.png");
    if (src.empty()) {
        printf("could not load image...\n");
        return -1;
    }



    imshow("input image", src);
    cvtColor(src, gray_src, COLOR_BGR2GRAY);

    // 二值分割  轉(zhuǎn)成黑白 
    threshold(gray_src, binary, 0, 255, THRESH_BINARY | THRESH_TRIANGLE);
    imshow("binary image", binary);

    //形態(tài)學(xué)操作
    Mat kernel = getStructuringElement(MORPH_RECT, Size(5, 5));
    //膨脹  亮度部分 黑色的范圍會變?。ò椎缀谏矬w)
    dilate(binary, binary, kernel, Point(-1, -1), 4);
    //imshow("dilate", binary);

    //距離變換
    Mat dist;
    bitwise_not(binary, binary);//取反(黑底白色物體)

    //計算圖像中每一個非零點距離離自己最近的零點的距離, 經(jīng)過簡單的運算,用于細(xì)化字符的輪廓和查找物體質(zhì)心(中心)
    distanceTransform(binary, dist, DIST_L2, 3);

    normalize(dist, dist, 0, 1.0, NORM_MINMAX);
    imshow("dist", dist);
    // 閾值化二值分割
    //threshold(dist, dist,0.7,1.0,THRESH_BINARY);//對距離進(jìn)行篩選,去除邊緣部分
    //normalize(dist, dist, 0, 255, NORM_MINMAX);
    Mat dist_8U;
    dist.convertTo(dist_8U, CV_8U);
    adaptiveThreshold(dist_8U, dist_8U, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 85, 0.0);//自適應(yīng)閾值,代替上面的閾值操作
    //形態(tài)學(xué)操作,使得斷開部分連接
    kernel = getStructuringElement(MORPH_RECT, Size(5, 5), Point(-1, -1));
    dilate(dist_8U, dist_8U, kernel, Point(-1, -1), 3);

    imshow("dist_8U", dist_8U);
    // 連通區(qū)域計數(shù)
    vector<vector<Point>> contours;
    findContours(dist_8U, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
    
    // draw result
    Mat markers = Mat::zeros(src.size(), CV_8UC3);
    RNG rng(12345);
    for (size_t t = 0; t < contours.size(); t++)
    {
     drawContours(markers, contours, static_cast<int>(t), Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)),
         - 1, 8, Mat());

    }
    printf("number of corns : %d", contours.size());
    imshow("Final result", markers);

    waitKey(0);

    return 0;

}


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容