1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
|
/******************************************************************************
*
* Project: GDAL
* Purpose: "edit" step of "raster pipeline"
* Author: Even Rouault <even dot rouault at spatialys.com>
*
******************************************************************************
* Copyright (c) 2024, Even Rouault <even dot rouault at spatialys.com>
*
* SPDX-License-Identifier: MIT
****************************************************************************/
#include "gdalalg_raster_edit.h"
#include "gdal_priv.h"
#include "gdal_utils.h"
#include "ogrsf_frmts.h"
//! @cond Doxygen_Suppress
#ifndef _
#define _(x) (x)
#endif
/************************************************************************/
/* GetGCPFilename() */
/************************************************************************/
static std::string GetGCPFilename(const std::vector<std::string> &gcps)
{
if (gcps.size() == 1 && !gcps[0].empty() && gcps[0][0] == '@')
{
return gcps[0].substr(1);
}
return std::string();
}
/************************************************************************/
/* GDALRasterEditAlgorithm::GDALRasterEditAlgorithm() */
/************************************************************************/
GDALRasterEditAlgorithm::GDALRasterEditAlgorithm(bool standaloneStep)
: GDALRasterPipelineStepAlgorithm(
NAME, DESCRIPTION, HELP_URL,
ConstructorOptions().SetAddDefaultArguments(false))
{
if (standaloneStep)
{
AddProgressArg();
AddArg("dataset", 0,
_("Dataset (to be updated in-place, unless --auxiliary)"),
&m_dataset, GDAL_OF_RASTER | GDAL_OF_UPDATE)
.SetPositional()
.SetRequired();
AddArg("auxiliary", 0,
_("Ask for an auxiliary .aux.xml file to be edited"),
&m_readOnly)
.AddHiddenAlias("ro")
.AddHiddenAlias(GDAL_ARG_NAME_READ_ONLY);
}
AddArg("crs", 0, _("Override CRS (without reprojection)"), &m_overrideCrs)
.AddHiddenAlias("a_srs")
.AddHiddenAlias("srs")
.SetIsCRSArg(/*noneAllowed=*/true);
AddBBOXArg(&m_bbox);
AddNodataArg(&m_nodata, /* noneAllowed = */ true);
{
auto &arg = AddArg("metadata", 0, _("Add/update dataset metadata item"),
&m_metadata)
.SetMetaVar("<KEY>=<VALUE>")
.SetPackedValuesAllowed(false);
arg.AddValidationAction([this, &arg]()
{ return ParseAndValidateKeyValue(arg); });
arg.AddHiddenAlias("mo");
}
AddArg("unset-metadata", 0, _("Remove dataset metadata item(s)"),
&m_unsetMetadata)
.SetMetaVar("<KEY>");
AddArg("unset-metadata-domain", 0, _("Remove dataset metadata domain(s)"),
&m_unsetMetadataDomain)
.SetMetaVar("<DOMAIN>");
AddArg("gcp", 0,
_("Add ground control point, formatted as "
"pixel,line,easting,northing[,elevation], or @filename"),
&m_gcps)
.SetPackedValuesAllowed(false)
.AddValidationAction(
[this]()
{
if (GetGCPFilename(m_gcps).empty())
{
for (const std::string &gcp : m_gcps)
{
const CPLStringList aosTokens(
CSLTokenizeString2(gcp.c_str(), ",", 0));
if (aosTokens.size() != 4 && aosTokens.size() != 5)
{
ReportError(CE_Failure, CPLE_IllegalArg,
"Bad format for %s", gcp.c_str());
return false;
}
for (int i = 0; i < aosTokens.size(); ++i)
{
if (CPLGetValueType(aosTokens[i]) ==
CPL_VALUE_STRING)
{
ReportError(CE_Failure, CPLE_IllegalArg,
"Bad format for %s", gcp.c_str());
return false;
}
}
}
}
return true;
});
if (standaloneStep)
{
AddArg("stats", 0, _("Compute statistics, using all pixels"), &m_stats)
.SetMutualExclusionGroup("stats");
AddArg("approx-stats", 0,
_("Compute statistics, using a subset of pixels"),
&m_approxStats)
.SetMutualExclusionGroup("stats");
AddArg("hist", 0, _("Compute histogram"), &m_hist);
}
}
/************************************************************************/
/* GDALRasterEditAlgorithm::~GDALRasterEditAlgorithm() */
/************************************************************************/
GDALRasterEditAlgorithm::~GDALRasterEditAlgorithm() = default;
/************************************************************************/
/* ParseGCPs() */
/************************************************************************/
std::vector<gdal::GCP> GDALRasterEditAlgorithm::ParseGCPs() const
{
std::vector<gdal::GCP> ret;
const std::string osGCPFilename = GetGCPFilename(m_gcps);
if (!osGCPFilename.empty())
{
auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
osGCPFilename.c_str(), GDAL_OF_VECTOR | GDAL_OF_VERBOSE_ERROR));
if (!poDS)
return ret;
if (poDS->GetLayerCount() != 1)
{
ReportError(CE_Failure, CPLE_AppDefined,
"GCPs can only be specified for single-layer datasets");
return ret;
}
auto poLayer = poDS->GetLayer(0);
const auto poLayerDefn = poLayer->GetLayerDefn();
int nIdIdx = -1, nInfoIdx = -1, nColIdx = -1, nLineIdx = -1, nXIdx = -1,
nYIdx = -1, nZIdx = -1;
const struct
{
int &idx;
const char *name;
bool required;
} aFields[] = {
{nIdIdx, "id", false}, {nInfoIdx, "info", false},
{nColIdx, "column", true}, {nLineIdx, "line", true},
{nXIdx, "x", true}, {nYIdx, "y", true},
{nZIdx, "z", false},
};
for (auto &field : aFields)
{
field.idx = poLayerDefn->GetFieldIndex(field.name);
if (field.idx < 0 && field.required)
{
ReportError(CE_Failure, CPLE_AppDefined,
"Field '%s' cannot be found in '%s'", field.name,
poDS->GetDescription());
return ret;
}
}
for (auto &&poFeature : poLayer)
{
gdal::GCP gcp;
if (nIdIdx >= 0)
gcp.SetId(poFeature->GetFieldAsString(nIdIdx));
if (nInfoIdx >= 0)
gcp.SetInfo(poFeature->GetFieldAsString(nInfoIdx));
gcp.Pixel() = poFeature->GetFieldAsDouble(nColIdx);
gcp.Line() = poFeature->GetFieldAsDouble(nLineIdx);
gcp.X() = poFeature->GetFieldAsDouble(nXIdx);
gcp.Y() = poFeature->GetFieldAsDouble(nYIdx);
if (nZIdx >= 0 && poFeature->IsFieldSetAndNotNull(nZIdx))
gcp.Z() = poFeature->GetFieldAsDouble(nZIdx);
ret.push_back(std::move(gcp));
}
}
else
{
for (const std::string &gcpStr : m_gcps)
{
const CPLStringList aosTokens(
CSLTokenizeString2(gcpStr.c_str(), ",", 0));
// Verified by validation action
CPLAssert(aosTokens.size() == 4 || aosTokens.size() == 5);
gdal::GCP gcp;
gcp.Pixel() = CPLAtof(aosTokens[0]);
gcp.Line() = CPLAtof(aosTokens[1]);
gcp.X() = CPLAtof(aosTokens[2]);
gcp.Y() = CPLAtof(aosTokens[3]);
if (aosTokens.size() == 5)
gcp.Z() = CPLAtof(aosTokens[4]);
ret.push_back(std::move(gcp));
}
}
return ret;
}
/************************************************************************/
/* GDALRasterEditAlgorithm::RunStep() */
/************************************************************************/
bool GDALRasterEditAlgorithm::RunStep(GDALPipelineStepRunContext &ctxt)
{
GDALDataset *poDS = m_dataset.GetDatasetRef();
if (poDS)
{
if (poDS->GetAccess() != GA_Update && !m_readOnly)
{
ReportError(CE_Failure, CPLE_AppDefined,
"Dataset should be opened in update mode unless "
"--auxiliary is set");
return false;
}
}
else
{
const auto poSrcDS = m_inputDataset[0].GetDatasetRef();
CPLAssert(poSrcDS);
CPLAssert(m_outputDataset.GetName().empty());
CPLAssert(!m_outputDataset.GetDatasetRef());
CPLStringList aosOptions;
aosOptions.push_back("-of");
aosOptions.push_back("VRT");
GDALTranslateOptions *psOptions =
GDALTranslateOptionsNew(aosOptions.List(), nullptr);
GDALDatasetH hSrcDS = GDALDataset::ToHandle(poSrcDS);
auto poRetDS = GDALDataset::FromHandle(
GDALTranslate("", hSrcDS, psOptions, nullptr));
GDALTranslateOptionsFree(psOptions);
m_outputDataset.Set(std::unique_ptr<GDALDataset>(poRetDS));
poDS = m_outputDataset.GetDatasetRef();
}
bool ret = poDS != nullptr;
if (poDS)
{
if (m_overrideCrs == "null" || m_overrideCrs == "none")
{
if (poDS->SetSpatialRef(nullptr) != CE_None)
{
ReportError(CE_Failure, CPLE_AppDefined,
"SetSpatialRef(%s) failed", m_overrideCrs.c_str());
return false;
}
}
else if (!m_overrideCrs.empty() && m_gcps.empty())
{
OGRSpatialReference oSRS;
oSRS.SetFromUserInput(m_overrideCrs.c_str());
oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
if (poDS->SetSpatialRef(&oSRS) != CE_None)
{
ReportError(CE_Failure, CPLE_AppDefined,
"SetSpatialRef(%s) failed", m_overrideCrs.c_str());
return false;
}
}
if (!m_bbox.empty())
{
if (poDS->GetRasterXSize() == 0 || poDS->GetRasterYSize() == 0)
{
ReportError(CE_Failure, CPLE_AppDefined,
"Cannot set extent because one of dataset height "
"or width is null");
return false;
}
GDALGeoTransform gt;
gt[0] = m_bbox[0];
gt[1] = (m_bbox[2] - m_bbox[0]) / poDS->GetRasterXSize();
gt[2] = 0;
gt[3] = m_bbox[3];
gt[4] = 0;
gt[5] = -(m_bbox[3] - m_bbox[1]) / poDS->GetRasterYSize();
if (poDS->SetGeoTransform(gt) != CE_None)
{
ReportError(CE_Failure, CPLE_AppDefined,
"Setting extent failed");
return false;
}
}
if (!m_nodata.empty())
{
for (int i = 0; i < poDS->GetRasterCount(); ++i)
{
if (EQUAL(m_nodata.c_str(), "none"))
poDS->GetRasterBand(i + 1)->DeleteNoDataValue();
else
poDS->GetRasterBand(i + 1)->SetNoDataValue(
CPLAtof(m_nodata.c_str()));
}
}
const CPLStringList aosMD(m_metadata);
for (const auto &[key, value] : cpl::IterateNameValue(aosMD))
{
if (poDS->SetMetadataItem(key, value) != CE_None)
{
ReportError(CE_Failure, CPLE_AppDefined,
"SetMetadataItem('%s', '%s') failed", key, value);
return false;
}
}
for (const std::string &key : m_unsetMetadata)
{
if (poDS->SetMetadataItem(key.c_str(), nullptr) != CE_None)
{
ReportError(CE_Failure, CPLE_AppDefined,
"SetMetadataItem('%s', NULL) failed", key.c_str());
return false;
}
}
for (const std::string &domain : m_unsetMetadataDomain)
{
if (poDS->SetMetadata(nullptr, domain.c_str()) != CE_None)
{
ReportError(CE_Failure, CPLE_AppDefined,
"SetMetadata(NULL, '%s') failed", domain.c_str());
return false;
}
}
if (!m_gcps.empty())
{
const auto gcps = ParseGCPs();
if (gcps.empty())
return false; // error already emitted by ParseGCPs()
OGRSpatialReference oSRS;
if (!m_overrideCrs.empty())
{
oSRS.SetFromUserInput(m_overrideCrs.c_str());
oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
}
if (poDS->SetGCPs(static_cast<int>(gcps.size()), gcps[0].c_ptr(),
oSRS.IsEmpty() ? nullptr : &oSRS) != CE_None)
{
ReportError(CE_Failure, CPLE_AppDefined, "Setting GCPs failed");
return false;
}
}
const int nBands = poDS->GetRasterCount();
int nCurProgress = 0;
const double dfTotalProgress =
((m_stats || m_approxStats) ? nBands : 0) + (m_hist ? nBands : 0);
if (m_stats || m_approxStats)
{
for (int i = 0; (i < nBands) && ret; ++i)
{
void *pScaledProgress = GDALCreateScaledProgress(
nCurProgress / dfTotalProgress,
(nCurProgress + 1) / dfTotalProgress, ctxt.m_pfnProgress,
ctxt.m_pProgressData);
++nCurProgress;
double dfMin = 0.0;
double dfMax = 0.0;
double dfMean = 0.0;
double dfStdDev = 0.0;
ret = poDS->GetRasterBand(i + 1)->ComputeStatistics(
m_approxStats, &dfMin, &dfMax, &dfMean, &dfStdDev,
pScaledProgress ? GDALScaledProgress : nullptr,
pScaledProgress) == CE_None;
GDALDestroyScaledProgress(pScaledProgress);
}
}
if (m_hist)
{
for (int i = 0; (i < nBands) && ret; ++i)
{
void *pScaledProgress = GDALCreateScaledProgress(
nCurProgress / dfTotalProgress,
(nCurProgress + 1) / dfTotalProgress, ctxt.m_pfnProgress,
ctxt.m_pProgressData);
++nCurProgress;
double dfMin = 0.0;
double dfMax = 0.0;
int nBucketCount = 0;
GUIntBig *panHistogram = nullptr;
ret = poDS->GetRasterBand(i + 1)->GetDefaultHistogram(
&dfMin, &dfMax, &nBucketCount, &panHistogram, TRUE,
pScaledProgress ? GDALScaledProgress : nullptr,
pScaledProgress) == CE_None;
if (ret)
{
ret = poDS->GetRasterBand(i + 1)->SetDefaultHistogram(
dfMin, dfMax, nBucketCount, panHistogram) ==
CE_None;
}
CPLFree(panHistogram);
GDALDestroyScaledProgress(pScaledProgress);
}
}
}
return poDS != nullptr;
}
GDALRasterEditAlgorithmStandalone::~GDALRasterEditAlgorithmStandalone() =
default;
//! @endcond
|