Search code examples
pointopencv3.0noise

With opencv,How to use not erosion/dilation but connectedComponentsWithStas to remove dots?


I have read this:

Remove spurious small islands of noise in an image - Python OpenCV

erosion/dilation are suggested,and just wondering is it possible to do same thing by using connectedComponectsStats?I have googled,got these:

http://www.itkeyword.com/doc/5188188731707068417/how-to-use-opencvs-connected-components-with-stats-in-python

http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_features_harris/py_features_harris.html#corner-with-subpixel-accuracy

but from these,I can't figure out how to remove dots,so would you please tell me how to do it,thanks in advance!

update: What I really want to do is extracting human shape from blow image by remove small dots.

demo image


Solution

  • Using connectedComponentsWithStats you can do something like this:

    img = cv2.imread(directory + "canny.png")
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    labelnum, labelimg, contours, GoCs = cv2.connectedComponentsWithStats(gray)
    for label in xrange(1, labelnum):
        x,y,w,h,size = contours[label]
        if size <= 50:
             img[y:y+h, x:x+w] = 0
    cv2.imwrite(directory + "cca_image.png", img)
    

    For the image you uploaded, I got this as the result :

    Result image

    Does this work for you? I guess dilation/erosion before calling connectedComponentsWithStats would help, but I leave that for you to decide.