Python归一化tif文件

Python归一化tif文件

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2019/6/25 10:39
# @Author  : wangyu
# @File    : Duo.py
# @Software: PyCharm
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()  # 地图投影信息
    im_data = dataset.ReadAsArray(0, 0, im_width, im_height).astype(np.float)  # 将数据写成数组,对应栅格矩阵
    del dataset  # 关闭对象,文件dataset
    return im_proj, im_geotrans, im_data, im_height, im_width

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):
    starttime = datetime.datetime.now()
    print('Normalization开始>>>')
    for filename in glob.glob(path):
        a, b = os.path.split(filename)
        bandname = b[9:24]
        print(bandname,'开始>>>>')
        substarttime = datetime.datetime.now()
        proj, geotrans, values, row1, column1 = read_img(filename)
        for i in range(6):  # 对每个图层进行归一化
            a=np.min(minvalues)
            b = np.max(values[i])
            values[i] = np.where(values[i] < minlist[i], 0, (values[i] - a) / (b - a))
        write_img(r'F:\SJP\test\G' + bandname+'.tif', proj, geotrans, values)
        subendtime = datetime.datetime.now()-substarttime
        print (bandname,'结束,一副影像耗费时间:',subendtime)
    endtime = datetime.datetime.now()-starttime
    print('Normalization结束,花费时间:',endtime )
if __name__=='__main__':
    Nor(r'F:\SJP\RC\112025_19840920__rad.tif')

 

你可能感兴趣的:(研究生生涯,python)