利用随机游走算法进行图像分割
from skimage import io,img_as_ubyte,img_as_float
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
import numpy as np
# 读取图像
img = img_as_float(io.imread("macro-photography-of-strawberry-934066.jpg"))
gray_img = rgb2gray(img)
h,w = gray_img.shape
# 查看直方图
plt.hist(gray_img.flat,bins =100,range=(0,1))
# 随机游走分割
markers = np.zeros_like(gray_img)
markers[gray_img>0.8]=1
markers[gray_img<0.45]=2
from skimage.segmentation import random_walker
# 使用随机游走算法获得的结果
labels = random_walker(gray_img,markers,beta=10,mode="bf")
# plt.imshow(labels)
# 转换成布尔类型
segm1 = (labels<1.1)
# print(segm1)
# 形态学开运算操作
from skimage.morphology import opening,disk
kernel = disk(10)
img_opening = opening(segm1,kernel)
print(type(img_opening))
# 将单通道阈值,转为RGB通道的阈值
segm = np.tile(img_opening.reshape(h,w,1),3)
# print(segm)
# 复制彩色图像
rgb_img = img.copy()
# 掩膜操作
rgb_img[segm] = 0
# 显示图像
plt.figure(figsize=(10,8),dpi=80)
plt.subplot(121)
plt.imshow(img)
plt.xlabel("原图",fontproperties='SimHei')
plt.subplot(122)
plt.imshow(rgb_img)
plt.xlabel("分割结果",fontproperties='SimHei')
plt.show()
Figure_1.png
randomwalk.png
网友评论