Python计算灰度共生矩阵和常用的纹理因子

2024-04-12 17:58

本文主要是介绍Python计算灰度共生矩阵和常用的纹理因子,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

如何使用skimage计算GLCM和纹理因子可以参考利用python的skimage计算灰度共生矩阵。但是Skimage库只提供了常用的8中纹理因子(均值、方差、同质性、对比度、差异性、熵、角二阶矩、相关性、)中的5种,缺少均值、方差和熵的计算。这里讲解如何修改源码添加这三个因子的计算。添加后调用方式和其他因子的计算相同。

修改/添加部分

找到 skimage库greycoprops源码。Spyder可以直接右键该函数,转到定义处。
需要添加/修改的部分,保持了与源码相同的编码风格,全是numpy向量化计算。

...............elif prop in ['ASM', 'energy', 'correlation', 'mean', 'variance', 'entroy']:
...............elif prop == 'mean':results = np.apply_over_axes(np.mean, P, axes=(0, 1))[0, 0]elif prop == 'variance':results = np.apply_over_axes(np.sum,(P - np.apply_over_axes(np.mean, P, axes=(0, 1)))**2,axes=(0, 1))[0, 0]elif prop == 'entroy':with np.errstate(divide='ignore'):condition_list = [P != 0, P == 0]choice_list = [-np.log10(P), 0]P = np.select(condition_list, choice_list)results = np.apply_over_axes(np.sum, P, axes=(0, 1))[0, 0]
..............

完整源码

def greycoprops(P, prop='contrast'):"""Calculate texture properties of a GLCM.Compute a feature of a grey level co-occurrence matrix to serve asa compact summary of the matrix. The properties are computed asfollows:- 'contrast': :math:`\\sum_{i,j=0}^{levels-1} P_{i,j}(i-j)^2`- 'dissimilarity': :math:`\\sum_{i,j=0}^{levels-1}P_{i,j}|i-j|`- 'homogeneity': :math:`\\sum_{i,j=0}^{levels-1}\\frac{P_{i,j}}{1+(i-j)^2}`- 'ASM': :math:`\\sum_{i,j=0}^{levels-1} P_{i,j}^2`- 'energy': :math:`\\sqrt{ASM}`- 'correlation':.. math:: \\sum_{i,j=0}^{levels-1} P_{i,j}\\left[\\frac{(i-\\mu_i) \\(j-\\mu_j)}{\\sqrt{(\\sigma_i^2)(\\sigma_j^2)}}\\right]Each GLCM is normalized to have a sum of 1 before the computation of textureproperties.Parameters----------P : ndarrayInput array. `P` is the grey-level co-occurrence histogramfor which to compute the specified property. The value`P[i,j,d,theta]` is the number of times that grey-level joccurs at a distance d and at an angle theta fromgrey-level i.prop : {'contrast', 'dissimilarity', 'homogeneity', 'energy', \'correlation', 'ASM'}, optionalThe property of the GLCM to compute. The default is 'contrast'.Returns-------results : 2-D ndarray2-dimensional array. `results[d, a]` is the property 'prop' forthe d'th distance and the a'th angle.References----------.. [1] The GLCM Tutorial Home Page,http://www.fp.ucalgary.ca/mhallbey/tutorial.htmExamples--------Compute the contrast for GLCMs with distances [1, 2] and angles[0 degrees, 90 degrees]>>> image = np.array([[0, 0, 1, 1],...                   [0, 0, 1, 1],...                   [0, 2, 2, 2],...                   [2, 2, 3, 3]], dtype=np.uint8)>>> g = greycomatrix(image, [1, 2], [0, np.pi/2], levels=4,...                  normed=True, symmetric=True)>>> contrast = greycoprops(g, 'contrast')>>> contrastarray([[0.58333333, 1.        ],[1.25      , 2.75      ]])"""check_nD(P, 4, 'P')(num_level, num_level2, num_dist, num_angle) = P.shapeif num_level != num_level2:raise ValueError('num_level and num_level2 must be equal.')if num_dist <= 0:raise ValueError('num_dist must be positive.')if num_angle <= 0:raise ValueError('num_angle must be positive.')# normalize each GLCMP = P.astype(np.float64)glcm_sums = np.apply_over_axes(np.sum, P, axes=(0, 1))glcm_sums[glcm_sums == 0] = 1P /= glcm_sums# create weights for specified propertyI, J = np.ogrid[0:num_level, 0:num_level]if prop == 'contrast':weights = (I - J) ** 2elif prop == 'dissimilarity':weights = np.abs(I - J)elif prop == 'homogeneity':weights = 1. / (1. + (I - J) ** 2)elif prop in ['ASM', 'energy', 'correlation', 'mean', 'variance', 'entroy']:passelse:raise ValueError('%s is an invalid property' % (prop))# compute property for each GLCMif prop == 'energy':asm = np.apply_over_axes(np.sum, (P ** 2), axes=(0, 1))[0, 0]results = np.sqrt(asm)elif prop == 'ASM':results = np.apply_over_axes(np.sum, (P ** 2), axes=(0, 1))[0, 0]elif prop == 'correlation':results = np.zeros((num_dist, num_angle), dtype=np.float64)I = np.array(range(num_level)).reshape((num_level, 1, 1, 1))J = np.array(range(num_level)).reshape((1, num_level, 1, 1))diff_i = I - np.apply_over_axes(np.sum, (I * P), axes=(0, 1))[0, 0]diff_j = J - np.apply_over_axes(np.sum, (J * P), axes=(0, 1))[0, 0]std_i = np.sqrt(np.apply_over_axes(np.sum, (P * (diff_i) ** 2),axes=(0, 1))[0, 0])std_j = np.sqrt(np.apply_over_axes(np.sum, (P * (diff_j) ** 2),axes=(0, 1))[0, 0])cov = np.apply_over_axes(np.sum, (P * (diff_i * diff_j)),axes=(0, 1))[0, 0]# handle the special case of standard deviations near zeromask_0 = std_i < 1e-15mask_0[std_j < 1e-15] = Trueresults[mask_0] = 1# handle the standard casemask_1 = mask_0 == Falseresults[mask_1] = cov[mask_1] / (std_i[mask_1] * std_j[mask_1])elif prop in ['contrast', 'dissimilarity', 'homogeneity']:weights = weights.reshape((num_level, num_level, 1, 1))results = np.apply_over_axes(np.sum, (P * weights), axes=(0, 1))[0, 0]elif prop == 'mean':results = np.apply_over_axes(np.mean, P, axes=(0, 1))[0, 0]elif prop == 'variance':results = np.apply_over_axes(np.sum, (P - np.apply_over_axes(np.mean, P, axes=(0, 1)))**2, axes=(0, 1))[0, 0]elif prop == 'entroy':with np.errstate(divide='ignore'):condition_list = [P != 0, P == 0]choice_list = [-np.log10(P), 0]P = np.select(condition_list, choice_list)results = np.apply_over_axes(np.sum, P, axes=(0, 1))[0, 0]return results

使用示例

分别为方差、均值、熵的计算。

greycoprops(glcm, 'variance')
greycoprops(glcm, 'mean')
greycoprops(glcm, 'entroy')

这篇关于Python计算灰度共生矩阵和常用的纹理因子的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/897843

相关文章

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以