You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遥感Python:如何基于双波段DN值条件生成仅含0和1的新波段或数组

基于双波段DN值创建二进制新波段的Python实现

当然可以!这在遥感数据处理中是非常常见的需求,借助Python的numpy(用于高效数组操作)和rasterio/xarray(用于栅格读写)就能轻松完成。下面我给你详细拆解实现步骤:

核心思路

利用numpy的矢量化条件判断直接对整个波段数组做批量处理——这比逐像素循环效率高得多,尤其适合大型遥感影像。

具体实现代码(以Rasterio为例)

Rasterio是处理栅格数据的常用库,步骤清晰易上手:

import numpy as np
import rasterio

# 1. 读取目标波段数据
with rasterio.open("your_remote_sensing_image.tif") as src:
    # Rasterio的波段索引从1开始,对应你的Band4和Band11
    band4 = src.read(4)
    band11 = src.read(11)

# 2. 定义判断条件:Band4≥11000 且 Band11≤23000
# 注意用&(按位与)而非and,因为要对数组逐元素判断
condition = (band4 >= 11000) & (band11 <= 23000)

# 3. 生成二进制新数组:满足条件设为0,否则设为1
new_binary_band = np.where(condition, 0, 1)

# 4. (可选)将新波段保存为栅格文件
with rasterio.open(
    "output_binary_band.tif",
    "w",
    driver="GTiff",  # 输出格式为GeoTIFF
    height=src.height,
    width=src.width,
    count=1,  # 单波段输出
    dtype=new_binary_band.dtype,
    crs=src.crs,  # 保持原影像的坐标系
    transform=src.transform,  # 保持原影像的地理变换信息
) as dst:
    dst.write(new_binary_band, 1)

可选方案:用Xarray简化操作

如果你习惯用Xarray处理多维遥感数据,代码会更简洁:

import xarray as xr

# 读取影像为Xarray数据集
ds = xr.open_dataset("your_remote_sensing_image.tif", engine="rasterio")

# 定义条件并生成新波段
condition = (ds.band_data.sel(band=4) >= 11000) & (ds.band_data.sel(band=11) <= 23000)
new_binary_band = xr.where(condition, 0, 1)

# 保存为GeoTIFF(需要rioxarray支持)
new_binary_band.rio.to_raster("output_binary_band_xarray.tif")

注意事项

  • 确保两个波段的数组形状完全一致,否则条件判断会报错
  • 如果影像存在NoData值,建议先通过np.isnan()或特定值(比如-9999)过滤,避免干扰条件判断
  • 新波段的数据类型可以指定为uint8(仅存0和1),能大幅减少文件体积:new_binary_band = np.where(condition, 0, 1).astype(np.uint8)

内容的提问来源于stack exchange,提问作者Kaitlyn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:50:19