Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

drawning labeling components in a image opencv c++

I have the next image.

original image

I used the function connectedComponentsWithStats for find the components of the image. now i want draw only the components with an area > 3000, in this case there are 3 of the 5 components that the function found, i used the function "compare" for draw the 3 components but the result is not expected (only draw 1 component), Some idea for get the final result? thank you. my result is:

final result

int main(int argc, const char** argv)

{

img = imread("blob.png", 0);

if (img.empty())
{
    cout << "Could not read input image file: " << endl;
    return -1;
}

namedWindow("Image", 1);
imshow("Image", img);

Mat labelImage(img.size(), CV_32S);
Mat stats, centroids;
int nLabels = connectedComponentsWithStats(img, labelImage, stats, centroids, 8, CV_32S);
std::vector<Vec3b> colors(nLabels);
std::vector<int> labels_finals;
colors[0] = Vec3b(0, 0, 0);//background


for (int label = 1; label < nLabels; ++label){ //label  0 is the background
    if ((stats.at<int>(label, CC_STAT_AREA)) > 3000){
        labels_finals.push_back(label);
        //cout << "hola" << endl;
    }

    cout << "area del component: " << label << "-> " << stats.at<int>(label, CC_STAT_AREA) << endl;
    //colors[label] = Vec3b((rand() & 255), (rand() & 255), (rand() & 255));
    colors[label] = Vec3b(0, 255, 0);
}


Mat dst(img.size(), CV_8UC3);
for (int r = 0; r < dst.rows; ++r){
    for (int c = 0; c < dst.cols; ++c){

        int label = labelImage.at<int>(r, c);
        //cout << "label:  " << label << endl; 
        Vec3b &pixel = dst.at<Vec3b>(r, c);//accesa al elemento 
        pixel = colors[label];
    }
}

Mat dst2(img.size(), CV_8UC3);

for (int i = 0; i < labels_finals.size(); ++i){
    std::cout << "path i:  " << labels_finals[i] << ' ' << endl;
    compare(labelImage, labels_finals[i], dst2, CMP_EQ);
}

imshow("compare imagem ", dst2);

}