import csv
import numpy as np
import rasterio
import pandas as pd
def readTif(fileName):
try:
dataset = rasterio.open(fileName)
return dataset
except rasterio.errors.RasterioIOError:
print(f"文件 {fileName} 无法打开")
return None
orgin_path = r'F:\datasets\ZY1E\不透水面提取\MIMFormer\HRMSI.tif'
sample_path = r'F:\datasets\ZY1E\不透水面提取\labels.tif'
csv_filename = r'F:\datasets\ZY1E\不透水面提取\labels.csv'
num_bands = 8
csv_head_name = [f'Band{i}' for i in range(1, num_bands + 1)] + ['Label', 'LabelName']
labels_name = {1: "Water", 2: "Other"}
ori_dataset = readTif(orgin_path)
label_dataset = readTif(sample_path)
if ori_dataset is not None and label_dataset is not None:
label_matri = label_dataset.read(1)
data_matri = ori_dataset.read()
nonzero_indices = np.nonzero(label_matri)
count = len(nonzero_indices[0])
# 准备数据
data = []
for i in range(count):
row, col = nonzero_indices[0][i], nonzero_indices[1][i]
band_values = data_matri[:, row, col].tolist()
label = label_matri[row, col]
label_name = labels_name.get(label, 'Unknown')
band_values.extend([label, label_name])
data.append(band_values)
# 使用 pandas 写入 CSV
df = pd.DataFrame(data, columns=csv_head_name)
df.to_csv(csv_filename, index=False)
print(f"已将数据写入 CSV 文件: {csv_filename}")
12-05
1740
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)