Last active
June 15, 2021 07:38
-
-
Save kunalsinx/39a7b4cb4adcb8328e48ae60a8de4af4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import rasterio | |
def get_tile_name_path(dst_dir:str, index:int, city=city, code=code): | |
''' | |
generating index specific tile name | |
''' | |
dst_tile_name = "{}_{}_{}.tif".format(city, code, str(index).zfill(5)) | |
dst_tile_path = os.path.join(dst_dir, dst_tile_name) | |
return dst_tile_name, dst_tile_path | |
def get_tile_transform(parent_transform, pixel_x:int,pixel_y:int): | |
''' | |
creating tile transform matrix from parent tif image | |
''' | |
crs_x = parent_transform.c + pixel_x * parent_transform.a | |
crs_y = parent_transform.f + pixel_y * parent_transform.e | |
tile_transform = rasterio.Affine(parent_transform.a, parent_transform.b, crs_x, | |
parent_transform.d, parent_transform.e, crs_y) | |
return tile_transform | |
def get_tile_profile(parent_tif:rasterio.io.DatasetReader, pixel_x:int, pixel_y:int): | |
''' | |
preparing tile profile | |
''' | |
tile_crs = parent_tif.crs | |
tile_nodata = parent_tif.nodata if parent_tif.nodata is not None else 0 | |
tile_transform = get_tile_transform(parent_tif.transform, pixel_x, pixel_y) | |
profile = dict( | |
driver="GTiff", | |
crs=tile_crs, | |
nodata=tile_nodata, | |
transform=tile_transform | |
) | |
return profile | |
def generate_tiles(tif:rasterio.io.DatasetReader, size:int, dst_dir:str): | |
i = 0 | |
for x in tqdm(range(0, tif.width, size)): | |
for y in range(0, tif.height, size): | |
# creating the tile specific profile | |
profile = get_tile_profile(tif, x, y) | |
# extracting the pixel data (couldnt understand as i dont think thats the correct way to pass the argument) | |
tile_data = tif.read(window=((y, y + size), (x, x + size)), | |
boundless=True, fill_value=profile['nodata'])[:3] | |
i+=1 | |
dst_name, dst_tile_path = get_tile_name_path(dst_dir, i) | |
c, h, w = tile_data.shape | |
profile.update( | |
height=h, | |
width=w, | |
count=c, | |
dtype=tile_data.dtype, | |
) | |
with rasterio.open(dst_tile_path, "w", **profile) as dst: | |
dst.write(tile_data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment