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')