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

基于分水岭变换的区域生长代码提取图像标记触发IndexError报错

报错根因

报错指向im_[:,:,0]代码行,触发原因是输入的img2为2维单通道灰度图像,没有第三个通道维度,但原代码默认针对3通道RGB图像编写,强行索引第0、1、2通道就会触发维度越界错误。

解决方案

方案1:适配单通道灰度图像输入

直接修改梯度计算逻辑,无需拆分RGB通道,修改后代码如下:

from skimage.filters import rank,gaussian
from skimage.morphology import disk
from skimage.feature import peak_local_max
import matplotlib.pyplot as plt

def get_markers(img2, indices=False):
    im_ = gaussian(img2, sigma=4)
    # 单通道直接计算梯度即可
    grad = rank.gradient(im_, disk(5)).astype('int')
    return peak_local_max(grad.max()-grad,threshold_rel=0.5, min_distance=60,indices=indices),grad

# 运行前可先打印维度确认
print("输入图像维度:", img2.shape)
markers,grad = get_markers(img2, True)
plt.figure()
plt.imshow(grad, cmap=plt.cm.gray)
plt.plot(markers[:,1],markers[:,0],'b+')
plt.show()

方案2:保持原RGB逻辑使用

如果你的业务场景需要处理彩色图像,检查图像读取环节的代码:

  • 确认读入图像时没有手动做灰度转换操作
  • 若使用OpenCV读入图像,需要额外把默认的BGR格式转为RGB格式,再传入函数使用

内容的提问来源于stack exchange,提问作者Caliginous

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:06:02