python计算灰度共生矩阵

def getIndex(intput_tifffile,output_tifffile,i):
    print('正在执行第',i,'景影像数据计算')
    try:
        tiffile=geotiffread(intput_tifffile)
    except:
        print("打开文件失败,检查数据")
    try:
        data=np.float32(tiffile.dataarray)  #首先要将输入数据格式化,统一成float32
        rows,cols,_= data.shape  #获取数据尺寸
        data[data==65535]=0   #忽略背景值
        ##ndvi转uint8,范围0-255
        ndvi = np.uint8((ndvi-np.nanmin(ndvi)) / (np.nanmax(ndvi)-np.nanmin(ndvi)) * 255)

        #设置切片的大小、缓冲区、切片的横纵数量(因为GLCM需要大量计算,不切片会内存溢出)
        pixelnum = 256  
        bufdist = 10
        ndvi_asm = np.zeros((rows,cols))
        xnum = ceil(cols/pixelnum)
        ynum = ceil(rows/pixelnum)

        #执行切片
        for i in range(ynum):
            if ynum == 1:                   # 裁剪行数只有1行(rows<=pixelnum),纵向不做缓冲区
                ylim = [0,rows]              
                kernel_y = [0,rows]
            else:                           # 裁剪行数大于1行
                if i == 0: 
                    ylim = [0,pixelnum+bufdist]     # 向一定方向扩展按照缓冲距延伸 再进行分类
                    kernel_y = [0,pixelnum]         # 在分类结果上只取核心范围kernel_x/y
                elif i == ynum-1: 
                    ylim = [i*pixelnum-bufdist,rows]
                    kernel_y = [i*pixelnum,rows]
                else:
                    ylim = [i*pixelnum-bufdist,(i+1)*pixelnum+bufdist]
                    kernel_y = [i*pixelnum,(i+1)*pixelnum] 
            for j in range(xnum):
                
                if xnum == 1:                   # 裁剪列数只有1列(rows<=pixelnum),横向不做缓冲区
                    xlim = [0,cols]              
                    kernel_x = [0,cols]
                else:                           # 裁剪行数大于1列
                    if j == 0: 
                        xlim = [0,pixelnum+bufdist]     # 向一定方向扩展按照缓冲距延伸 再进行分类
                        kernel_x = [0,pixelnum]         # 在分类结果上只取核心范围kernel_x/y
                    elif j == xnum-1: 
                        xlim = [j*pixelnum-bufdist,cols]
                        kernel_x = [j*pixelnum,cols]
                    else:
                        xlim = [j*pixelnum-bufdist,(j+1)*pixelnum+bufdist]
                        kernel_x = [j*pixelnum,(j+1)*pixelnum] 

                #依次取得对应切片的ndvi值
                subdata = ndvi[ylim[0]:ylim[1],xlim[0]:xlim[1]]  

                #计算切片ndvi的asm
                

                #合并各切片asm
                ndvi_asm[kernel_y[0]:kernel_y[1],kernel_x[0]:kernel_x[1]] =np.float32(ndvi_asm_subdata[kernel_y[0]-ylim[0]:(kernel_y[0]-ylim[0])+(kernel_y[1]-kernel_y[0]),kernel_x[0]-xlim[0]:(kernel_x[0]-xlim[0])+(kernel_x[1]-kernel_x[0])]) 
        
     
    try:
        geotiffwrite(output_tifffile,data_index,tiffile.geo_transform,tiffile.projection,'FLOAT32') 
    except:
        print("输出错误,请检查输出路径是否存在!")

你可能感兴趣的:(python,python,矩阵,人工智能)