Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

it maybe far easier, than you thought:

Mat labels;
int n = connectedComponents(bin_img, labels);
// now, we have n different components there,
// get the mask for each of them
vector<Mat> masks;
for (size_t i=0; i<n; i++) {
    Mat mask;
    compare(labels, Scalar(i), mask, CMP_EQ);
    masks.push_back(mask);
}

it maybe far easier, than you thought:

Mat labels;
int n = connectedComponents(bin_img, labels);
// now, we have n n-1 different components there,
// (0 is background)
// get the mask for each of them
vector<Mat> masks;
for (size_t i=0; i=1; i<n; i++) {
    Mat mask;
    compare(labels, Scalar(i), mask, CMP_EQ);
    masks.push_back(mask);
}

it maybe far easier, than you thought:

Mat labels;
int n = connectedComponents(bin_img, labels);
// now, we have n-1 different components there,
// (0 is background)
// get the mask for each of them
vector<Mat> masks;
for (size_t i=1; i<n; i++) {
    Mat mask;
    compare(labels, Scalar(i), mask, CMP_EQ);
    masks.push_back(mask);
}

But I don't know why all my element in vector masks is same totally.

there is a pitfall with this vector constructor:

vector<Mat> vm(27,Mat(3,3,0,17));

now you have 27 items in the vector, but they all are the same Mat, pointing to the same data !

it maybe far easier, than you thought:

Mat labels;
int n = connectedComponents(bin_img, labels);
// now, we have n-1 different components there,
// (0 is background)
// get the mask for each of them
vector<Mat> masks;
for (size_t i=1; i<n; i++) {
    Mat mask;
    compare(labels, Scalar(i), mask, CMP_EQ);
    masks.push_back(mask);
}

But I don't know why all my element in vector masks is same totally.

there is a pitfall with this vector constructor:

vector<Mat> vm(27,Mat(3,3,0,17));

now you have 27 items in the vector, but they all are the same Mat, pointing to the same data !

the only way around that is initializing them in a loop:

vector<Mat> vm(27);
for (int i=0; i<27; i++)
     vm[i] = Mat(3,3,0,17);