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处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地

利用python实现对excel文件进行加密

《利用python实现对excel文件进行加密》由于文件内容的私密性,需要对Excel文件进行加密,保护文件以免给第三方看到,本文将以Python语言为例,和大家讲讲如何对Excel文件进行加密,感兴... 目录前言方法一:使用pywin32库(仅限Windows)方法二:使用msoffcrypto-too

使用Python实现矢量路径的压缩、解压与可视化

《使用Python实现矢量路径的压缩、解压与可视化》在图形设计和Web开发中,矢量路径数据的高效存储与传输至关重要,本文将通过一个Python示例,展示如何将复杂的矢量路径命令序列压缩为JSON格式,... 目录引言核心功能概述1. 路径命令解析2. 路径数据压缩3. 路径数据解压4. 可视化代码实现详解1

python获取网页表格的多种方法汇总

《python获取网页表格的多种方法汇总》我们在网页上看到很多的表格,如果要获取里面的数据或者转化成其他格式,就需要将表格获取下来并进行整理,在Python中,获取网页表格的方法有多种,下面就跟随小编... 目录1. 使用Pandas的read_html2. 使用BeautifulSoup和pandas3.

Python装饰器之类装饰器详解

《Python装饰器之类装饰器详解》本文将详细介绍Python中类装饰器的概念、使用方法以及应用场景,并通过一个综合详细的例子展示如何使用类装饰器,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录1. 引言2. 装饰器的基本概念2.1. 函数装饰器复习2.2 类装饰器的定义和使用3. 类装饰

Python 交互式可视化的利器Bokeh的使用

《Python交互式可视化的利器Bokeh的使用》Bokeh是一个专注于Web端交互式数据可视化的Python库,本文主要介绍了Python交互式可视化的利器Bokeh的使用,具有一定的参考价值,感... 目录1. Bokeh 简介1.1 为什么选择 Bokeh1.2 安装与环境配置2. Bokeh 基础2

如何使用 Python 读取 Excel 数据

《如何使用Python读取Excel数据》:本文主要介绍使用Python读取Excel数据的详细教程,通过pandas和openpyxl,你可以轻松读取Excel文件,并进行各种数据处理操... 目录使用 python 读取 Excel 数据的详细教程1. 安装必要的依赖2. 读取 Excel 文件3. 读

Python的time模块一些常用功能(各种与时间相关的函数)

《Python的time模块一些常用功能(各种与时间相关的函数)》Python的time模块提供了各种与时间相关的函数,包括获取当前时间、处理时间间隔、执行时间测量等,:本文主要介绍Python的... 目录1. 获取当前时间2. 时间格式化3. 延时执行4. 时间戳运算5. 计算代码执行时间6. 转换为指