import os
import numpy as np
import rasterio
from rasterio.windows import Window
from tqdm import tqdm
def crop_tif(image_path, image_out_path, crop_size=256):
"""
将多波段栅格影像裁剪为256*256大小的不重合小块影像
:param image_path: 待处理影像
:image_out_path: 切图保存路径
:param crop_size: 裁剪尺寸,默认为256
:return:
"""
with rasterio.open(image_path) as src:
width = src.width
height = src.height
crop_width = crop_height = crop_size
# 判断行列是否256的倍数,不是则舍弃行列的最后部分
if width % crop_size == 0:
width = width
else:
width = width - (width % crop_size)
if height % crop_size == 0:
height = height
else:
height = height - (height % crop_size)
for i in tqdm(range(0, width, crop_width), desc='影像切割256*256'):
for j in range(0, height, crop_height):
window = Window(i, j, crop_width, crop_height)
cropped_img = src.read(window=window)
# 根据窗口大小创建输出文件
out_profile = src.profile
out_profile.update({
'width': crop_width,
'height': crop_height,
'transform': src.window_transform(window)
})
# f"{'akesu'}_{i}_{j}.tif" 保存的文件名构成 可自行更改 akesu是名字,i是切割文件左上角的列序号,j是切割文件左上角的行序号
out_path = os.path.join(image_out_path, f"{'akesu'}_{i}_{j}.tif")
with rasterio.open(out_path, 'w', **out_profile) as out_ds:
out_ds.write(cropped_img)