Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove small connected objects using OpenCV

I use OpenCV and Python and I want to remove the small connected object from my image.

I have the following binary image as input:

Input binary image

The image is the result of this code:

dilation = cv2.dilate(dst,kernel,iterations = 2)
erosion = cv2.erode(dilation,kernel,iterations = 3)

I want to remove the objects highlighted in red:

enter image description here

How can I achieve this using OpenCV?

like image 639
Zahra Avatar asked Mar 14 '17 23:03

Zahra


People also ask

How do you remove small objects in Python?

Remove small objects: L = labelmatrix(CC); BW2 = ismember(L, find([S. Area] >= P));

How do I remove black dots from an image in Python?

Try apply filter in frequency domain, your image after FFT will have regular bright dots, because your image noise. If you will remove these dots and make inverse FFT transform you will remove dots from your image. Check this examples please: example1 , example2 and example3.


2 Answers

How about with connectedComponentsWithStats :

#find all your connected components (white blobs in your image)
nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(img, connectivity=8)
#connectedComponentswithStats yields every seperated component with information on each of them, such as size
#the following part is just taking out the background which is also considered a component, but most of the time we don't want that.
sizes = stats[1:, -1]; nb_components = nb_components - 1

# minimum size of particles we want to keep (number of pixels)
#here, it's a fixed value, but you can set it as you want, eg the mean of the sizes or whatever
min_size = 150  

#your answer image
img2 = np.zeros((output.shape))
#for every component in the image, you keep it only if it's above min_size
for i in range(0, nb_components):
    if sizes[i] >= min_size:
        img2[output == i + 1] = 255

Output :enter image description here

like image 104
Soltius Avatar answered Sep 20 '22 08:09

Soltius


In order to remove objects automatically you need to locate them in the image. From the image you provided I see nothing that distinguishes the 7 highlighted items from others. You have to tell your computer how to recognize objects you don't want. If they look the same, this is not possible.

If you have multiple images where the objects always look like that you could use template matching techniques.

Also the closing operation doesn't make much sense to me.

like image 41
Piglet Avatar answered Sep 22 '22 08:09

Piglet