参考、学习自Great
from skimage.segmentation import slicfrom skimage.segmentation import mark_boundariesfrom skimage.util import img_as_floatimport matplotlib.pyplot as pltimport numpy as npimport cv2# argsargs = {"image": './hand_0.png'}# load the image and apply SLIC and extract (approximately)# the supplied number of segmentsimage = cv2.imread(args["image"])segments = slic(img_as_float(image), n_segments=100, sigma=5)# show the output of SLICfig = plt.figure('Superpixels')ax = fig.add_subplot(1, 1, 1)ax.imshow(mark_boundaries(img_as_float(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)), segments))plt.axis("off")plt.show()print("segments:\n", segments)print("np.unique(segments):", np.unique(segments))# loop over the unique segment valuesfor (i, segVal) in enumerate(np.unique(segments)): # construct a mask for the segment print("[x] inspecting segment {}, for {}".format(i, segVal)) mask = np.zeros(image.shape[:2], dtype="uint8") mask[segments == segVal] = 255 # show the masked region cv2.imshow("Mask", mask) cv2.imshow("Applied", np.multiply(image, cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) > 0)) cv2.waitKey(0)