How to keep those specify number of lagest component? [closed]

asked 2017-11-08 00:37:05 -0600

yode gravatar image

updated 2017-11-08 00:37:55 -0600

This is my test image

.

I wnat to keep those 4th largest component. For this target, I have write a ton code:

#include<opencv.hpp>
#include<vector>
using namespace std;
using namespace cv;

bool mygreater(const vector<int> a, const vector<int> b) {
    if (a[1] < b[1])
        return false;
    else
        return true;
}

int main() {
    Mat mask, img = imread("blobn.png", 0);

    threshold(img, mask, 0, 255, THRESH_OTSU);
    Mat labels;
    int n;
    n = connectedComponents(img, labels);
    vector<vector<int>> countCom;
    for (int i=0; i < n; i++) {
        vector<int> temp{ i,0 };
        countCom.push_back(temp);
    }
    //std::cout << labels.type();
    for (int i = 0; i < labels.rows; i++) {
        int* data = labels.ptr<int>(i);
        for (int j = 0; j < labels.cols; j++) {
            countCom[data[j]][1]++;
        }
    }

    countCom.erase(countCom.begin());


    sort(countCom.begin(),  countCom.end(), mygreater);

    vector<int> resultCom;
    for (int i = 0; i < 4; i++)
        resultCom.push_back(countCom[i][0]);

    cout << endl;

    for (int i = 0; i < 4; i++)
        cout << resultCom[i]<<"\t";
    for (int i = 0; i < labels.rows; i++) {
        int* data = labels.ptr<int>(i);
        for (int j = 0; j < labels.cols; j++)
            if (find(resultCom.begin(), resultCom.end(), data[j]) == resultCom.end())
                data[j] = 0;
    }

    return 0;
}

Is there any easy method can do this in our opencv?

edit retag flag offensive reopen merge delete

Closed for the following reason question is not relevant or outdated by sturkmen
close date 2020-09-26 14:26:47.524781

Comments

Use connectedComponentsWithStats to get surface and sort surface

LBerger gravatar imageLBerger ( 2017-11-08 15:41:10 -0600 )edit