12
votes

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?

2
What criteria did you use to determine which objects to highlight? Why those particular 7 and any of the other similarly sized or smaller objects? - Dan Mašek
nn i want to remove all smalls object and this 7 its just example for object how i want to remove it - Zahra
@DanMašek I want to use the surface of the object as a criteria - Zahra
@DanMašek i know this method but i need to use a method without contour :( - Zahra
@Zahra Then why didn't you mention that fact (and specify that requirement) that in your question? - Dan Mašek

2 Answers

39
votes

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

3
votes

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.