基于python的遥感影像灰色关联矩阵纹理特征计算

遥感影像纹理特征是描述影像中像素间空间关系的统计特征,常用于地物分类、目标识别和变化检测等遥感应用中。常见的纹理特征计算方式包括灰度共生矩阵(GLCM)、灰度差异矩阵(GLDM)、灰度不均匀性矩阵(GLRLM)等。这些方法通过对像素灰度值的统计分析,揭示了影像中像素间的空间分布规律,从而提取出纹理特征。

常用的纹理特征包括

1. 对比度(Contrast): 描述图像中灰度级之间的对比程度。

2. 同质性(Homogeneity): 描述图像中灰度级分布的均匀程度。

3. 熵(Entropy): 描述图像中灰度级分布的不确定性。

4. 方差(Variance): 描述图像中灰度级的离散程度。

5. 相关性(Correlation): 描述图像中像素间的灰度值相关程度。

6. 能量(Energy): 是灰度共生矩阵各元素值的平方和。

7. 均值(Mean): 描述图像中每个灰度级出现的平均频率。

8. 不相似度(Dissimilarity): 描述图像中不同灰度级之间的差异程度。

这些纹理特征可以通过GLCM等方法计算得到,用于描述遥感影像的纹理信息,对于遥感影像的分类和分析具有重要意义。

在ENVI中可以直接使用工具箱的工具直接计算得到输出影像

在这里插入图片描述

此外也可以使用python的skimage.feature库,这个库的greycoprops函数只有contrast、dissimilarity、homogeneity、ASM、energy和correlation这几个特征没有均值、方差和熵。因此下面对这个库的原函数进行修正,添加了方差等计算的greycoprops函数

def greycoprops(P, prop='contrast'):
    """Calculate texture properties of a GLCM.

    Compute a feature of a grey level co-occurrence matrix to serve as
    a compact summary of the matrix. The properties are computed as
    follows:

    - '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 texture
    properties.

    Parameters
    ----------
    P : ndarray
        Input array. `P` is the grey-level co-occurrence histogram
        for which to compute the specified property. The value
        `P[i,j,d,theta]` is the number of times that grey-level j
        occurs at a distance d and at an angle theta from
        grey-level i.
    prop : {'contrast', 'dissimilarity', 'homogeneity', 'energy', \
            'correlation', 'ASM'}, optional
        The property of the GLCM to compute. The default is 'contrast'.

    Returns
    -------
    results : 2-D ndarray
        2-dimensional array. `results[d, a]` is the property 'prop' for
        the d'th distance and the a'th angle.

    References
    ----------
    .. [1] The GLCM Tutorial Home Page,
           http://www.fp.ucalgary.ca/mhallbey/tutorial.htm

    Examples
    --------
    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')
    >>> contrast
    array([[0.58333333, 1.        ],
           [1.25      , 2.75      ]])

    """
    check_nD(P, 4, 'P')

    (num_level, num_level2, num_dist, num_angle) = P.shape
    if 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 GLCM
    P = P.astype(np.float32)
    glcm_sums = np.apply_over_axes(np.sum, P, axes=(0, 1))
    glcm_sums[glcm_sums == 0] = 1
    P /= glcm_sums

    # create weights for specified property
    I, J = np.ogrid[0:num_level, 0:num_level]
    if prop == 'contrast':
        weights = (I - J) ** 2
    elif prop == 'dissimilarity':
        weights = np.abs(I - J)
    elif prop == 'homogeneity':
        weights = 1. / (1. + (I - J) ** 2)
    elif prop in ['ASM', 'energy', 'correlation', 'entropy', 'mean', 'variance']:
        pass
    else:
        raise ValueError('%s is an invalid property ?' % (prop))

    # compute property for each GLCM
    if 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 == 'entropy':
        results = np.apply_over_axes(np.sum, -P * np.log10(P+0.00001), 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 zero
        mask_0 = std_i < 1e-15
        mask_0[std_j < 1e-15] = True
        results[mask_0] = 1

        # handle the standard case
        mask_1 = mask_0 == False
        results[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':
        I = np.array(range(num_level)).reshape((num_level, 1, 1, 1))
        results = np.apply_over_axes(np.sum, (P * I), axes=(0, 1))[0, 0]
    elif prop == 'variance':
        I = np.array(range(num_level)).reshape((num_level, 1, 1, 1))
        mean = np.apply_over_axes(np.sum, (P * I), axes=(0, 1))[0, 0]
        results = np.apply_over_axes(np.sum, (P * (I - mean) ** 2), axes=(0, 1))[0, 0]
        
    return results

具体影像分析时还需要考虑灰色关联矩阵计算的角度、步长、灰度级数和窗口大小。以一张多光谱影像为例,相关性使用了greycoprops,其他的特征使用公式计算,实际上导入上面的新greycoprops函数后其他特征都可以用函数计算,具体代码如下,输出结果为多光谱各个波段的纹理特征的多通道影像:

from osgeo import gdal, osr
import os
import numpy as np
import cv2
from skimage import data
from skimage.feature import greycoprops

def export_tif(out_tif_name, var_lat, var_lon, NDVI, bandname=None):
    # 判断数组维度
    if len(NDVI.shape) > 2:
        im_bands, im_height, im_width = NDVI.shape
    else:
        im_bands, (im_height, im_width) = 1, NDVI.shape
    LonMin, LatMax, LonMax, LatMin = [min(var_lon), max(var_lat), max(var_lon), min(var_lat)]
    # 分辨率计算
    Lon_Res = (LonMax - LonMin) / (float(im_width) - 1)
    Lat_Res = (LatMax - LatMin) / (float(im_height) - 1)
    driver = gdal.GetDriverByName('GTiff')
    out_tif = driver.Create(out_tif_name, im_width, im_height, im_bands, gdal.GDT_Float32)  # 创建框架

    # 设置影像的显示范围
    # Lat_Res一定要是-的
    geotransform = (LonMin, Lon_Res, 0, LatMax, 0, -Lat_Res)
    out_tif.SetGeoTransform(geotransform)

    # 获取地理坐标系统信息,用于选取需要的地理坐标系统
    srs = osr.SpatialReference()
    srs.ImportFromEPSG(4326)  # 定义输出的坐标系为"WGS 84",AUTHORITY["EPSG","4326"]
    out_tif.SetProjection(srs.ExportToWkt())  # 给新建图层赋予投影信息

    # 数据写出
    if im_bands == 1:
        out_tif.GetRasterBand(1).WriteArray(NDVI)
    else:
        for bands in range(im_bands):
            # 为每个波段设置名称
            if bandname is not None:
                out_tif.GetRasterBand(bands + 1).SetDescription(bandname[bands])
            out_tif.GetRasterBand(bands + 1).WriteArray(NDVI[bands])
    
    # 生成 ENVI HDR 文件
    hdr_file = out_tif_name.replace('.tif', '.hdr')
    with open(hdr_file, 'w') as f:
        f.write('ENVI\n')
        f.write('description = {Generated by export_tif}\n')
        f.write('samples = {}\n'.format(im_width))
        f.write('lines   = {}\n'.format(im_height))
        f.write('bands   = {}\n'.format(im_bands))
        f.write('header offset = 0\n')
        f.write('file type = ENVI Standard\n')
        f.write('data type = {}\n'.format(gdal.GetDataTypeName(out_tif.GetRasterBand(1).DataType)))
        f.write('interleave = bsq\n')
        f.write('sensor type = Unknown\n')
        f.write('byte order = 0\n')
        band_names_str = ', '.join(str(band) for band in bandname)
        f.write('band names = {%s}\n'%(band_names_str))
       
    del out_tif
                                                        
                                                        
def fast_glcm(img, vmin=0, vmax=255, levels=8, kernel_size=5, distance=1.0, angle=0.0):
    '''
    Parameters
    ----------
    img: array_like, shape=(h,w), dtype=np.uint8
        input image
    vmin: int
        minimum value of input image
    vmax: int
        maximum value of input image
    levels: int
        number of grey-levels of GLCM
    kernel_size: int
        Patch size to calculate GLCM around the target pixel
    distance: float
        pixel pair distance offsets [pixel] (1.0, 2.0, and etc.)
    angle: float
        pixel pair angles [degree] (0.0, 30.0, 45.0, 90.0, and etc.)

    Returns
    -------
    Grey-level co-occurrence matrix for each pixels
    shape = (levels, levels, h, w)
    '''

    mi, ma = vmin, vmax
    ks = kernel_size
    h,w = img.shape

    # digitize
    bins = np.linspace(mi, ma+1, levels+1)
    gl1 = np.digitize(img, bins) - 1

    # make shifted image
    dx = distance*np.cos(np.deg2rad(angle))
    dy = distance*np.sin(np.deg2rad(-angle))
    mat = np.array([[1.0,0.0,-dx], [0.0,1.0,-dy]], dtype=np.float32)
    gl2 = cv2.warpAffine(gl1, mat, (w,h), flags=cv2.INTER_NEAREST,
                         borderMode=cv2.BORDER_REPLICATE)

    # make glcm
    glcm = np.zeros((levels, levels, h, w), dtype=np.uint8)
    for i in range(levels):
        for j in range(levels):
            mask = ((gl1==i) & (gl2==j))
            glcm[i,j, mask] = 1

    kernel = np.ones((ks, ks), dtype=np.uint8)
    for i in range(levels):
        for j in range(levels):
            glcm[i,j] = cv2.filter2D(glcm[i,j], -1, kernel)
    # 灰色关联矩阵归一化,之后结果与ENVI相同
    glcm = glcm.astype(np.float32)
    glcm_sums = np.apply_over_axes(np.sum, glcm, axes=(0, 1))
    glcm_sums[glcm_sums == 0] = 1
    glcm /= glcm_sums
    return glcm


def fast_glcm_texture(img, vmin=0, vmax=255, levels=8, ks=5, distance=1.0, angle=0.0):
    '''
    calc glcm texture
    '''
    h,w = img.shape
    glcm = fast_glcm(img, vmin, vmax, levels, ks, distance, angle)
    mean = np.zeros((h,w), dtype=np.float32)
    var = np.zeros((h,w), dtype=np.float32)
    cont = np.zeros((h,w), dtype=np.float32)
    diss = np.zeros((h,w), dtype=np.float32)
    homo = np.zeros((h,w), dtype=np.float32)
    asm = np.zeros((h,w), dtype=np.float32)
    ent = np.zeros((h,w), dtype=np.float32)
    cor = np.zeros((h, w), dtype=np.float32)
    
    for i in range(levels):
        for j in range(levels):
            mean += glcm[i,j] * i
            homo += glcm[i,j] / (1.+(i-j)**2)
            asm  += glcm[i,j]**2
            cont += glcm[i,j] * (i-j)**2
            diss += glcm[i,j] * np.abs(i-j)
            ent -= glcm[i, j] * np.log10(glcm[i, j] + 0.00001)
    for i in range(levels):
        for j in range(levels):
            var += glcm[i, j] * (i - mean)**2
    greycoprops(glcm, 'correlation')  # 上面计算的几个特征均可这样写
    cor[cor == 1.0] = 0.
    homo[homo == 1.] = 0
    asm[asm == 1.] = 0
    return [mean, var, cont, diss, homo, asm, ent, cor]

# 遥感影像
image = r'..\path\to\your\file\image.tif'
# 文件输出路径
out_path = r'..\output\path'
dataset = gdal.Open(image)  # 读取数据
adfGeoTransform = dataset.GetGeoTransform()
nXSize = dataset.RasterXSize  # 列数
nYSize = dataset.RasterYSize  # 行数
im_data = dataset.ReadAsArray(0, 0, nXSize, nYSize)  # 读取数据
im_data[im_data==65536] = 0
var_lat = []  # 纬度
var_lon = []  # 经度
for j in range(nYSize):
    lat = adfGeoTransform[3] + j * adfGeoTransform[5]
    var_lat.append(lat)
for i in range(nXSize):
    lon = adfGeoTransform[0] + i * adfGeoTransform[1]
    var_lon.append(lon)
result = []
band_name=[]
for i, img in enumerate(im_data):
    img = np.uint8(255.0 * (img - np.min(img))/(np.max(img) - np.min(img))) # normalization
    fast_result = fast_glcm_texture(img, vmin=0, vmax=255, levels=32, ks=3, distance=1.0, angle=0.0)
    result += fast_result
    variable_names = ['mean', 'variance', 'contrast', 'dissimilarity', 'homogeneity', 'ASM', 'entropy', 'correlation']
    for names in variable_names:
        band_name.append('band_'+str(i+1)+'_'+names)
name = os.path.splitext(os.path.basename(image))[0]
export_tif(os.path.join(out_path, '%s_TF.tif' % name), var_lat, var_lon, np.array(result), bandname=band_name)  
print('over')

总结

目前熵值特征计算结果与ENVI有差异,不过只是数值差异,使用影像打开的结果显示一致,说明只是值的范围差异,不影响分析,其他特征均与ENVI的计算结果一致

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/393990.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

软件架构与系统架构:区别与联系的分析

软件架构与系统架构&#xff1a;区别与联系的分析 在信息技术领域&#xff0c;软件架构和系统架构这两个术语经常被提及。尽管它们在某些方面有重叠&#xff0c;但它们确实代表了不同的概念和聚焦点。理解这两种架构之间的区别和联系对于任何从事技术开发和设计的专业人士都是至…

大模型LLM训练显存消耗详解

参考论文&#xff1a;ZeRO: Memory Optimizations Toward Training Trillion Parameter Models 大模型的显存消耗一直都是面试常见的问题&#xff0c;这次我就彻彻底底的根据论文ZeRO中的调研和分析做一次分析 显存消耗的两个部分&#xff1a;Model States&#xff08;跟模型的…

spark sql官网优化指南

两句话概括 缓存数据调整参数 缓存数据 把数据缓存到内存,spark sql能够只扫描需要列并且会自动压缩数据,占用最小的内存和减小GC压力。这无需多言,内存远远要快于磁盘,spark效率比hive高这个就是一个主要原因。 缓存数据代码spark.catalog.cacheTable("tableName&qu…

unity C#中的封装、继承和多态简单易懂的经典实例

文章目录 封装 (Encapsulation)继承 (Inheritance)多态 (Polymorphism) C#中的封装、继承和多态是面向对象编程&#xff08;OOP&#xff09;的三大核心特性。下面分别对这三个概念进行深入解释&#xff0c;并通过实例来说明它们在实际开发中的应用。 封装 (Encapsulation) 实例…

java项目的构建流程

1.创建项目 2.创建模块 创建时要注意组ID的命名 通常包含以下模块: 项目的pom文件中,依赖如下(web模块不需要依赖,也不需要main文件夹): 3.配置pom文件 1),主pom文件 <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://mav…

【机构vip教程】Android SDK手机测试环境搭建

Android SDK 的安装和环境变量的配置 前置条件&#xff1a;需已安装 jdk1.8及 以上版本 1、下载Android SDK&#xff0c;解压后即可&#xff08;全英文路径&#xff09;&#xff1b;下载地址&#xff1a;http://tools.android-studio.org/index.php/sdk 2、新建一个环境变量&…

力扣题目训练(14)

2024年2月7日力扣题目训练 2024年2月7日力扣题目训练501. 二叉搜索树中的众数504. 七进制数506. 相对名次201. 数字范围按位与209. 长度最小的子数组87. 扰乱字符串 2024年2月7日力扣题目训练 2024年2月7日第十四天编程训练&#xff0c;今天主要是进行一些题训练&#xff0c;包…

3DSC特征描述符、对应关系可视化以及ICP配准

一、3DSC特征描述符可视化 C #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/search/kdtree.h> #include <pcl/io/pcd_io.h> #include <pcl/features/normal_3d_omp.h>//使用OMP需要添加的头文件 #include <pcl…

linux下ffmpeg调用GPU硬件解码(VDPAU/VAAPI)保存文件

本文讲解在linux下面&#xff0c;如何通过ffmpeg调用GPU硬件解码&#xff0c;并保存解码完的yuv文件。 其实&#xff0c;ffmpeg自带的例子hw_decode.c这个文件&#xff0c;就已经能满足要求了&#xff0c;因此&#xff0c;本文就尝试讲解以下hw_decode这个例子。hw_decode.c可以…

Java图形化界面编程——五子棋游戏 笔记

2.8.5 五子棋 接下来&#xff0c;我们使用之前学习的绘图技术&#xff0c;做一个五子棋的游戏。 注意&#xff0c;这个代码只实现了五子棋的落子、删除棋子和动画等逻辑实现&#xff0c;并没有把五子棋的游戏逻辑编写完整&#xff0c;比较简单易上手。 图片素材 package…

深度学习与计算机视觉 | 实用CV开源项目汇总(有github代码链接,建议收藏!)

本文来源公众号“深度学习与计算机视觉”&#xff0c;仅用于学术分享&#xff0c;侵权删&#xff0c;干货满满。 原文链接&#xff1a;【建议收藏】实用CV开源项目汇总&#xff08;文末有彩蛋~&#xff09; 01 Trace.moe 图像反向搜索动漫场景&#xff0c;使用动漫截图搜索该…

数据库实验报告

用SQL语句和企业管理器建立如下的表结构并输入数据 给定表结构如下&#xff1a; 创建数据库 创建数据库 create table student(Sno int auto_increment primary key,Sname varchar(45),Ssex varchar(45),Sage int,Sdept varchar(45) )engine InnoDB default charsetutf8; …

java之VO,BO,PO,DO,DTO

概念 VO&#xff08;View Object&#xff09;&#xff1a;视图对象&#xff0c;用于展示层&#xff0c;它的作用是把某个指定页面&#xff08;或组件&#xff09;的所有数据封装起来。DTO&#xff08;Data Transfer Object&#xff09;&#xff1a;数据传输对象&#xff0c;这…

代码随想录刷题笔记-Day19

1. 二叉搜索树的最小绝对差 530. 二叉搜索树的最小绝对差https://leetcode.cn/problems/minimum-absolute-difference-in-bst/ 给你一个二叉搜索树的根节点 root &#xff0c;返回 树中任意两不同节点值之间的最小差值 。 差值是一个正数&#xff0c;其数值等于两值之差的绝…

windows安装Mysql解压版

windows安装Mysql解压版 一、下载mysql-8.0.36-winx64.zip二、解压三、配置3.1. 添加环境变量&#xff1a;新建MYSQL_HOME3.2.如何验证是否添加成功&#xff1a;必须以管理员身份启动3.3. 初始化MySQL&#xff1a;必须以管理员身份启动3.4. 注册MySQL服务&#xff1a;必须以管理…

算法练习-01背包问题【含递推公式推导】(思路+流程图+代码)

难度参考 难度&#xff1a;困难 分类&#xff1a;动态规划 难度与分类由我所参与的培训课程提供&#xff0c;但需 要注意的是&#xff0c;难度与分类仅供参考。且所在课程未提供测试平台&#xff0c;故实现代码主要为自行测试的那种&#xff0c;以下内容均为个人笔记&#xff0…

PCL库学习及ROS使用

PCL库学习 c_cpp_properties.json {"configurations": [{"name": "Linux","includePath": ["${workspaceFolder}/**","/usr/include","/usr/local/include"],"defines": [],"compiler…

Linux第60步_“buildroot”构建根文件系统第2步_配置“buildroot下的busybox”并测试“buildroot”生成的根文件系统

1、查看“buildroot下的busybox”安装路径 打开终端 输入“ls回车” 输入“cd linux回车/”&#xff0c;切换到到“linux”目录 输入“ls回车”&#xff0c;查看“linux”目录下的文件和文件夹 输入“cd buildroot/回车”&#xff0c;切换到到“buildroot”目录 输入“ls…

ClickHouse迎战十亿行数据的挑战

本文字数&#xff1a;6782&#xff1b;估计阅读时间&#xff1a;17 分钟 作者&#xff1a;Dale McDiarmid 审校&#xff1a;庄晓东&#xff08;魏庄&#xff09; 本文在公众号【ClickHouseInc】首发 本月初&#xff0c;Decodable 公司的 Gunnar Morling 提出了一项为期一月挑战…

接口测试怎么进行,如何做好接口测试

一、什么是接口&#xff1f; 接口测试主要用于外部系统与系统之间以及内部各个子系统之间的交互点&#xff0c;定义特定的交互点&#xff0c;然后通过这些交互点来&#xff0c;通过一些特殊的规则也就是协议&#xff0c;来进行数据之间的交互。 二、 常用接口采用方式&#x…