python实现栅格图像的裁剪
深度学习做样本必要的一步,代码如下
import os, os.path
import rasterio
from rasterio.windows import Window
import rasterio.mask
def rastersplit(input_value_raster, tile_width_in, tile_height_in, outfolder):
dataset = rasterio.open(input_value_raster)
# height and width of the raster
height, width = dataset.shape
# split the large raser into number of tiles, tile size is 2000*2000
tile_width = tile_width_in
tile_height = tile_height_in
tile_num_col = int(width / tile_width + 0.5)
tile_num_row = int(height / tile_height + 0.5)
# the output folder
if not os.path.exists(outfolder): os.mkdir(outfolder)
# create each tile
for i in range(tile_num_row):
# re-initiate the tile width when reach the right boundary
tile_width = tile_width_in
row_start = i * tile_height
# loop each column
for j in range(tile_num_col):
print('The i and j is:', i, j)
tilename = os.path.join(outfolder, 'row%s-col%s.tif' % (i, j))
col_start = j * tile_width
row_end = (i + 1) * tile_height
col_end = (j + 1) * tile_width
# deal with the right boundary
if row_end > height - 1: tile_height = height - row_start
if col_end > width - 1: tile_width = width - col_start
# window = get_data_window(lu_dataset.read(1, masked=True))
window = Window(col_off=col_start, row_off=row_start, width=tile_width, height=tile_height)
kwargs = dataset.meta.copy()
kwargs.update({
'height': window.height,
'width': window.width,
'transform': rasterio.windows.transform(window, dataset.transform)})
img_window = dataset.read(window=window)
if img_window.min() <= 0: continue
with rasterio.open(tilename, 'w', **kwargs) as dst:
dst.write(img_window)
root = 'E:DeepLearningdata'#栅格影像
data = os.path.join(root, 'landuse.tif')
label = os.path.join(root, 'result')
if not os.path.exists(label): os.mkdir(label)
tile_width = 128 #裁剪后的尺寸
tile_height = 128
rastersplit(data, tile_width, tile_height, label)
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
二维码