Probably connectedComponentsWithStats
is not the most efficient way to remove dots. I would rather use the erosion or the opening (erosion+dilatation) morphology operator.
If you want to stuck with connectedComponentsWithStats
, the code (C++) will be:
for(int i=0;i<stats.rows;i++) //for each label
if(stats.at<ushort>(i,CC_STAT_AREA)<=3) //if area<3
for(int y=centroids.at<float>(i,1)-1;y<=centroids.at<float>(i,1)+1;y++) // scan the neighboring pixels
for(int x=centroids.at<float>(i,0)-1;x<=centroids.at<float>(i,0)+1;x++)
if(labels.at<ushort>(x,y)==i)image.at<uchar>(x,y))=0; // if the label matches, set the current pixel to 0
I commented the code, so it will be easier to rewrite in Python.