以下代码:
import numpy as np
import cv2
import matplotlib.pyplot as plt
image = cv2.imread("FYROJ.png")
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 3)
im_contours, contours, hier = cv2.findContours(thresh, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_NONE)
hier = hier[0]
kept_contours = [contour for idx, contour in enumerate(contours) if hier[idx][2] >= 0]
drawing = np.zeros_like(gray)
cv2.drawContours(drawing, kept_contours, -1, color=255)
ret, markers = cv2.connectedComponents(drawing)
watershed_res = cv2.watershed(image, np.int32(markers))
plt.imshow(watershed_res)
plt.show()
将生成此图像:
也许试着从这里开始,选择原始图像中有很多黑色像素的区域。。。