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算法

猜你喜欢