Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

This is my current answer, I have increased the 99s to 0.004s now

Mat img(1000, 2000, CV_8UC1);
randu(img, Scalar(0), Scalar(255));
inRange(img, Scalar(160), Scalar(200), img);

Mat labels, stats, centroids;
int counts_img = connectedComponentsWithStats(img, labels, stats, centroids);

vector<int> drop_label(counts_img - 3);
iota(drop_label.begin(), drop_label.end(), 1);


vector<int> replace_table(counts_img);
iota(replace_table.begin(), replace_table.end(), 0);
for (int i : drop_label)
    replace_table[i] = 0;

//start to count the time.
double start_time = (double)getTickCount();

Mat select = img.clone() = 0;
int img_height = img.rows, img_width = img.cols;
for (int i = 0; i < img_height; i++) {
    int*plabels = labels.ptr<int>(i);
    uchar*pselect = select.ptr<uchar>(i);
    for (int j = 0; j < img_width; j++) {
        if (replace_table[plabels[j]] != 0)
            pselect[j] = 255;
    }
}

Mat result = img - select;

//total time
double total_time = ((double)getTickCount() - start_time) / getTickFrequency();
cout << "total time: " << total_time << "s" << endl;