Skip to content

Instantly share code, notes, and snippets.

@prakashjayy
Created June 15, 2021 05:15
Show Gist options
  • Save prakashjayy/e8eabfa518517b6479ef6a9b4d168e45 to your computer and use it in GitHub Desktop.
Save prakashjayy/e8eabfa518517b6479ef6a9b4d168e45 to your computer and use it in GitHub Desktop.
Generating tiles on satellite and its mask respectively.
def get_tile_name_path(dst_dir, index, city=city, code=code):
'''
generating 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,pixel_y):
'''
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, pixel_x, pixel_y):
'''
creating profile of the tile
'''
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, size, dst_dir):
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