6

i have a binary image and I want to remove small white dots from the image using opencv python.You can refer to my problem here enter link description here

My original image is

enter image description here

i want the output image as:

enter image description here

Krupali Mistry
  • 624
  • 1
  • 9
  • 23

3 Answers3

13

This seems to work using connected components in Python Opencv.

enter image description here

#!/bin/python3.7

import cv2
import numpy as np

src = cv2.imread('img.png', cv2.IMREAD_GRAYSCALE)

# convert to binary by thresholding
ret, binary_map = cv2.threshold(src,127,255,0)

# do connected components processing
nlabels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary_map, None, None, None, 8, cv2.CV_32S)

#get CC_STAT_AREA component as stats[label, COLUMN] 
areas = stats[1:,cv2.CC_STAT_AREA]

result = np.zeros((labels.shape), np.uint8)

for i in range(0, nlabels - 1):
    if areas[i] >= 100:   #keep
        result[labels == i + 1] = 255

cv2.imshow("Binary", binary_map)
cv2.imshow("Result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

cv2.imwrite("Filterd_result.png, result)


enter image description here

See here

fmw42
  • 46,825
  • 10
  • 62
  • 80
4

You can simply use image smoothing techniques like gaussian blur, etc. to remove noise from the image, followed by binary thresholding like below:

img = cv2.imread("your-image.png",0)
blur = cv2.GaussianBlur(img,(13,13),0)
thresh = cv2.threshold(blur, 100, 255, cv2.THRESH_BINARY)[1]

cv2.imshow('original', img)
cv2.imshow('output', thresh)
cv2.waitKey(0)
cv2.destroyAllWinsdows()

output:

enter image description here

Read about different image smoothing/blurring techniques from here.

Anubhav Singh
  • 8,321
  • 4
  • 25
  • 43
  • Thank you for the suggestion but using gaussian blur the edges would be affected so I want connectedcompoments function to work – Krupali Mistry Jul 31 '19 at 05:43
  • But there are also image blurring techniques which preserves the edges while removing noises like median blur, etc. So, why not you try those. – Anubhav Singh Jul 31 '19 at 05:52
1

You can use the closing function - erosion followed by dilation. It don't need the blurring function.

import cv2 as cv
import numpy as np

img = cv.imread('original',0)
kernel = np.ones((5,5),np.uint8)

opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)

cv2.imshow('original', img)
cv2.imshow('output', opening)
cv2.waitKey(0)
cv2.destroyAllWindows()
Sociopath
  • 13,068
  • 19
  • 47
  • 75