如何使用GDAL重采样图像 .

本文介绍如何使用GDAL库进行图像重采样,并提供了一个详细的重采样接口实现示例,包括各种重采样算法的选择与应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  在编写重采样图像时,可以使用GDAL来读写图像,然后自己编写重采样算法(最邻近像元法,双线性内插法,三次立方卷积法等)【关于这采样算法有时间我会单独写一篇文章来说明原理的】将计算的结果写入图像中来实现。

    在GDAL的算法中,已经提供了五种重采样算法,其定义如下(位置gdalwarper.h 的46行):

/*! Warp Resampling Algorithm */
typedef enum {
  /*! Nearest neighbour (select on one input pixel) */ GRA_NearestNeighbour=0,
  /*! Bilinear (2x2 kernel) */                         GRA_Bilinear=1,
  /*! Cubic Convolution Approximation (4x4 kernel) */  GRA_Cubic=2,
  /*! Cubic B-Spline Approximation (4x4 kernel) */     GRA_CubicSpline=3,
  /*! Lanczos windowed sinc interpolation (6x6 kernel) */ GRA_Lanczos=4
} GDALResampleAlg;


在查看Gdalwarp的源代码发现,warp的功能非常强大,可以用来做投影转换,重投影,投影定义,重采样,镶嵌,几何精校正和影像配准等。一句话,很好很强大。下面就看看其中的一点点皮毛,使用warp来编写一个重采样的接口,代码如下:

/**
* 重采样函数(GDAL)
* @param pszSrcFile        输入文件的路径
* @param pszOutFile        写入的结果图像的路径
* @param fResX             X转换采样比,默认大小为1.0,大于1图像变大,小于1表示图像缩小
* @param fResY             Y转换采样比,默认大小为1.0
* @param nResampleMode     采样模式,有五种,具体参见GDALResampleAlg定义,默认为双线性内插
* @param pExtent           采样范围,为NULL表示计算全图
* @param pBandIndex        指定的采样波段序号,为NULL表示采样全部波段
* @param pBandCount        采样的波段个数,同pBandIndex一同使用,表示采样波段的个数
* @param pszFormat         写入的结果图像的格式
* @param pProgress         进度条指针
* @return 成功返回0,否则为其他值
*/
int ResampleGDAL(const char* pszSrcFile, const char* pszOutFile, float fResX , float fResY, LT_ResampleMode nResampleMode,
    LT_Envelope* pExtent, int* pBandIndex, int *pBandCount, const char* pszFormat,  LT_Progress *pProgress)
{
    if(pProgress != NULL)
    {
        pProgress->SetProgressCaption("重采样");
        pProgress->SetProgressTip("正在执行重采样...");
    }

    GDALAllRegister();
    GDALDataset *pDSrc = (GDALDataset *)GDALOpen(pszSrcFile, GA_ReadOnly);
    if (pDSrc == NULL)
    {
        if(pProgress != NULL)
            pProgress->SetProgressTip("指定的文件不存在,或者该格式不被支持!");

        return RE_NOFILE;
    }

    GDALDriver *pDriver = GetGDALDriverManager()->GetDriverByName(pszFormat);
    if (pDriver == NULL)
    {
        if(pProgress != NULL)
            pProgress->SetProgressTip("不能创建该格式的文件!");

        GDALClose((GDALDatasetH) pDSrc);
        return RE_CREATEFILE;
    }

    int iBandCount = pDSrc->GetRasterCount();
    string strWkt = pDSrc->GetProjectionRef();//返回坐标系统
    GDALDataType dataType = pDSrc->GetRasterBand(1)->GetRasterDataType();

    double dGeoTrans[6] = {0};
    pDSrc->GetGeoTransform(dGeoTrans);   //六个参数其实是图像行列号坐标和地理坐标转换系数

    int iNewBandCount = iBandCount;
    if (pBandIndex != NULL && pBandCount != NULL)
    {
        int iMaxBandIndex = pBandIndex[0];    //找出最大的波段索引序号
        for (int i=1; i<*pBandCount; i++)
        {
            if (iMaxBandIndex < pBandIndex[i])
                iMaxBandIndex = pBandIndex[i];
        }

        if(iMaxBandIndex > iBandCount)
        {
            if(pProgress != NULL)
                pProgress->SetProgressTip("指定的波段序号超过图像的波段数,请检查输入参数!");

            GDALClose((GDALDatasetH) pDSrc);
            return RE_PARAMERROR;
        }
        
        iNewBandCount = *pBandCount;
    }

    LT_Envelope enExtent;
    enExtent.setToNull();

    if (pExtent == NULL)    //全图计算

    {
        double dPrj[4] = {0};    //x1,x2,y1,y2
        ImageRowCol2Projection(dGeoTrans, 0, 0, dPrj[0], dPrj[2]); //将图像左上角行列号(0,0)坐标转为地理坐标
        ImageRowCol2Projection(dGeoTrans, pDSrc->GetRasterXSize(), pDSrc->GetRasterYSize(), dPrj[1], dPrj[3]);//将图像右下角的坐标转为地理坐标
        enExtent.init(dPrj[0], dPrj[1], dPrj[2], dPrj[3]);

        pExtent = &enExtent;
    }
    
    dGeoTrans[0] = pExtent->getMinX();
    dGeoTrans[3] = pExtent->getMaxY();   //dGeoTrans[0],dGeoTrans[3]表示的是左上角的地理坐标
    dGeoTrans[1] = dGeoTrans[1] / fResX; 
    dGeoTrans[5] = dGeoTrans[5] / fResY;  //dGeoTrans[1],dGeoTrans[5]表示的是图像横向和纵向的分辨率

    int iNewWidth  = static_cast<int>( (pExtent->getMaxX() - pExtent->getMinX() / ABS(dGeoTrans[1]) + 0.5) );
    int iNewHeight = static_cast<int>( (pExtent->getMaxX() - pExtent->getMinX() / ABS(dGeoTrans[5]) + 0.5) );

    GDALDataset *pDDst = pDriver->Create(pszOutFile, iNewWidth, iNewHeight, iNewBandCount, dataType, NULL);
    if (pDDst == NULL)
    {
        if(pProgress != NULL)
            pProgress->SetProgressTip("创建输出文件失败!");

        GDALClose((GDALDatasetH) pDSrc);
        return RE_CREATEFILE;
    }

    pDDst->SetProjection(strWkt.c_str());
    pDDst->SetGeoTransform(dGeoTrans);

    GDALResampleAlg eResample = (GDALResampleAlg) nResampleMode;

    if(pProgress != NULL)
    {
        pProgress->SetProgressTip("正在执行重采样...");
        pProgress->SetProgressTotalStep(iNewBandCount*iNewHeight);
    }

    int *pSrcBand = NULL;
    int *pDstBand = NULL;
    int iBandSize = 0;
    if (pBandIndex != NULL && pBandCount != NULL)
    {
        iBandSize = *pBandCount;
        pSrcBand = new int[iBandSize];
        pDstBand = new int[iBandSize];

        for (int i=0; i<iBandSize; i++)
        {
            pSrcBand[i] = pBandIndex[i];
            pDstBand[i] = i+1;
        }
    }
    else
    {
        iBandSize = iBandCount;
        pSrcBand = new int[iBandSize];
        pDstBand = new int[iBandSize];

        for (int i=0; i<iBandSize; i++)
        {
            pSrcBand[i] = i+1;
            pDstBand[i] = i+1;
        }
    }
    
    void *hTransformArg = NULL, *hGenImgPrjArg = NULL;
    hTransformArg = hGenImgPrjArg = GDALCreateGenImgProjTransformer2((GDALDatasetH) pDSrc, (GDALDatasetH) pDDst, NULL);
    if (hTransformArg == NULL)
    {
        if(pProgress != NULL)
            pProgress->SetProgressTip("转换参数错误!");

        GDALClose((GDALDatasetH) pDSrc);
        GDALClose((GDALDatasetH) pDDst);
        return RE_PARAMERROR;
    }
    
    GDALTransformerFunc pFnTransformer = GDALGenImgProjTransform;
    GDALWarpOptions *psWo = GDALCreateWarpOptions();

    psWo->papszWarpOptions = CSLDuplicate(NULL);
    psWo->eWorkingDataType = dataType;
    psWo->eResampleAlg = eResample;

    psWo->hSrcDS = (GDALDatasetH) pDSrc;
    psWo->hDstDS = (GDALDatasetH) pDDst;

    psWo->pfnTransformer = pFnTransformer;
    psWo->pTransformerArg = hTransformArg;

    psWo->pfnProgress = GDALProgress;
    psWo->pProgressArg = pProgress;

    psWo->nBandCount = iNewBandCount;
    psWo->panSrcBands = (int *) CPLMalloc(iNewBandCount*sizeof(int));
    psWo->panDstBands = (int *) CPLMalloc(iNewBandCount*sizeof(int));
    for (int i=0; i<iNewBandCount; i++)
    {
        psWo->panSrcBands[i] = pSrcBand[i];
        psWo->panDstBands[i] = pDstBand[i];
    }

    RELEASE(pSrcBand);
    RELEASE(pDstBand);

    GDALWarpOperation oWo;
    if (oWo.Initialize(psWo) != CE_None)
    {
        if(pProgress != NULL)
            pProgress->SetProgressTip("转换参数错误!");

        GDALClose((GDALDatasetH) pDSrc);
        GDALClose((GDALDatasetH) pDDst);

        return RE_PARAMERROR;
    }

    oWo.ChunkAndWarpImage(0, 0, iNewWidth, iNewHeight);
    
    GDALDestroyGenImgProjTransformer(psWo->pTransformerArg);
    GDALDestroyWarpOptions( psWo );
    GDALClose((GDALDatasetH) pDSrc);
    GDALClose((GDALDatasetH) pDDst);

    if(pProgress != NULL)
        pProgress->SetProgressTip("重采样完成!");

    return RE_SUCCESS;
}

### 使用 GDAL 进行重采样的方法 GDAL 提供了多种工具来完成栅格数据的重采样操作,其中最常用的两种方式分别是 `gdal_translate` 和 `gdal_warp`。以下是具体的方法和示例: #### 方法一:使用 `gdal_translate` 修改分辨率 `gdal_translate` 是一种简单的方式,可以通过指定 `-outsize` 参数调整输出图像的空间大小或者通过 `-tr` 参数直接设定目标像元尺寸。 ```python from osgeo import gdal # 输入文件路径 input_file = 'input.tif' output_file = 'output_resampled.tif' # 设置新的像元分辨率 (x_resolution, y_resolution) new_xres = 30 # 新X方向分辨率 new_yres = 30 # 新Y方向分辨率 # 执行重采样命令 options = ['-of', 'GTiff', '-tr', str(new_xres), str(new_yres), '-r', 'near'] gdal.Translate(output_file, input_file, options=options) print(f"Resampling completed and saved to {output_file}.") ``` 此方法适用于简单的分辨率修改场景,并且其性能较优[^1]。 --- #### 方法二:使用 `gdal.Warp` 实现更复杂的重采样 对于需要更多控制选项的情况(例如裁剪、投影转换等),可以使用 `gdal.Warp` 函数。它支持更多的参数配置,适合复杂的数据处理需求。 ```python from osgeo import gdal # 定义输入和输出文件名 input_file = 'input.tif' output_file = 'output_warped.tif' # 设定新分辨率和其他参数 new_xres = 30 # X方向的新分辨率 new_yres = 30 # Y方向的新分辨率 resample_method = 'cubic' # 可选插值方法 ['near'|'bilinear'|'cubic'|...] # 调用Warp函数进行重采样 warp_options = gdal.WarpOptions( format='GTiff', xRes=new_xres, yRes=new_yres, resampleAlg=resample_method ) gdal.Warp(output_file, input_file, options=warp_options) print(f"Warping with resampling completed and saved to {output_file}.") ``` 这种方法不仅能够改变分辨率,还可以同时完成其他任务,比如坐标系转换或裁剪边界调整[^3]。 --- #### 插值算法的选择 在上述代码中提到的插值方法 (`-r`) 对最终结果的质量有很大影响。常见的几种插值方法如下: - **近邻法 (Nearest Neighbor)**:速度快,但可能会引入锯齿效应。 - **双线性插值 (Bilinear Interpolation)**:平滑度较高,计算量适中。 - **三次卷积插值 (Cubic Convolution)**:提供更高的平滑性和精度,但耗时较长。 不同应用场景下可以选择合适的插值策略以平衡速度与质量之间的关系[^4]。 --- #### Java 中调用 GDAL 的注意事项 虽然 Python 是目前主流语言之一,在某些特定环境下也可能需要用到 Java 来集成 GDAL 功能。然而需要注意的是,Java 版本可能存在一些局限性,尤其是在高性能运算方面表现不如原生 C++ 或者绑定紧密的语言如 Python。因此如果计划采用这种方式,则需额外关注程序稳定性测试以及针对实际业务逻辑做进一步优化[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值