基本思路:读取tif→高度为256进行裁剪→横向重叠裁剪→保存png
# 对tif进行横向重叠裁剪生成png
import cv2
import os
from PIL import Image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None
def convert_multiband_tif_to_png(input_path):
image = cv2.imread(input_path, cv2.IMREAD_UNCHANGED)
height, width = image.shape[:2]
crop_size = 256
list_H = []
for y in range(0, height - crop_size + 1, crop_size):
cropped_image = image[y:y + crop_size, :]
list_H.append(cropped_image)
return list_H
def crop_png_with_horizontal_overlap(list_h, output_folder, overlap_percentage):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
height, width = list_h[0].shape[:2]
overlap_pixels = int(256 * overlap_percentage / 100)
crop_size = 256
idx = 10001
for item in list_h:
for x in range(0, width, crop_size - overlap_pixels):
if x + crop_size > width: # 处理剩余部分不足的情况
break
cropped_image = item[:, x:x + crop_size]
output_path = os.path.join(output_folder, f"{idx}.png")
cv2.imwrite(output_path, cropped_image)
idx += 1
print("Successfully Done", idx-1)
print("左右重叠裁剪完成并保存为PNG格式。")
input_path = "change_label.tif" # 输入三波段tif文件路径
output_folder = "dataset/OUT" # 输出png文件
overlap_percentage = 30 # 左右重叠度百分比
# 将三波段的tif图像转换为PNG格式
converted_png_path = convert_multiband_tif_to_png(input_path)
crop_png_with_horizontal_overlap(converted_png_path, output_folder, overlap_percentage)