这是一种使用交互式图像分割的方法。在这种方法中,您必须手动标记一些前景像素和一些背景像素,如下所示:
(我在 MS Paint 中进行了标记。)下面的代码使用函数 skimage.segmentation.random_walker 进行图像分割,并生成这个分割图像:
(这种方法还可以处理具有更复杂背景区域的图像。)这是代码:
import skimage
import skimage.viewer
import skimage.segmentation
import skimage.data
import skimage.io
import matplotlib.pyplot as plt
import numpy as np
img = skimage.io.imread("D:/Users/Pictures/img.jpg")
imgLabeled = skimage.io.imread("D:/Users/Pictures/imgLabeled.jpg")
redChannel = imgLabeled[:,:,0]
greenChannel = imgLabeled[:,:,1]
blueChannel = imgLabeled[:,:,2]
markers = np.zeros(img.shape,dtype=np.uint)
markers[(redChannel < 20) & (greenChannel > 210) & (blueChannel < 20)] = 1
markers[(redChannel < 20) & (greenChannel < 20) & (blueChannel > 210)] = 2
plt.imshow(markers)
labels = skimage.segmentation.random_walker(img, markers, beta=1000, mode='cg')
seg1 = np.copy(img)
seg1[labels==2] = 0
seg2 = np.copy(img)
seg2[labels==1] = 0
# plt.imsave("D:/Users/Pictures/imgSeg.png",seg1)
plt.figure()
plt.imshow(seg1)
plt.figure()
plt.imshow(seg2)