import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('coin.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
kernel = np.ones((3, 3), np.uint8)
noise_del = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel,iterations=2)
bg = cv2.dilate(noise_del, kernel, iterations=3)
dist_transform = cv2.distanceTransform(noise_del, cv2.DIST_L2, 5)
ret, fg = cv2.threshold(dist_transform, 0.5*dist_transform.max(), 255, 0)
fg = np.uint8(fg)
unknown = cv2.subtract(bg, fg)
ret, markers = cv2.connectedComponents(fg)
markers = markers + 1
markers[unknown == 255] = 0
makers = cv2.watershed(img, markers)
img[markers == -1] = [0, 0, 255]
images = [gray, thresh, bg, dist_transform, fg, unknown, markers, img]
titles = ["Gray", 'Binary', 'BG', 'Distance', 'FG', 'Unknown', 'Markers', 'Result']
for i in range(len(images)):
plt.subplot(2, 4, i+1), plt.imshow(images[i]), plt.title(titles[i]), plt.xticks([]), plt.yticks([])
plt.show()