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

相关文章

计算绕原点旋转某角度后的点的坐标

问题: A点(x, y)按顺时针旋转 theta 角度后点的坐标为A1点(x1,y1)  ,求x1 y1坐标用(x,y)和 theta 来表示 方法一: 设 OA 向量和x轴的角度为 alpha , 那么顺时针转过 theta后 ,OA1 向量和x轴的角度为 (alpha - theta) 。 使用圆的参数方程来表示点坐标。A的坐标可以表示为: \[\left\{ {\begin{ar

Python 字符串占位

在Python中,可以使用字符串的格式化方法来实现字符串的占位。常见的方法有百分号操作符 % 以及 str.format() 方法 百分号操作符 % name = "张三"age = 20message = "我叫%s,今年%d岁。" % (name, age)print(message) # 我叫张三,今年20岁。 str.format() 方法 name = "张三"age

React+TS前台项目实战(十七)-- 全局常用组件Dropdown封装

文章目录 前言Dropdown组件1. 功能分析2. 代码+详细注释3. 使用方式4. 效果展示 总结 前言 今天这篇主要讲全局Dropdown组件封装,可根据UI设计师要求自定义修改。 Dropdown组件 1. 功能分析 (1)通过position属性,可以控制下拉选项的位置 (2)通过传入width属性, 可以自定义下拉选项的宽度 (3)通过传入classN

一道经典Python程序样例带你飞速掌握Python的字典和列表

Python中的列表(list)和字典(dict)是两种常用的数据结构,它们在数据组织和存储方面有很大的不同。 列表(List) 列表是Python中的一种有序集合,可以随时添加和删除其中的元素。列表中的元素可以是任何数据类型,包括数字、字符串、其他列表等。列表使用方括号[]表示,元素之间用逗号,分隔。 定义和使用 # 定义一个列表 fruits = ['apple', 'banana

Python应用开发——30天学习Streamlit Python包进行APP的构建(9)

st.area_chart 显示区域图。 这是围绕 st.altair_chart 的语法糖。主要区别在于该命令使用数据自身的列和指数来计算图表的 Altair 规格。因此,在许多 "只需绘制此图 "的情况下,该命令更易于使用,但可定制性较差。 如果 st.area_chart 无法正确猜测数据规格,请尝试使用 st.altair_chart 指定所需的图表。 Function signa

python实现最简单循环神经网络(RNNs)

Recurrent Neural Networks(RNNs) 的模型: 上图中红色部分是输入向量。文本、单词、数据都是输入,在网络里都以向量的形式进行表示。 绿色部分是隐藏向量。是加工处理过程。 蓝色部分是输出向量。 python代码表示如下: rnn = RNN()y = rnn.step(x) # x为输入向量,y为输出向量 RNNs神经网络由神经元组成, python

python 喷泉码

因为要完成毕业设计,毕业设计做的是数据分发与传输的东西。在网络中数据容易丢失,所以我用fountain code做所发送数据包的数据恢复。fountain code属于有限域编码的一部分,有很广泛的应用。 我们日常生活中使用的二维码,就用到foutain code做数据恢复。你遮住二维码的四分之一,用手机的相机也照样能识别。你遮住的四分之一就相当于丢失的数据包。 为了实现并理解foutain

python 点滴学

1 python 里面tuple是无法改变的 tuple = (1,),计算tuple里面只有一个元素,也要加上逗号 2  1 毕业论文改 2 leetcode第一题做出来

Python爬虫-贝壳新房

前言 本文是该专栏的第32篇,后面会持续分享python爬虫干货知识,记得关注。 本文以某房网为例,如下图所示,采集对应城市的新房房源数据。具体实现思路和详细逻辑,笔者将在正文结合完整代码进行详细介绍。接下来,跟着笔者直接往下看正文详细内容。(附带完整代码) 正文 地址:aHR0cHM6Ly93aC5mYW5nLmtlLmNvbS9sb3VwYW4v 目标:采集对应城市的

python 在pycharm下能导入外面的模块,到terminal下就不能导入

项目结构如下,在ic2ctw.py 中导入util,在pycharm下不报错,但是到terminal下运行报错  File "deal_data/ic2ctw.py", line 3, in <module>     import util 解决方案: 暂时方案:在终端下:export PYTHONPATH=/Users/fujingling/PycharmProjects/PSENe