Skip to main content
 首页 » 编程设计

python之在python中按最小值组合重叠栅格

2025年02月15日17haluo1

我想合并一些单波段光栅图像。我希望处理重叠,以便选择像素中的最小值。 所有图像都具有相同的投影。

我尝试查看 gdalwarp 和 gdal_merge(在命令行中),但在重叠部分它们只使用最后一张图像中的值。

我也看到了使用 PIL 混合或粘贴的建议,但是这些需要一个 alpha 层,它指示应该如何混合重叠,当然我没有。

有谁知道如何使重叠取决于图像中的实际值?

请您参考如下方法:

据我所知,使用标准命令行实用程序无法做到这一点。您尝试通常随 GDAL 一起提供的“gdal_calc.py”,这要求栅格具有相同的尺寸,因此可能需要进行一些预处理(例如使用 gdalwarp)。两个栅格的最小值可以用类似的东西计算:

python gdal_calc.py -A file1.tif -B file2.tif --calc="minimum(A,B)" --outfile=res.tif 

我不太确定在没有重叠的区域会发生什么,也许您需要添加 nodata 关键字,更多信息请访问: http://www.gdal.org/gdal_calc.html

您必须指定 gdal_calc.py 的完整路径。

对于 future 的版本:

从 GDAL 2.2 开始,支持用 Python 编写的 VRT 像素函数:

http://www.gdal.org/gdal_vrttut.html#gdal_vrttut_derived_python

然后你就可以制作一个看起来像这样的 VRT:

<VRTDataset rasterXSize="20" rasterYSize="20"> 
  <SRS>EPSG:26711</SRS> 
  <GeoTransform>440720,60,0,3751320,0,-60</GeoTransform> 
  <VRTRasterBand dataType="Byte" band="1" subClass="VRTDerivedRasterBand"> 
    <PixelFunctionType>add</PixelFunctionType> 
    <PixelFunctionLanguage>Python</PixelFunctionLanguage> 
    <PixelFunctionCode><![CDATA[ 
import numpy as np 
def add(in_ar, out_ar, xoff, yoff, xsize, ysize, raster_xsize, 
                   raster_ysize, buf_radius, gt, **kwargs): 
    np.round_(np.clip(np.minimum(in_ar, axis = 0, dtype = 'uint16'),0,255), 
              out = out_ar) 
]]> 
    </PixelFunctionCode> 
    <SimpleSource> 
      <SourceFilename relativeToVRT="1">byte.tif</SourceFilename> 
    </SimpleSource> 
    <SimpleSource> 
      <SourceFilename relativeToVRT="1">byte2.tif</SourceFilename> 
    </SimpleSource> 
  </VRTRasterBand> 
</VRTDataset> 

同样从 GDAL 2.2 开始,将内置像素函数,这是一个好主意。我还没有看到像 min、max、mean 这样的聚合,但是一旦基础设施存在,应该很容易添加。 http://www.gdal.org/gdal_vrttut.html#gdal_vrttut_derived_c