You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

scikit-image中threshold_local与threshold_adaptive结果不一致问题

解决skimage中threshold_adaptive警告与结果不符的问题

我来帮你搞定这个问题!你遇到的警告和结果不符的情况,本质是scikit-image版本更新带来的API变化导致的——threshold_adaptive已经被标记为弃用,它现在只是threshold_local的别名,但两者的返回值完全不一样:

  • 旧版本的threshold_adaptive直接返回阈值处理后的二值图像(0/1或True/False的矩阵)
  • 现在的threshold_local(也就是你调用threshold_adaptive实际执行的函数)返回的是与原图像同尺寸的阈值矩阵,你需要手动用原图像和这个阈值矩阵做比较,才能得到二值化结果

修改后的代码

把你的代码做两处小调整就能解决问题:

  1. 替换导入的函数为threshold_local(官方推荐直接使用这个,threshold_adaptive后续会被移除)
  2. 对threshold_local的返回值做一次比较操作,生成二值图像

完整代码如下:

import matplotlib.pyplot as plt
from skimage import data
from skimage.filters import threshold_otsu, threshold_local  # 替换threshold_adaptive为threshold_local

image = data.page()
global_thresh = threshold_otsu(image)
binary_global = image > global_thresh

block_size = 35
# 手动用原图像和阈值矩阵比较,得到二值结果
binary_adaptive = image > threshold_local(image, block_size, offset=10)

fig, axes = plt.subplots(nrows=3, figsize=(7, 8))
ax0, ax1, ax2 = axes
plt.gray()

ax0.imshow(image)
ax0.set_title('Image')
ax1.imshow(binary_global)
ax1.set_title('Global thresholding')
ax2.imshow(binary_adaptive)
ax2.set_title('Adaptive thresholding')

for ax in axes:
    ax.axis('off')

plt.show()

为什么原来的代码结果不对?

你之前的代码直接把threshold_adaptive现在返回的阈值矩阵当成了二值图像来显示,阈值矩阵的数值范围和二值图完全不同,所以显示结果自然不符合预期。加上image >的比较后,就能得到正确的自适应阈值二值化图像,同时那个警告也会消失。

内容的提问来源于stack exchange,提问作者Luis Ramon Ramirez Rodriguez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:59:17