connected components
Connected Components
This opencv function helps to connected pixels into areas. It firstly needs to get the binary map of an image through threshold function.
And then returns the labels for the whole image. Each label correpond to a separate area on the image.
It also returns the stats about the areas, including the size of area, left & top positions of an area, the width and height of an area, etc.
'image' is an input image by cv2
#apply Otsu's algorithm to calculate thresholds for a later Canny operation
#thresh_img is the binary map
thresh, thresh_img = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
#remove stand alone dots / noises
connectivity = 4 # 4 way connection or 8
nlabels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh_img, connectivity, cv2.CV_32S)
areas = stats[:, cv2.CC_STAT_AREA]
# left = stats[:, cv2.CC_STAT_LEFT]
# top = stats[:, cv2.CC_STAT_TOP]
# width = stats[:, cv2.CC_STAT_WIDTH]
# height = stats[:, cv2.CC_STAT_HEIGHT]
#mean background gray level
background = np.mean(blur[labels == 0])# label 0 is for background
for label in range(1, nlabels):
if areas[label] <= small_dot_size: # area in piexles. small dots
image[labels == label] = background #erase the small area as background