Repository navigation
Expand file tree
/
Copy pathimage_split.py
More file actions
99 lines (72 loc) · 3.51 KB
/
Copy pathimage_split.py
File metadata and controls
99 lines (72 loc) · 3.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import rasterio
from rasterio.windows import Window
import os
import math
from PIL import Image
import numpy as np
# --- 1. 配置参数 ---
# 输入文件路径列表
INPUT_FILES = [
r"/home/fengze/下载/Building change detection dataset_add/1. The two-period image data/2012/whole_image/test/image/2012_test.tif",
]
# 输出文件夹的基础路径
OUTPUT_BASE_DIR = r"/home/fengze/桌面/datasets/drone_change_detection/test/A"
# 切割后小图块的尺寸(像素)
TILE_SIZE = 512
# 相邻图块的重叠区域大小(像素)
OVERLAP = 64
# --- 2. 核心切割函数 ---
def crop_large_geotiff(image_path, output_dir, tile_size, overlap):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
step = tile_size - overlap
with rasterio.open(image_path) as src:
img_h, img_w = src.height, src.width
meta = src.meta.copy()
n_rows = math.ceil((img_h - tile_size) / step) + 1 if img_h > tile_size else 1
n_cols = math.ceil((img_w - tile_size) / step) + 1 if img_w > tile_size else 1
print(f"正在处理 {os.path.basename(image_path)},尺寸: {img_w}x{img_h}...")
tile_count = 0
for i in range(n_rows):
for j in range(n_cols):
y_offset = i * step
if y_offset + tile_size > img_h:
y_offset = img_h - tile_size
x_offset = j * step
if x_offset + tile_size > img_w:
x_offset = img_w - tile_size
# 定义窗口
window = Window(x_offset, y_offset, tile_size, tile_size)
#以下为将标注图片转换为png二值图的代码
# tile_data = src.read(window=window)
# tile_bw_data = (tile_data[0] > 0).astype(np.uint8) * 255
# image_to_save = Image.fromarray(tile_bw_data)
# output_filename = f"tile_{i}_{j}.png"
# output_path = os.path.join(output_dir, output_filename)
# image_to_save.save(output_path)
# 以下为保存为GeoTIFF格式的代码
# 计算新图块的地理转换参数
transform = src.window_transform(window)
# 更新元数据
tile_meta = meta.copy()
tile_meta.update({
"height": window.height,
"width": window.width,
"transform": transform
})
# 读取窗口内的数据并写入新文件
output_filename = f"tile_{i}_{j}.tif"
output_path = os.path.join(output_dir, output_filename)
with rasterio.open(output_path, "w", **tile_meta) as dst:
dst.write(src.read(window=window))
tile_count += 1
print(f"处理完成!共生成 {tile_count} 个GeoTIFF图块,保存在: {output_dir}")
# --- 3. 运行主程序 ---
if __name__ == '__main__':
for file_path in INPUT_FILES:
if not os.path.exists(file_path):
print(f"警告:输入文件不存在,已跳过 -> {file_path}")
continue
basename = os.path.splitext(os.path.basename(file_path))[0]
output_directory = OUTPUT_BASE_DIR#os.path.join(OUTPUT_BASE_DIR, basename + "_tiles")
crop_large_geotiff(file_path, output_directory, TILE_SIZE, OVERLAP)