Python对图片进行二值化处理之Otsu算法

时间:2026-02-16 05:50:23

1、打开winPython包中的IDLE,即shell界面。

载入要用的工具箱:

from skimage import data,filters,color

import matplotlib.pyplot as plt

Python对图片进行二值化处理之Otsu算法

2、读取相关要进行灰度的图片:

image=color.rgb2gray(data.coffee())

Python对图片进行二值化处理之Otsu算法

3、对图片进行二值化处理,代码如下,前一句是获取阈值,后一个是进行二值化运算(后一个运算的<=符号可以根据自己的需求定义):

thresh = filters.threshold_otsu(image)

dst =(image <= thresh)*1.0

Python对图片进行二值化处理之Otsu算法

4、采用以下指令,来查看我们二值化的效果,代码如下:

plt.figure('thresh') 

plt.subplot(121) 

plt.imshow(image,plt.cm.gray) 

plt.subplot(122) 

plt.imshow(dst,plt.cm.gray) 

plt.show()

Python对图片进行二值化处理之Otsu算法

5、结果如下图。

Python对图片进行二值化处理之Otsu算法

© 2026 海能知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com