import cv2
import numpy as np

img1 = cv2.imread('../data/BnW.png', cv2.IMREAD_GRAYSCALE)

connectivity = 8
num_labels1, labelmap = cv2.connectedComponents(img1, connectivity, cv2.CV_32S)

img1 = np.hstack((img1, labelmap.astype(np.float32)/(num_labels1)))
cv2.imshow('Connected components', img1)

img2 = cv2.imread('../data/Lena.png', 0)
otsu_thr, otsu_mask = cv2.threshold(img2, -1, 1, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
output = cv2.connectedComponentsWithStats(otsu_mask, connectivity, cv2.CV_32S)

num_labels2, labelmap, stats, centers = output
colored = np.full((img2.shape[0], img2.shape[1], 3), 0, np.uint8)
for l in range(1, num_labels2):
    if stats[l][4] > 200:
        colored[labelmap == l] = (0, 255*l/num_labels2, 255*num_labels2/l)
        cv2.circle(colored, (int(centers[l][0]), int(centers[l][1])), 5, (255,0,0), cv2.FILLED)
        img2 = cv2.cvtColor(otsu_mask*255, cv2.COLOR_GRAY2BGR)
cv2.imshow('Connected components', np.hstack((img2, colored)))

cv2.waitKey()
cv2.destroyAllWindows()
