文章的最后有完整的一个实例的代码
图像自动阈值分割(基于skimage.filters)
图像阈值分割是一种广泛应用的分割技术,利用图像中要提取的目标区域与其背景在灰度特性上的差异,把图像看作具有不同灰度级的两类区域(目标区域和背景区域)的组合,选取一个比较合理的阈值,以确定图像中每个像素点应该属于目标区域还是背景区域,从而产生相应的二值图像。
在
skimage
库中,阈值分割的功能是放在
filters
模块中。我们可以手动指定一个阈值,从而来实现分割。也可以让系统自动生成一个阈值,下面几种方法就是用来自动生成阈值。
机器视觉领域许多算法都要求先对图像进行二值化。这种二值化操作阈值的选取非常重要。阈值选取的不合适,可能得到的结果就毫无用处。
简单的说,这类算法假设一副图像由前景色和背景色组成,通过统计学的方法来选取一个阈值,使得这个阈值可以将前景色和背景色尽可能的分开。或者更准确的说是在某种判据下最优。与数理统计领域的 fisher 线性判别算法其实是等价的。
一、threshold_otsu
基于Otsu的阈值分割方法,函数调用格式:
thresh = skimage.filters.threshold_otsu(image, nbins=256) # 返回一个阈值。
otsu算法中判据是最大类间方差 (intra-class variance or the variance within the class)。
更多参考http://blog.csdn.net/liyuanbhu/article/details/49387483
二、threshold_yen
thresh = filters.threshold_yen(image)
三、threshold_li
thresh = filters.threshold_li(image)
四、threshold_isodata
threshold = (image[image <= threshold].mean() +image[image > threshold].mean()) / 2.0
thresh = filters.threshold_isodata(image)
五、threshold_adaptive
thresh = skimage.filters.threshold_adaptive(image, block_size, method='gaussian')
'''
block_size: 块大小,指当前像素的相邻区域大小,一般是奇数(如3,5,7...)
method: 用来确定自适应阈值的方法,有'mean', 'generic', 'gaussian' 和 'median'。省略时默认为gaussian.该函数直接访问一个阈值后的图像,而不是阈值。
'''
完整实例代码:(Otsu)
from skimage import data, filters
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
# image = data.camera() # 大家测试的时候,直接从模块中的data中读取图片
image = Image.open('/Users/sushun/PycharmProjects/TRS_SearchByCharacters/picture/399.jpg').convert('L')
image = np.array(image)
print(image.shape)
thresh = filters.threshold_otsu(image) #
dst = (image <= thresh) * 1.0 # 根据阈值进行分割
# dst1 = filters.threshold_adaptive(image, 31, 'mean')
# dst2 = filters.threshold_adaptive(image, 5, 'median')
plt.figure('thresh', figsize=(8, 8))
plt.subplot(121)
plt.title('original image')
plt.imshow(image, plt.cm.gray)
plt.subplot(122)
plt.title('binary image')
plt.imshow(dst, plt.cm.gray)
plt.show()
效果如下:
# 上述代码中的
# dst1 = filters.threshold_adaptive(image, 31, 'mean')
# dst2 = filters.threshold_adaptive(image, 5, 'median')
dst1效果如下:
那么其他的方法大家不妨自己手动去敲一下/复制一下代码试一试,看一看更多的效果。