运行GLCM计算代码触发rasterio循环导入属性错误如何解决
报错根因
AttributeError: partially initialized module 'rasterio' has no attribute '_loading' 这个报错和代码内部的循环导入逻辑无关,90%以上的触发场景是以下两种:
- 你的代码文件本身被命名为
rasterio.py,Python导入模块时优先加载同目录下的同名文件,而非系统安装的正式rasterio库,导致模块半初始化 - rasterio安装包损坏,或与numpy、GDAL等依赖版本不匹配,常见于非conda环境下直接pip安装未补全依赖的情况
报错修复步骤
- 立刻检查当前代码文件名,若命名为
rasterio.py直接重命名为其他名称,同时删除同目录下的__pycache__缓存文件夹后重新运行 - 若重命名后仍报错,执行以下命令重装干净的rasterio版本:
pip uninstall -y rasterio pip install rasterio -i https://pypi.tuna.tsinghua.edu.cn/simple
现有代码的其他问题修复
导入问题解决后,原代码仍存在3个会导致运行失败的问题,需一并修改:
- 调用了
rescale_intensity函数但未导入,该函数属于skimage.exposure模块 - Windows本地路径未加原始字符串标识,反斜杠会被识别为转义字符导致文件找不到
- GLCM计算要求输入灰度值范围与
levels参数匹配,设置levels=8时需先将图像灰度值量化到0-7的连续整数区间,否则会触发索引越界报错
修正后可直接运行的完整代码如下:
from skimage.feature import greycomatrix, greycoprops import numpy as np import rasterio from skimage.exposure import rescale_intensity # 路径加r前缀标识原始字符串,避免转义问题 img_path = r"D:\Fig-2-6-2D-slices-some-of-series-of-MRI-brain-image.png" with rasterio.open(img_path, 'r') as src: import_file = src.read() img = import_file[0, :, :] # 取第一个通道转为二维数组 # 灰度量化到0-7区间,适配GLCM levels=8的参数要求 img = rescale_intensity(img, out_range=(0, 7)).astype(np.uint8) print(f"输入图像维度:{img.shape}") # 生成GLCM矩阵,距离为1,统计4个方向 GLCM = greycomatrix( img, distances=[1], angles=[0, np.pi/4, np.pi/2, 3*np.pi/4], levels=8, symmetric=False, normed=True ) # 计算各纹理特征 contrast = greycoprops(GLCM, 'contrast') dissimilarity = greycoprops(GLCM, 'dissimilarity') homogeneity = greycoprops(GLCM, 'homogeneity') energy = greycoprops(GLCM, 'energy') correlation = greycoprops(GLCM, 'correlation') ASM = greycoprops(GLCM, 'ASM')
补充说明:scikit-image 0.19及以上版本中,
greycomatrix、greycoprops已更名为graycomatrix、graycoprops,若运行时提示函数不存在,将函数名中grey替换为gray即可。
内容的提问来源于stack exchange,提问作者sairam
相关产品推荐
相关产品推荐

