遥感图像归一化 - 行走的蓑衣客

时间:2024-03-06 20:28:29

python代码

import os
import numpy as np
from osgeo import gdal
import glob
import datetime


# 读图像文件
def read_img(filename):
    dataset = gdal.Open(filename)  # 打开文件
    im_width = dataset.RasterXSize  # 栅格矩阵的列数
    im_height = dataset.RasterYSize  # 栅格矩阵的行数
    im_geotrans = dataset.GetGeoTransform()  # 仿射矩阵
    im_proj = dataset.GetProjection()  # 地图投影信息
    bands = dataset.RasterCount
    im_data = dataset.ReadAsArray(0, 0, im_width, im_height).astype(np.float32)  # 将数据写成数组,对应栅格矩阵
    del dataset  # 关闭对象,文件dataset
    return im_proj, im_geotrans, im_data, im_height, im_width,bands


def write_img(filename, im_proj, im_geotrans, im_data):
    # gdal数据类型包括
    # gdal.GDT_Byte,
    # gdal .GDT_UInt16, gdal.GDT_Int16, gdal.GDT_UInt32, gdal.GDT_Int32,
    # gdal.GDT_Float32, gdal.GDT_Float64

    # 判断栅格数据的数据类型
    if \'int8\' in im_data.dtype.name:
        datatype = gdal.GDT_Byte
    elif \'int16\' in im_data.dtype.name:
        datatype = gdal.GDT_UInt16
    else:
        datatype = gdal.GDT_Float32

    # 判读数组维数
    if len(im_data.shape) != 1:
        im_bands, im_height, im_width = im_data.shape
    else:
        im_bands, (im_height, im_width) = 1, im_data.shape

    # 创建文件
    driver = gdal.GetDriverByName("GTiff")  # 数据类型必须有,因为要计算需要多大内存空间
    dataset = driver.Create(filename, im_width, im_height, im_bands, datatype)

    dataset.SetGeoTransform(im_geotrans)  # 写入仿射变换参数
    dataset.SetProjection(im_proj)  # 写入投影
    if im_bands == 1:
        dataset.GetRasterBand(1).WriteArray(im_data)  # 写入数组数据
    else:
        for i in range(im_bands):
            dataset.GetRasterBand(i + 1).WriteArray(im_data[i])
    del dataset


def Nor(path,out):
    starttime = datetime.datetime.now()
    print(\'Normalization开始>>>\')
    for filename in glob.glob(path):
        a1,bandname= os.path.split(filename)

        print(bandname, \'开始>>>>\')
        substarttime = datetime.datetime.now()
        proj, geotrans, values, row1, column1,bands = read_img(filename)
        for i in range(bands):  # 对每个图层进行归一化
            a = np.min(values[i])
            b = np.max(values[i])
            values[i] =(values[i] - a) / (b - a)
        write_img(out+"\\" + bandname + \'.tif\', proj, geotrans, values)
        subendtime = datetime.datetime.now() - substarttime
        print(bandname, \'结束,一副影像耗费时间:\', subendtime)
    endtime = datetime.datetime.now() - starttime
    print(\'Normalization结束,花费时间:\', endtime)


if __name__ == \'__main__\':
    path=r\'E:\湖泊测试数据\改进分水岭\125.tif\'
    out=r\'E:\湖泊测试数据\成果\'
    Nor(path,out)

 

posted on 2021-09-12 21:33  行走的蓑衣客  阅读(98)  评论(0编辑  收藏  举报