import os
import numpy
from osgeo import gdal
class GRID:
def read_img(self, 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)
del dataset
return im_proj, im_geotrans, im_data
def write_img(self, filename, im_proj, origin_x, origin_y, pixel_width, pixel_height, im_data):
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) == 3:
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((origin_x, pixel_width, 0, origin_y, 0, pixel_height))
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 calcLonLat(dataset, x, y):
minx, xres, xskew, maxy, yskew, yres = dataset.GetGeoTransform()
lon = minx + xres * x
lat = maxy +xres * y
return lon, lat
if __name__ == "__main__":
file_name = r"E:\pythonWS\readgeotiff\python_server_data\tiff\200002_result.tif"
dataset = gdal.Open(file_name)
minx, xres, xskew, maxy, yskew, yres = dataset.GetGeoTransform()
proj, geotrans, data = GRID().read_img(file_name)
print(proj)
print(geotrans)
print(data.shape)
width, height = data.shape
size=1024
for j in range(height // size):
for i in range(width // size):
if(j==height//size):
cur_image = data[i * size:(i + 1) * size, j * size:(j + 1) * size]
lon = minx + xres * size * j
lat = maxy + yres * (i * size)
GRID().write_img(r'E:\pythonWS\readgeotiff\python_server_data\temptif/{}_{}.tif'.format(i, j), proj,
lon, lat, xres, yres, cur_image)
else:
cur_image = data[i*size:(i + 1) * size, j * size:(j + 1) * size]
lon=minx+xres*size*j
lat=maxy+yres*(i*size)
GRID().write_img(r'E:\pythonWS\readgeotiff\python_server_data\temptif/{}_{}.tif'.format(i, j), proj,
lon, lat, xres, yres, cur_image)