Commit 4bb6fcd7 authored by xuebingbing's avatar xuebingbing

gdal-dev updates

parent 21b37d13
......@@ -58,7 +58,7 @@ public:
/**
* Json object types
*/
enum Type {
enum class Type {
Unknown,
Null,
Object,
......@@ -73,7 +73,7 @@ public:
/**
* Json object format to string options
*/
enum PrettyFormat {
enum class PrettyFormat {
Plain, ///< No extra whitespace or formatting applied
Spaced, ///< Minimal whitespace inserted
Pretty ///< Formatted output
......@@ -128,14 +128,14 @@ public:
GInt64 ToLong(GInt64 nDefault = 0) const;
bool ToBool(bool bDefault = false) const;
CPLJSONArray ToArray() const;
std::string Format(enum PrettyFormat eFormat) const;
std::string Format(PrettyFormat eFormat) const;
//
void Delete(const std::string &osName);
CPLJSONArray GetArray(const std::string &osName) const;
CPLJSONObject GetObj(const std::string &osName) const;
CPLJSONObject operator[](const std::string &osName) const;
enum Type GetType() const;
Type GetType() const;
/*! @cond Doxygen_Suppress */
std::string GetName() const { return m_osKey; }
/*! @endcond */
......@@ -169,6 +169,22 @@ public:
private:
explicit CPLJSONArray(const std::string &osName, JSONObjectH poJsonObject);
class CPL_DLL ConstIterator
{
const CPLJSONArray& m_oSelf;
int m_nIdx;
mutable CPLJSONObject m_oObj{};
public:
ConstIterator(const CPLJSONArray& oSelf, bool bStart): m_oSelf(oSelf), m_nIdx(bStart ? 0 : oSelf.Size()) {}
~ConstIterator() = default;
CPLJSONObject& operator*() const { m_oObj = m_oSelf[m_nIdx]; return m_oObj; }
ConstIterator& operator++() { m_nIdx ++; return *this; }
bool operator==(const ConstIterator& it) const { return m_nIdx == it.m_nIdx; }
bool operator!=(const ConstIterator& it) const { return m_nIdx != it.m_nIdx; }
};
/*! @endcond */
public:
int Size() const;
......@@ -181,6 +197,11 @@ public:
void Add(bool bValue);
CPLJSONObject operator[](int nIndex);
const CPLJSONObject operator[](int nIndex) const;
/** Iterator to first element */
ConstIterator begin() const { return ConstIterator(*this, true); }
/** Iterator to after last element */
ConstIterator end() const { return ConstIterator(*this, false); }
};
/**
......@@ -207,7 +228,7 @@ public:
bool LoadChunks(const std::string &osPath, size_t nChunkSize = 16384,
GDALProgressFunc pfnProgress = nullptr,
void *pProgressArg = nullptr);
bool LoadUrl(const std::string &osUrl, char **papszOptions,
bool LoadUrl(const std::string &osUrl, const char* const* papszOptions,
GDALProgressFunc pfnProgress = nullptr,
void *pProgressArg = nullptr);
......
......@@ -1053,7 +1053,7 @@ CPL_C_END
static_cast<size_t>(!(sizeof(array) % sizeof(*(array)))))
extern "C++" {
template<class T> static void CPL_IGNORE_RET_VAL(T) {}
template<class T> static void CPL_IGNORE_RET_VAL(const T&) {}
inline static bool CPL_TO_BOOL(int x) { return x != 0; }
} /* extern "C++" */
......
......@@ -81,14 +81,14 @@ class FileProp
CPLString ETag{};
};
typedef struct
struct CachedDirList
{
bool bGotFileList = false;
unsigned int nGenerationAuthParameters = 0;
CPLStringList oFileList{}; /* only file name without path */
} CachedDirList;
};
typedef struct
struct WriteFuncStruct
{
char* pBuffer = nullptr;
size_t nSize = 0;
......@@ -116,7 +116,7 @@ typedef struct
// CURLOPT_SUPPRESS_CONNECT_HEADERS fixes this
bool bIsProxyConnectHeader = false;
#endif
} WriteFuncStruct;
};
/************************************************************************/
/* VSICurlFilesystemHandler */
......@@ -161,7 +161,8 @@ class VSICurlFilesystemHandler : public VSIFilesystemHandler
std::shared_ptr<std::string>>>::iterator,
FilenameOffsetPairHasher>>;
RegionCacheType oRegionCache;
std::unique_ptr<RegionCacheType> m_poRegionCacheDoNotUseDirectly{}; // do not access directly. Use GetRegionCache();
RegionCacheType* GetRegionCache();
lru11::Cache<std::string, FileProp> oCacheFileProp;
......@@ -435,7 +436,7 @@ class IVSIS3LikeFSHandler: public VSICurlFilesystemHandler
double dfRetryDelay);
bool CompleteMultipart(const CPLString& osFilename,
const CPLString& osUploadID,
const std::vector<CPLString> aosEtags,
const std::vector<CPLString>& aosEtags,
IVSIS3LikeHandleHelper *poS3HandleHelper,
int nMaxRetry,
double dfRetryDelay);
......
......@@ -32,6 +32,10 @@
#include "cpl_multiproc.h"
#include "cpl_list.h"
#include <condition_variable>
#include <memory>
#include <mutex>
#include <vector>
/**
......@@ -42,26 +46,23 @@
*/
#ifndef DOXYGEN_SKIP
struct CPLWorkerThreadJob;
class CPLWorkerThreadPool;
typedef struct
struct CPLWorkerThread
{
CPLThreadFunc pfnFunc;
void *pData;
} CPLWorkerThreadJob;
CPL_DISALLOW_COPY_ASSIGN(CPLWorkerThread)
CPLWorkerThread() = default;
typedef struct
{
CPLThreadFunc pfnInitFunc;
void *pInitData;
CPLWorkerThreadPool *poTP;
CPLJoinableThread *hThread;
int bMarkedAsWaiting;
// CPLWorkerThreadJob *psNextJob;
CPLThreadFunc pfnInitFunc = nullptr;
void *pInitData = nullptr;
CPLWorkerThreadPool *poTP = nullptr;
CPLJoinableThread *hThread = nullptr;
bool bMarkedAsWaiting = false;
CPLMutex *hMutex;
CPLCond *hCond;
} CPLWorkerThread;
std::mutex m_mutex{};
std::condition_variable m_cv{};
};
typedef enum
{
......@@ -71,14 +72,16 @@ typedef enum
} CPLWorkerThreadState;
#endif // ndef DOXYGEN_SKIP
class CPLJobQueue;
/** Pool of worker threads */
class CPL_DLL CPLWorkerThreadPool
{
CPL_DISALLOW_COPY_ASSIGN(CPLWorkerThreadPool)
std::vector<CPLWorkerThread> aWT{};
CPLCond* hCond = nullptr;
CPLMutex* hMutex = nullptr;
std::vector<std::unique_ptr<CPLWorkerThread>> aWT{};
std::mutex m_mutex{};
std::condition_variable m_cv{};
volatile CPLWorkerThreadState eState = CPLWTS_OK;
CPLList* psJobQueue = nullptr;
volatile int nPendingJobs = 0;
......@@ -95,6 +98,7 @@ class CPL_DLL CPLWorkerThreadPool
CPLWorkerThreadPool();
~CPLWorkerThreadPool();
bool Setup(int nThreads,
CPLThreadFunc pfnInitFunc,
void** pasInitData);
......@@ -102,6 +106,9 @@ class CPL_DLL CPLWorkerThreadPool
CPLThreadFunc pfnInitFunc,
void** pasInitData,
bool bWaitallStarted);
std::unique_ptr<CPLJobQueue> CreateJobQueue();
bool SubmitJob(CPLThreadFunc pfnFunc, void* pData);
bool SubmitJobs(CPLThreadFunc pfnFunc, const std::vector<void*>& apData);
void WaitCompletion(int nMaxRemainingJobs = 0);
......@@ -111,4 +118,32 @@ class CPL_DLL CPLWorkerThreadPool
int GetThreadCount() const { return static_cast<int>(aWT.size()); }
};
/** Job queue */
class CPL_DLL CPLJobQueue
{
CPL_DISALLOW_COPY_ASSIGN(CPLJobQueue)
CPLWorkerThreadPool* m_poPool = nullptr;
std::mutex m_mutex{};
std::condition_variable m_cv{};
int m_nPendingJobs = 0;
static void JobQueueFunction(void*);
void DeclareJobFinished();
//! @cond Doxygen_Suppress
protected:
friend class CPLWorkerThreadPool;
explicit CPLJobQueue(CPLWorkerThreadPool* poPool);
//! @endcond
public:
~CPLJobQueue();
/** Return the owning worker thread pool */
CPLWorkerThreadPool* GetPool() { return m_poPool; }
bool SubmitJob(CPLThreadFunc pfnFunc, void* pData);
void WaitCompletion(int nMaxRemainingJobs = 0);
};
#endif // CPL_WORKER_THREAD_POOL_H_INCLUDED_
......@@ -135,8 +135,11 @@ typedef enum
/*! Average */ GRIORA_Average = 5,
/*! Mode (selects the value which appears most often of all the sampled points) */
GRIORA_Mode = 6,
/*! Gauss blurring */ GRIORA_Gauss = 7
/*! Gauss blurring */ GRIORA_Gauss = 7,
/* NOTE: values 8 to 12 are reserved for max,min,med,Q1,Q3 */
/*! @cond Doxygen_Suppress */
GRIORA_LAST = GRIORA_Gauss
/*! @endcond */
} GDALRIOResampleAlg;
/* NOTE to developers: only add members, and if so edit INIT_RASTERIO_EXTRA_ARG */
......@@ -440,6 +443,11 @@ typedef struct GDALDimensionHS* GDALDimensionH;
*/
#define GDAL_DCAP_NOTNULL_FIELDS "DCAP_NOTNULL_FIELDS"
/** Capability set by a driver that can create fields with UNIQUE constraint.
* @since GDAL 3.2
*/
#define GDAL_DCAP_UNIQUE_FIELDS "DCAP_UNIQUE_FIELDS"
/** Capability set by a driver that can create fields with DEFAULT values.
* @since GDAL 2.0
*/
......
......@@ -864,7 +864,7 @@ struct CPL_DLL GDALDatasetUniquePtrDeleter
* reference counter has not been manually modified.
* @since GDAL 2.3
*/
typedef std::unique_ptr<GDALDataset, GDALDatasetUniquePtrDeleter> GDALDatasetUniquePtr;
using GDALDatasetUniquePtr = std::unique_ptr<GDALDataset, GDALDatasetUniquePtrDeleter>;
/* ******************************************************************** */
/* GDALRasterBlock */
......@@ -2608,13 +2608,15 @@ typedef CPLErr (*GDALResampleFunction)
double dfSrcXDelta,
double dfSrcYDelta,
GDALDataType eWrkDataType,
void * pChunk,
GByte * pabyChunkNodataMask,
const void * pChunk,
const GByte * pabyChunkNodataMask,
int nChunkXOff, int nChunkXSize,
int nChunkYOff, int nChunkYSize,
int nDstXOff, int nDstXOff2,
int nDstYOff, int nDstYOff2,
GDALRasterBand * poOverview,
void** ppDstBuffer,
GDALDataType* peDstBufferDataType,
const char * pszResampling,
int bHasNoData, float fNoDataValue,
GDALColorTable* poColorTable,
......@@ -2624,29 +2626,6 @@ typedef CPLErr (*GDALResampleFunction)
GDALResampleFunction GDALGetResampleFunction(const char* pszResampling,
int* pnRadius);
#ifdef GDAL_ENABLE_RESAMPLING_MULTIBAND
typedef CPLErr (*GDALResampleFunctionMultiBands)
( double dfXRatioDstToSrc,
double dfYRatioDstToSrc,
double dfSrcXDelta,
double dfSrcYDelta,
GDALDataType eWrkDataType,
void * pChunk, int nBands,
GByte * pabyChunkNodataMask,
int nChunkXOff, int nChunkXSize,
int nChunkYOff, int nChunkYSize,
int nDstXOff, int nDstXOff2,
int nDstYOff, int nDstYOff2,
GDALRasterBand ** papoDstBands,
const char * pszResampling,
int bHasNoData, float fNoDataValue,
GDALColorTable* poColorTable,
GDALDataType eSrcDataType);
GDALResampleFunctionMultiBands GDALGetResampleFunctionMultiBands(const char* pszResampling,
int* pnRadius);
#endif
GDALDataType GDALGetOvrWorkDataType(const char* pszResampling,
GDALDataType eSrcDataType);
......@@ -2714,7 +2693,6 @@ void GDALNullifyOpenDatasetsList();
CPLMutex** GDALGetphDMMutex();
CPLMutex** GDALGetphDLMutex();
void GDALNullifyProxyPoolSingleton();
GDALDriver* GDALGetAPIPROXYDriver();
void GDALSetResponsiblePIDForCurrentThread(GIntBig responsiblePID);
GIntBig GDALGetResponsiblePIDForCurrentThread();
......
/**********************************************************************
*
* Project: GDAL
* Purpose: Global thread pool
* Author: Even Rouault, <even dot rouault at spatialys dot com>
*
**********************************************************************
* Copyright (c) 2020, Even Rouault, <even dot rouault at spatialys dot com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#ifndef GDAL_THREAD_POOL_H
#define GDAL_THREAD_POOL_H
#include "cpl_worker_thread_pool.h"
CPLWorkerThreadPool* GDALGetGlobalThreadPool(int nThreads);
void GDALDestroyGlobalThreadPool();
#endif // GDAL_THREAD_POOL_H
......@@ -265,6 +265,7 @@ class GDALPansharpenOperation
size_t nBandValues,
T nMaxValue ) const;
// cppcheck-suppress functionStatic
CPLErr PansharpenChunk( GDALDataType eWorkDataType, GDALDataType eBufDataType,
const void* pPanBuffer,
const void* pUpsampledSpectralBuffer,
......
......@@ -288,6 +288,13 @@ GDALAutoCreateWarpedVRT( GDALDatasetH hSrcDS,
GDALResampleAlg eResampleAlg,
double dfMaxError, const GDALWarpOptions *psOptions );
GDALDatasetH CPL_DLL CPL_STDCALL
GDALAutoCreateWarpedVRTEx( GDALDatasetH hSrcDS,
const char *pszSrcWKT, const char *pszDstWKT,
GDALResampleAlg eResampleAlg,
double dfMaxError, const GDALWarpOptions *psOptions,
CSLConstList papszTransformerOptions );
GDALDatasetH CPL_DLL CPL_STDCALL
GDALCreateWarpedVRT( GDALDatasetH hSrcDS,
int nPixels, int nLines, double *padfGeoTransform,
......
......@@ -342,6 +342,8 @@ int CPL_DLL OGR_Fld_IsIgnored( OGRFieldDefnH hDefn );
void CPL_DLL OGR_Fld_SetIgnored( OGRFieldDefnH hDefn, int );
int CPL_DLL OGR_Fld_IsNullable( OGRFieldDefnH hDefn );
void CPL_DLL OGR_Fld_SetNullable( OGRFieldDefnH hDefn, int );
int CPL_DLL OGR_Fld_IsUnique( OGRFieldDefnH hDefn );
void CPL_DLL OGR_Fld_SetUnique( OGRFieldDefnH hDefn, int );
const char CPL_DLL *OGR_Fld_GetDefault( OGRFieldDefnH hDefn );
void CPL_DLL OGR_Fld_SetDefault( OGRFieldDefnH hDefn, const char* );
int CPL_DLL OGR_Fld_IsDefaultDriverSpecific( OGRFieldDefnH hDefn );
......
......@@ -573,10 +573,17 @@ typedef enum
*/
#define ALTER_DEFAULT_FLAG 0x10
/** Alter field UNIQUE constraint.
* Used by OGR_L_AlterFieldDefn().
* @since GDAL 3.2
*/
#define ALTER_UNIQUE_FLAG 0x20
/** Alter all parameters of field definition.
* Used by OGR_L_AlterFieldDefn().
*/
#define ALTER_ALL_FLAG (ALTER_NAME_FLAG | ALTER_TYPE_FLAG | ALTER_WIDTH_PRECISION_FLAG | ALTER_NULLABLE_FLAG | ALTER_DEFAULT_FLAG)
#define ALTER_ALL_FLAG (ALTER_NAME_FLAG | ALTER_TYPE_FLAG | ALTER_WIDTH_PRECISION_FLAG | ALTER_NULLABLE_FLAG | ALTER_DEFAULT_FLAG | ALTER_UNIQUE_FLAG)
/** Validate that fields respect not-null constraints.
* Used by OGR_F_Validate().
......
......@@ -35,6 +35,8 @@
#include "cpl_port.h"
#include <expat.h>
#include <memory>
/* Compatibility stuff for expat >= 1.95.0 and < 1.95.7 */
#ifndef XMLCALL
#define XMLCALL
......@@ -53,6 +55,20 @@
/* Only for internal use ! */
XML_Parser CPL_DLL OGRCreateExpatXMLParser(void);
//
//! @cond Doxygen_Suppress
struct CPL_DLL OGRExpatUniquePtrDeleter
{
void operator()(XML_Parser oParser) const
{ XML_ParserFree(oParser); }
};
//! @endcond
/** Unique pointer type for XML_Parser.
* @since GDAL 3.2
*/
using OGRExpatUniquePtr = std::unique_ptr<XML_ParserStruct, OGRExpatUniquePtrDeleter>;
#endif /* HAVE_EXPAT */
#endif /* OGR_EXPATH_INCLUDED */
......@@ -84,6 +84,7 @@ class OGRStyleTable;
* <li>a width (optional): maximal number of characters. See SetWidth() / GetWidth()</li>
* <li>a precision (optional): number of digits after decimal point. See SetPrecision() / GetPrecision()</li>
* <li>a NOT NULL constraint (optional). See SetNullable() / IsNullable()</li>
* <li>a UNIQUE constraint (optional). See SetUnique() / IsUnique()</li>
* <li>a default value (optional). See SetDefault() / GetDefault()</li>
* <li>a boolean to indicate whether it should be ignored when retrieving features. See SetIgnored() / IsIgnored()</li>
* </ul>
......@@ -103,6 +104,7 @@ class CPL_DLL OGRFieldDefn
OGRFieldSubType eSubType;
int bNullable;
int bUnique;
public:
OGRFieldDefn( const char *, OGRFieldType );
......@@ -144,6 +146,9 @@ class CPL_DLL OGRFieldDefn
int IsNullable() const { return bNullable; }
void SetNullable( int bNullableIn ) { bNullable = bNullableIn; }
int IsUnique() const { return bUnique; }
void SetUnique( int bUniqueIn ) { bUnique = bUniqueIn; }
int IsSame( const OGRFieldDefn * ) const;
/** Convert a OGRFieldDefn* to a OGRFieldDefnH.
......
......@@ -65,7 +65,7 @@ enum class OGRWktFormat
};
/// Options for formatting WKT output
struct OGRWktOptions
struct CPL_DLL OGRWktOptions
{
public:
/// Type of WKT output to produce.
......
......@@ -291,6 +291,55 @@ inline OGRLayer::FeatureIterator begin(OGRLayer* poLayer) { return poLayer->begi
*/
inline OGRLayer::FeatureIterator end(OGRLayer* poLayer) { return poLayer->end(); }
/** Unique pointer type for OGRLayer.
* @since GDAL 3.2
*/
using OGRLayerUniquePtr = std::unique_ptr<OGRLayer>;
/************************************************************************/
/* OGRGetNextFeatureThroughRaw */
/************************************************************************/
/** Template class offering a GetNextFeature() implementation relying on
* GetNextRawFeature()
*
* @since GDAL 3.2
*/
template<class BaseLayer> class OGRGetNextFeatureThroughRaw
{
public:
/** Implement OGRLayer::GetNextFeature(), relying on BaseLayer::GetNextRawFeature() */
OGRFeature* GetNextFeature()
{
const auto poThis = static_cast<BaseLayer*>(this);
while( true )
{
OGRFeature *poFeature = poThis->GetNextRawFeature();
if (poFeature == nullptr)
return nullptr;
if((poThis->m_poFilterGeom == nullptr
|| poThis->FilterGeometry( poFeature->GetGeometryRef() ) )
&& (poThis->m_poAttrQuery == nullptr
|| poThis->m_poAttrQuery->Evaluate( poFeature )) )
{
return poFeature;
}
else
delete poFeature;
}
}
};
/** Utility macro to define GetNextFeature() through GetNextRawFeature() */
#define DEFINE_GET_NEXT_FEATURE_THROUGH_RAW(BaseLayer) \
private: \
friend class OGRGetNextFeatureThroughRaw<BaseLayer>; \
public: \
OGRFeature* GetNextFeature() override { return OGRGetNextFeatureThroughRaw<BaseLayer>::GetNextFeature(); }
/************************************************************************/
/* OGRDataSource */
/************************************************************************/
......@@ -521,6 +570,7 @@ void CPL_DLL RegisterOGRGMLAS();
void CPL_DLL RegisterOGRMVT();
void CPL_DLL RegisterOGRNGW();
void CPL_DLL RegisterOGRMapML();
void CPL_DLL RegisterOGRLVBAG();
// @endcond
CPL_C_END
......
Metadata-Version: 2.1
Name: GDAL
Version: 3.1.0
Summary: GDAL: Geospatial Data Abstraction Library
Home-page: http://www.gdal.org
Author: Frank Warmerdam
Author-email: warmerdam@pobox.com
Maintainer: Howard Butler
Maintainer-email: hobu.inc@gmail.com
License: MIT
Description: b'\nGDAL/OGR in Python\n==================\n \nThis Python package and extensions are a number of tools for programming and \nmanipulating the GDAL_ Geospatial Data Abstraction Library. Actually, it is \ntwo libraries -- GDAL for manipulating geospatial raster data and OGR for \nmanipulating geospatial vector data -- but we\'ll refer to the entire package \nas the GDAL library for the purposes of this document.\n\nThe GDAL project (primarily Even Rouault) maintains SWIG generated Python \nbindings for GDAL and OGR. Generally speaking the classes and methods mostly \nmatch those of the GDAL and OGR C++ classes. There is no Python specific \nreference documentation, but the `GDAL API Tutorial`_ includes Python examples.\n\nDependencies\n------------\n \n * libgdal (3.1.0 or greater) and header files (gdal-devel)\n * numpy (1.0.0 or greater) and header files (numpy-devel) (not explicitly \n required, but many examples and utilities will not work without it)\n\nInstallation\n------------\n\nUnix\n~~~~~~~~~~~~~\n\nThe GDAL Python bindings support both distutils and setuptools, with a \npreference for using setuptools. If setuptools can be imported, setup will \nuse that to build an egg by default. If setuptools cannot be imported, a \nsimple distutils root install of the GDAL package (and no dependency \nchaining for numpy) will be made. \n\neasy_install\n~~~~~~~~~~~~\n\nGDAL can be installed from the Python CheeseShop::\n\n $ sudo easy_install GDAL\n\nIt may be necessary to have libgdal and its development headers installed \nif easy_install is expected to do a source build because no egg is available \nfor your specified platform and Python version.\n\nsetup.py\n~~~~~~~~~\n\nMost of setup.py\'s important variables are controlled with the setup.cfg \nfile. In setup.cfg, you can modify pointers to include files and libraries. \nThe most important option that will likely need to be modified is the \ngdal_config parameter. If you installed GDAL from a package, the location \nof this program is likely /usr/bin/gdal-config, but it may be in another place \ndepending on how your packager arranged things. \n\nAfter modifying the location of gdal-config, you can build and install \nwith the setup script::\n \n $ python setup.py build\n $ python setup.py install\n\nIf you have setuptools installed, you can also generate an egg::\n \n $ python setup.py bdist_egg\n\nBuilding as part of the GDAL library source tree\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can also have the GDAL Python bindings built as part of a source \nbuild by specifying --with-python as part of your configure line::\n\n $ ./configure --with-python\n\nUse the typical make and make install commands to complete the installation:: \n \n $ make\n $ make install\n\nA note about setuptools\n.......................\n\n./configure attempts to detect if you have setuptools installed in the tree \nof the Python binary it was given (or detected on the execution path), and it \nwill use an egg build by default in that instance. If you have a need to \nuse a distutils-only install, you will have to edit setup.py to ensure that \nthe HAVE_SETUPTOOLS variable is ultimately set to False and proceed with a \ntypical \'python setup.py install\' command.\n\nWindows\n~~~~~~~~~~~~\n\nYou will need the following items to complete an install of the GDAL Python\nbindings on Windows:\n\n* `GDAL Windows Binaries`_ Download the package that best matches your environment. \n\nAs explained in the README_EXE.txt file, after unzipping the GDAL binaries you \nwill need to modify your system path and variables. If you\'re not sure how to \ndo this, read the `Microsoft Knowledge Base doc`_ \n\n1. Add the installation directory bin folder to your system PATH, remember \n to put a semicolon in front of it before you add to the existing path.\n\n ::\n \n C:\\gdalwin32-1.7\\bin\n\n2. Create a new user or system variable with the data folder from \n your installation.\n\n ::\n \n Name : GDAL_DATA\n Path : C:\\gdalwin32-1.7\\data\n\nSkip down to the `Usage`_ section to test your install. Note, a reboot \nmay be required.\n\nSWIG\n----\n\nThe GDAL Python package is built using SWIG_. The earliest version of SWIG_ \nthat is supported to generate the wrapper code is 1.3.40. It is possible \nthat usable bindings will build with a version earlier than 1.3.40, but no \ndevelopment efforts are targeted at versions below it. You should not have \nto run SWIG in your development tree to generate the binding code, as it \nis usually included with the source. However, if you do need to regenerate, \nyou can do so with the following make command from within the ./swig/python\ndirectory::\n\n $ make generate\n\nTo ensure that all of the bindings are regenerated, you can clean the \nbindings code out before the generate command by issuing::\n\n $ make veryclean\n\nUsage\n-----\n\nImports\n~~~~~~~\n\nThere are five major modules that are included with the GDAL_ Python bindings.::\n\n >>> from osgeo import gdal\n >>> from osgeo import ogr\n >>> from osgeo import osr\n >>> from osgeo import gdal_array\n >>> from osgeo import gdalconst\n\nAdditionally, there are five compatibility modules that are included but \nprovide notices to state that they are deprecated and will be going away. \nIf you are using GDAL 1.7 bindings, you should update your imports to utilize \nthe usage above, but the following will work until at least GDAL 2.1. ::\n\n >>> import gdal\n >>> import ogr\n >>> import osr\n >>> import gdalnumeric\n >>> import gdalconst\n\nIf you have previous code that imported the global module and still need to \nsupport the old import, a simple try...except import can silence the \ndeprecation warning and keep things named essentially the same as before::\n\n >>> try:\n ... from osgeo import gdal\n ... except ImportError:\n ... import gdal\n\nDocstrings\n~~~~~~~~~~\n\nCurrently, only the OGR module has docstrings which are generated from the \nC/C++ API doxygen materials. Some of the arguments and types might not \nmatch up exactly with what you are seeing from Python, but they should be \nenough to get you going. Docstrings for GDAL and OSR are planned for a future \nrelease.\n\nNumpy/Numeric\n-------------\n\nOne advanced feature of the GDAL Python bindings not found in the other \nlanguage bindings (C#, Perl) is integration with the Python numerical array \nfacilities. The gdal.Dataset.ReadAsArray() method can be used to read raster \ndata as numerical arrays, ready to use with the Python numerical array \ncapabilities.\n\nThese facilities have evolved somewhat over time. In the past the package was \nknown as "Numeric" and imported using "import Numeric". A new generation is \nimported using "import numpy". Currently the old generation bindings only \nsupport the older Numeric package, and the new generation bindings only \nsupport the new generation numpy package. They are mostly compatible, and \nby importing gdalnumeric (or osgeo.gdal_array) you will get whichever is\nappropriate to the current bindings type.\n\nExamples\n~~~~~~~~\n\nOne example of GDAL/numpy integration is found in the `val_repl.py`_ script.\n\nPerformance Notes\n~~~~~~~~~~~~~~~~~\n\nReadAsArray expects to make an entire copy of a raster band or dataset unless \nthe data are explicitly subsetted as part of the function call. For large \ndata, this approach is expected to be prohibitively memory intensive.\n\n.. _GDAL API Tutorial: http://www.gdal.org/gdal_tutorial.html\n.. _GDAL Windows Binaries: http://gisinternals.com/sdk/\n.. _Microsoft Knowledge Base doc: http://support.microsoft.com/kb/310519\n.. _Python Cheeseshop: http://pypi.python.org/pypi/GDAL/\n.. _val_repl.py: http://trac.osgeo.org/gdal/browser/trunk/gdal/swig/python/samples/val_repl.py\n.. _GDAL: http://www.gdal.org\n.. _SWIG: http://www.swig.org\n'
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: C
Classifier: Programming Language :: C++
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Description-Content-Type: text/x-rst
Provides-Extra: numpy
README.rst
gdal.py
gdalconst.py
gdalnumeric.py
ogr.py
osr.py
setup.cfg
setup.py
GDAL.egg-info/PKG-INFO
GDAL.egg-info/SOURCES.txt
GDAL.egg-info/dependency_links.txt
GDAL.egg-info/not-zip-safe
GDAL.egg-info/requires.txt
GDAL.egg-info/top_level.txt
extensions/gdal_array_wrap.cpp
extensions/gdal_wrap.cpp
extensions/gdalconst_wrap.c
extensions/gnm_wrap.cpp
extensions/ogr_wrap.cpp
extensions/osr_wrap.cpp
osgeo/__init__.py
osgeo/gdal.py
osgeo/gdal_array.py
osgeo/gdalconst.py
osgeo/gdalnumeric.py
osgeo/gnm.py
osgeo/ogr.py
osgeo/osr.py
scripts/epsg_tr.py
scripts/esri2wkt.py
scripts/gcps2vec.py
scripts/gcps2wld.py
scripts/gdal2tiles.py
scripts/gdal2xyz.py
scripts/gdal_auth.py
scripts/gdal_calc.py
scripts/gdal_edit.py
scripts/gdal_fillnodata.py
scripts/gdal_merge.py
scripts/gdal_pansharpen.py
scripts/gdal_polygonize.py
scripts/gdal_proximity.py
scripts/gdal_retile.py
scripts/gdal_sieve.py
scripts/gdalchksum.py
scripts/gdalcompare.py
scripts/gdalident.py
scripts/gdalimport.py
scripts/gdalmove.py
scripts/mkgraticule.py
scripts/ogrmerge.py
scripts/pct2rgb.py
scripts/rgb2pct.py
\ No newline at end of file
# import osgeo.gdal as a convenience
from osgeo.gdal import deprecation_warn
deprecation_warn('gdal')
from osgeo.gdal import *
# import osgeo.gdalconst as a convenience
from osgeo.gdal import deprecation_warn
deprecation_warn('gdalconst')
from osgeo.gdalconst import *
# import osgeo.gdal_array as a convenience
from osgeo.gdal import deprecation_warn
deprecation_warn('gdalnumeric')
from osgeo.gdal_array import *
# import osgeo.ogr as a convenience
from osgeo.gdal import deprecation_warn
deprecation_warn('ogr')
from osgeo.ogr import *
# __init__ for osgeo package.
# making the osgeo package version the same as the gdal version:
from sys import platform, version_info
if version_info >= (3, 8, 0) and platform == 'win32':
import os
if 'USE_PATH_FOR_GDAL_PYTHON' in os.environ and 'PATH' in os.environ:
for p in os.environ['PATH'].split(';'):
if p:
os.add_dll_directory(p)
if version_info >= (2, 7, 0):
def swig_import_helper():
import importlib
from os.path import dirname, basename
mname = basename(dirname(__file__)) + '._gdal'
try:
return importlib.import_module(mname)
except ImportError as e:
if version_info >= (3, 8, 0) and platform == 'win32':
import os
if not 'USE_PATH_FOR_GDAL_PYTHON' in os.environ:
msg = 'On Windows, with Python >= 3.8, DLLs are no longer imported from the PATH.\n'
msg += 'If gdalXXX.dll is in the PATH, then set the USE_PATH_FOR_GDAL_PYTHON=YES environment variable\n'
msg += 'to feed the PATH into os.add_dll_directory().'
import sys
import traceback
traceback_string = ''.join(traceback.format_exception(*sys.exc_info()))
raise ImportError(traceback_string + '\n' + msg)
return importlib.import_module('_gdal')
_gdal = swig_import_helper()
del swig_import_helper
elif version_info >= (2, 6, 0):
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_gdal', [dirname(__file__)])
except ImportError:
import _gdal
return _gdal
if fp is not None:
try:
_mod = imp.load_module('_gdal', fp, pathname, description)
except ImportError as e:
if version_info >= (3, 8, 0) and platform == 'win32':
import os
if not 'USE_PATH_FOR_GDAL_PYTHON' in os.environ:
msg = 'On Windows, with Python >= 3.8, DLLs are no longer imported from the PATH.\n'
msg += 'If gdalXXX.dll is in the PATH, then set the USE_PATH_FOR_GDAL_PYTHON=YES environment variable\n'
msg += 'to feed the PATH into os.add_dll_directory().'
import sys
import traceback
traceback_string = ''.join(traceback.format_exception(*sys.exc_info()))
raise ImportError(traceback_string + '\n' + msg)
raise
finally:
fp.close()
return _mod
_gdal = swig_import_helper()
del swig_import_helper
else:
import _gdal
__version__ = _gdal.__version__ = _gdal.VersionInfo("RELEASE_NAME")
This diff is collapsed.
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
def swig_import_helper():
import importlib
pkg = __name__.rpartition('.')[0]
mname = '.'.join((pkg, '_gdalconst')).lstrip('.')
try:
return importlib.import_module(mname)
except ImportError:
return importlib.import_module('_gdalconst')
_gdalconst = swig_import_helper()
del swig_import_helper
elif _swig_python_version_info >= (2, 6, 0):
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_gdalconst', [dirname(__file__)])
except ImportError:
import _gdalconst
return _gdalconst
try:
_mod = imp.load_module('_gdalconst', fp, pathname, description)
finally:
if fp is not None:
fp.close()
return _mod
_gdalconst = swig_import_helper()
del swig_import_helper
else:
import _gdalconst
del _swig_python_version_info
try:
_swig_property = property
except NameError:
pass # Python < 2.2 doesn't have 'property'.
try:
import builtins as __builtin__
except ImportError:
import __builtin__
def _swig_setattr_nondynamic(self, class_type, name, value, static=1):
if (name == "thisown"):
return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'SwigPyObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name, None)
if method:
return method(self, value)
if (not static):
object.__setattr__(self, name, value)
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self, class_type, name, value):
return _swig_setattr_nondynamic(self, class_type, name, value, 0)
def _swig_getattr(self, class_type, name):
if (name == "thisown"):
return self.this.own()
method = class_type.__swig_getmethods__.get(name, None)
if method:
return method(self)
raise AttributeError("'%s' object has no attribute '%s'" % (class_type.__name__, name))
def _swig_repr(self):
try:
strthis = "proxy of " + self.this.__repr__()
except __builtin__.Exception:
strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
def _swig_setattr_nondynamic_method(set):
def set_attr(self, name, value):
if (name == "thisown"):
return self.this.own(value)
if hasattr(self, name) or (name == "this"):
set(self, name, value)
else:
raise AttributeError("You cannot add attributes to %s" % self)
return set_attr
GDT_Unknown = _gdalconst.GDT_Unknown
GDT_Byte = _gdalconst.GDT_Byte
GDT_UInt16 = _gdalconst.GDT_UInt16
GDT_Int16 = _gdalconst.GDT_Int16
GDT_UInt32 = _gdalconst.GDT_UInt32
GDT_Int32 = _gdalconst.GDT_Int32
GDT_Float32 = _gdalconst.GDT_Float32
GDT_Float64 = _gdalconst.GDT_Float64
GDT_CInt16 = _gdalconst.GDT_CInt16
GDT_CInt32 = _gdalconst.GDT_CInt32
GDT_CFloat32 = _gdalconst.GDT_CFloat32
GDT_CFloat64 = _gdalconst.GDT_CFloat64
GDT_TypeCount = _gdalconst.GDT_TypeCount
GA_ReadOnly = _gdalconst.GA_ReadOnly
GA_Update = _gdalconst.GA_Update
GF_Read = _gdalconst.GF_Read
GF_Write = _gdalconst.GF_Write
GRIORA_NearestNeighbour = _gdalconst.GRIORA_NearestNeighbour
GRIORA_Bilinear = _gdalconst.GRIORA_Bilinear
GRIORA_Cubic = _gdalconst.GRIORA_Cubic
GRIORA_CubicSpline = _gdalconst.GRIORA_CubicSpline
GRIORA_Lanczos = _gdalconst.GRIORA_Lanczos
GRIORA_Average = _gdalconst.GRIORA_Average
GRIORA_Mode = _gdalconst.GRIORA_Mode
GRIORA_Gauss = _gdalconst.GRIORA_Gauss
GCI_Undefined = _gdalconst.GCI_Undefined
GCI_GrayIndex = _gdalconst.GCI_GrayIndex
GCI_PaletteIndex = _gdalconst.GCI_PaletteIndex
GCI_RedBand = _gdalconst.GCI_RedBand
GCI_GreenBand = _gdalconst.GCI_GreenBand
GCI_BlueBand = _gdalconst.GCI_BlueBand
GCI_AlphaBand = _gdalconst.GCI_AlphaBand
GCI_HueBand = _gdalconst.GCI_HueBand
GCI_SaturationBand = _gdalconst.GCI_SaturationBand
GCI_LightnessBand = _gdalconst.GCI_LightnessBand
GCI_CyanBand = _gdalconst.GCI_CyanBand
GCI_MagentaBand = _gdalconst.GCI_MagentaBand
GCI_YellowBand = _gdalconst.GCI_YellowBand
GCI_BlackBand = _gdalconst.GCI_BlackBand
GCI_YCbCr_YBand = _gdalconst.GCI_YCbCr_YBand
GCI_YCbCr_CrBand = _gdalconst.GCI_YCbCr_CrBand
GCI_YCbCr_CbBand = _gdalconst.GCI_YCbCr_CbBand
GRA_NearestNeighbour = _gdalconst.GRA_NearestNeighbour
GRA_Bilinear = _gdalconst.GRA_Bilinear
GRA_Cubic = _gdalconst.GRA_Cubic
GRA_CubicSpline = _gdalconst.GRA_CubicSpline
GRA_Lanczos = _gdalconst.GRA_Lanczos
GRA_Average = _gdalconst.GRA_Average
GRA_Mode = _gdalconst.GRA_Mode
GRA_Max = _gdalconst.GRA_Max
GRA_Min = _gdalconst.GRA_Min
GRA_Med = _gdalconst.GRA_Med
GRA_Q1 = _gdalconst.GRA_Q1
GRA_Q3 = _gdalconst.GRA_Q3
GPI_Gray = _gdalconst.GPI_Gray
GPI_RGB = _gdalconst.GPI_RGB
GPI_CMYK = _gdalconst.GPI_CMYK
GPI_HLS = _gdalconst.GPI_HLS
CXT_Element = _gdalconst.CXT_Element
CXT_Text = _gdalconst.CXT_Text
CXT_Attribute = _gdalconst.CXT_Attribute
CXT_Comment = _gdalconst.CXT_Comment
CXT_Literal = _gdalconst.CXT_Literal
CE_None = _gdalconst.CE_None
CE_Debug = _gdalconst.CE_Debug
CE_Warning = _gdalconst.CE_Warning
CE_Failure = _gdalconst.CE_Failure
CE_Fatal = _gdalconst.CE_Fatal
CPLE_None = _gdalconst.CPLE_None
CPLE_AppDefined = _gdalconst.CPLE_AppDefined
CPLE_OutOfMemory = _gdalconst.CPLE_OutOfMemory
CPLE_FileIO = _gdalconst.CPLE_FileIO
CPLE_OpenFailed = _gdalconst.CPLE_OpenFailed
CPLE_IllegalArg = _gdalconst.CPLE_IllegalArg
CPLE_NotSupported = _gdalconst.CPLE_NotSupported
CPLE_AssertionFailed = _gdalconst.CPLE_AssertionFailed
CPLE_NoWriteAccess = _gdalconst.CPLE_NoWriteAccess
CPLE_UserInterrupt = _gdalconst.CPLE_UserInterrupt
CPLE_ObjectNull = _gdalconst.CPLE_ObjectNull
CPLE_HttpResponse = _gdalconst.CPLE_HttpResponse
CPLE_AWSBucketNotFound = _gdalconst.CPLE_AWSBucketNotFound
CPLE_AWSObjectNotFound = _gdalconst.CPLE_AWSObjectNotFound
CPLE_AWSAccessDenied = _gdalconst.CPLE_AWSAccessDenied
CPLE_AWSInvalidCredentials = _gdalconst.CPLE_AWSInvalidCredentials
CPLE_AWSSignatureDoesNotMatch = _gdalconst.CPLE_AWSSignatureDoesNotMatch
OF_ALL = _gdalconst.OF_ALL
OF_RASTER = _gdalconst.OF_RASTER
OF_VECTOR = _gdalconst.OF_VECTOR
OF_GNM = _gdalconst.OF_GNM
OF_MULTIDIM_RASTER = _gdalconst.OF_MULTIDIM_RASTER
OF_READONLY = _gdalconst.OF_READONLY
OF_UPDATE = _gdalconst.OF_UPDATE
OF_SHARED = _gdalconst.OF_SHARED
OF_VERBOSE_ERROR = _gdalconst.OF_VERBOSE_ERROR
DMD_LONGNAME = _gdalconst.DMD_LONGNAME
DMD_HELPTOPIC = _gdalconst.DMD_HELPTOPIC
DMD_MIMETYPE = _gdalconst.DMD_MIMETYPE
DMD_EXTENSION = _gdalconst.DMD_EXTENSION
DMD_EXTENSIONS = _gdalconst.DMD_EXTENSIONS
DMD_CONNECTION_PREFIX = _gdalconst.DMD_CONNECTION_PREFIX
DMD_CREATIONOPTIONLIST = _gdalconst.DMD_CREATIONOPTIONLIST
DMD_CREATIONDATATYPES = _gdalconst.DMD_CREATIONDATATYPES
DMD_CREATIONFIELDDATATYPES = _gdalconst.DMD_CREATIONFIELDDATATYPES
DMD_SUBDATASETS = _gdalconst.DMD_SUBDATASETS
DCAP_OPEN = _gdalconst.DCAP_OPEN
DCAP_CREATE = _gdalconst.DCAP_CREATE
DCAP_CREATECOPY = _gdalconst.DCAP_CREATECOPY
DCAP_VIRTUALIO = _gdalconst.DCAP_VIRTUALIO
DCAP_RASTER = _gdalconst.DCAP_RASTER
DCAP_VECTOR = _gdalconst.DCAP_VECTOR
DCAP_NOTNULL_FIELDS = _gdalconst.DCAP_NOTNULL_FIELDS
DCAP_DEFAULT_FIELDS = _gdalconst.DCAP_DEFAULT_FIELDS
DCAP_NOTNULL_GEOMFIELDS = _gdalconst.DCAP_NOTNULL_GEOMFIELDS
DIM_TYPE_HORIZONTAL_X = _gdalconst.DIM_TYPE_HORIZONTAL_X
DIM_TYPE_HORIZONTAL_Y = _gdalconst.DIM_TYPE_HORIZONTAL_Y
DIM_TYPE_VERTICAL = _gdalconst.DIM_TYPE_VERTICAL
DIM_TYPE_TEMPORAL = _gdalconst.DIM_TYPE_TEMPORAL
DIM_TYPE_PARAMETRIC = _gdalconst.DIM_TYPE_PARAMETRIC
CPLES_BackslashQuotable = _gdalconst.CPLES_BackslashQuotable
CPLES_XML = _gdalconst.CPLES_XML
CPLES_URL = _gdalconst.CPLES_URL
CPLES_SQL = _gdalconst.CPLES_SQL
CPLES_CSV = _gdalconst.CPLES_CSV
GFT_Integer = _gdalconst.GFT_Integer
GFT_Real = _gdalconst.GFT_Real
GFT_String = _gdalconst.GFT_String
GFU_Generic = _gdalconst.GFU_Generic
GFU_PixelCount = _gdalconst.GFU_PixelCount
GFU_Name = _gdalconst.GFU_Name
GFU_Min = _gdalconst.GFU_Min
GFU_Max = _gdalconst.GFU_Max
GFU_MinMax = _gdalconst.GFU_MinMax
GFU_Red = _gdalconst.GFU_Red
GFU_Green = _gdalconst.GFU_Green
GFU_Blue = _gdalconst.GFU_Blue
GFU_Alpha = _gdalconst.GFU_Alpha
GFU_RedMin = _gdalconst.GFU_RedMin
GFU_GreenMin = _gdalconst.GFU_GreenMin
GFU_BlueMin = _gdalconst.GFU_BlueMin
GFU_AlphaMin = _gdalconst.GFU_AlphaMin
GFU_RedMax = _gdalconst.GFU_RedMax
GFU_GreenMax = _gdalconst.GFU_GreenMax
GFU_BlueMax = _gdalconst.GFU_BlueMax
GFU_AlphaMax = _gdalconst.GFU_AlphaMax
GFU_MaxCount = _gdalconst.GFU_MaxCount
GRTT_THEMATIC = _gdalconst.GRTT_THEMATIC
GRTT_ATHEMATIC = _gdalconst.GRTT_ATHEMATIC
GMF_ALL_VALID = _gdalconst.GMF_ALL_VALID
GMF_PER_DATASET = _gdalconst.GMF_PER_DATASET
GMF_ALPHA = _gdalconst.GMF_ALPHA
GMF_NODATA = _gdalconst.GMF_NODATA
GDAL_DATA_COVERAGE_STATUS_UNIMPLEMENTED = _gdalconst.GDAL_DATA_COVERAGE_STATUS_UNIMPLEMENTED
GDAL_DATA_COVERAGE_STATUS_DATA = _gdalconst.GDAL_DATA_COVERAGE_STATUS_DATA
GDAL_DATA_COVERAGE_STATUS_EMPTY = _gdalconst.GDAL_DATA_COVERAGE_STATUS_EMPTY
GARIO_PENDING = _gdalconst.GARIO_PENDING
GARIO_UPDATE = _gdalconst.GARIO_UPDATE
GARIO_ERROR = _gdalconst.GARIO_ERROR
GARIO_COMPLETE = _gdalconst.GARIO_COMPLETE
GTO_TIP = _gdalconst.GTO_TIP
GTO_BIT = _gdalconst.GTO_BIT
GTO_BSQ = _gdalconst.GTO_BSQ
from numpy import *
from osgeo.gdal_array import *
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
# import osgeo.osr as a convenience
from osgeo.gdal import deprecation_warn
deprecation_warn('osr')
from osgeo.osr import *
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ******************************************************************************
# $Id$
#
# Project: CFS OGC MapServer
# Purpose: Script to create WKT and PROJ.4 dictionaries for EPSG GCS/PCS
# codes.
# Author: Frank Warmerdam, warmerdam@pobox.com
#
# ******************************************************************************
# Copyright (c) 2001, Frank Warmerdam
# Copyright (c) 2009-2010, 2019, Even Rouault <even dot rouault at spatialys.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# ******************************************************************************
import sys
from osgeo import osr
from osgeo import gdal
# =============================================================================
def Usage():
print('Usage: epsg_tr.py [-wkt] [-pretty_wkt] [-proj4] [-xml] [-postgis]')
print(' [-authority name]')
sys.exit(1)
# =============================================================================
def trHandleCode(set_srid, srs, auth_name, code, deprecated, output_format):
if output_format == '-pretty_wkt':
print('%s:%s' % (auth_name, str(code)))
print(srs.ExportToPrettyWkt())
if output_format == '-xml':
print(srs.ExportToXML())
if output_format == '-wkt':
print('EPSG:%d' % code)
print(srs.ExportToWkt())
if output_format == '-proj4':
out_string = srs.ExportToProj4()
name = srs.GetName()
print('# %s' % name)
if out_string.find('+proj=') > -1:
print('<%s> %s <>' % (str(code), out_string))
else:
print('# Unable to translate coordinate system '
'%s:%s into PROJ.4 format.' % (auth_name, str(code)))
print('#')
if output_format == '-postgis':
if code in set_srid:
if auth_name == 'ESRI':
if int(code) < 32767:
return
assert code not in set_srid, (auth_name, code)
set_srid.add(code)
name = srs.GetName()
if deprecated and 'deprecated' not in name:
name += " (deprecated)"
wkt = srs.ExportToWkt()
proj4text = srs.ExportToProj4()
print('---')
print('--- %s %s : %s' % (auth_name, str(code), name))
print('---')
if proj4text is None or len(proj4text) == 0:
print('-- (unable to translate to PROJ.4)')
else:
wkt = gdal.EscapeString(wkt, scheme=gdal.CPLES_SQL)
proj4text = gdal.EscapeString(proj4text, scheme=gdal.CPLES_SQL)
print('INSERT INTO "spatial_ref_sys" ("srid","auth_name","auth_srid","srtext","proj4text") VALUES (%d,\'%s\',%d,\'%s\',\'%s\');' %
(int(code), auth_name, int(code), wkt, proj4text))
# INGRES COPY command input.
if output_format == '-copy':
try:
wkt = srs.ExportToWkt()
proj4text = srs.ExportToProj4()
print('%s\t%d%s\t%s\t%d%s\t%d%s\n'
% (str(code), 4, auth_name, str(code), len(wkt), wkt,
len(proj4text), proj4text))
except:
pass
# =============================================================================
if __name__ == '__main__':
output_format = '-pretty_wkt'
authority = None
argv = gdal.GeneralCmdLineProcessor(sys.argv)
if argv is None:
sys.exit(0)
# Parse command line arguments.
i = 1
while i < len(argv):
arg = argv[i]
if arg == '-wkt' or arg == '-pretty_wkt' or arg == '-proj4' \
or arg == '-postgis' or arg == '-xml' or arg == '-copy':
output_format = arg
elif arg == '-authority':
i = i + 1
authority = argv[i]
elif arg[0] == '-':
Usage()
else:
Usage()
i = i + 1
# Output BEGIN transaction for PostGIS
if output_format == '-postgis':
print('BEGIN;')
# loop over all codes to generate output
if authority:
authorities = [ authority ]
elif output_format == '-postgis' :
authorities = [ 'EPSG', 'ESRI' ]
else:
authorities = [ 'EPSG', 'ESRI', 'IGNF' ]
set_srid = set()
for authority in authorities:
if authority in ('EPSG', 'ESRI'):
set_codes_geographic = set()
set_codes_geographic_3d = set()
set_codes_projected = set()
set_codes_geocentric = set()
set_codes_compound = set()
set_deprecated = set()
for crs_info in osr.GetCRSInfoListFromDatabase(authority):
code = int(crs_info.code)
if crs_info.type == osr.OSR_CRS_TYPE_COMPOUND:
set_codes_compound.add(code)
elif crs_info.type == osr.OSR_CRS_TYPE_GEOGRAPHIC_3D:
set_codes_geographic_3d.add(code)
elif crs_info.type == osr.OSR_CRS_TYPE_GEOGRAPHIC_2D:
set_codes_geographic.add(code)
elif crs_info.type == osr.OSR_CRS_TYPE_PROJECTED:
set_codes_projected.add(code)
elif crs_info.type == osr.OSR_CRS_TYPE_GEOCENTRIC:
set_codes_geocentric.add(code)
if crs_info.deprecated:
set_deprecated.add(code)
set_codes_geographic = sorted(set_codes_geographic)
set_codes_geographic_3d = sorted(set_codes_geographic_3d)
set_codes_projected = sorted(set_codes_projected)
set_codes_geocentric = sorted(set_codes_geocentric)
set_codes_compound = sorted(set_codes_compound)
for typestr, set_codes in (('Geographic 2D CRS', set_codes_geographic),
('Projected CRS', set_codes_projected),
('Geocentric CRS', set_codes_geocentric),
('Compound CRS', set_codes_compound),
('Geographic 3D CRS', set_codes_geographic_3d)):
if set_codes and output_format == '-postgis':
print('-' * 80)
print('--- ' + authority + ' ' + typestr)
print('-' * 80)
for code in set_codes:
srs = osr.SpatialReference()
srs.SetFromUserInput(authority + ':' + str(code))
deprecated = False
if code in set_deprecated:
deprecated = True
trHandleCode(set_srid, srs, authority, str(code), deprecated, output_format)
else:
for crs_info in osr.GetCRSInfoListFromDatabase(authority):
srs = osr.SpatialReference()
srs.SetFromUserInput(authority + ':' + crs_info.code)
trHandleCode(set_srid, srs, authority, crs_info.code, crs_info.deprecated, output_format)
# Output COMMIT transaction for PostGIS
if output_format == '-postgis':
print('COMMIT;')
print('VACUUM ANALYZE spatial_ref_sys;')
#!/usr/bin/env python3
# ******************************************************************************
# $Id$
#
# Project: GDAL
# Purpose: Simple command line program for translating ESRI .prj files
# into WKT.
# Author: Frank Warmerdam, warmerda@home.com
#
# ******************************************************************************
# Copyright (c) 2000, Frank Warmerdam
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# ******************************************************************************
import sys
from osgeo import osr
if len(sys.argv) < 2:
print('Usage: esri2wkt.py <esri .prj file>')
sys.exit(1)
prj_fd = open(sys.argv[1])
prj_lines = prj_fd.readlines()
prj_fd.close()
for i, prj_line in enumerate(prj_lines):
prj_lines[i] = prj_line.rstrip()
prj_srs = osr.SpatialReference()
err = prj_srs.ImportFromESRI(prj_lines)
if err != 0:
print('Error = %d' % err)
else:
print(prj_srs.ExportToPrettyWkt())
#!/usr/bin/env python3
# ******************************************************************************
# $Id$
#
# Project: GDAL
# Purpose: Convert GCPs to a point layer.
# Author: Frank Warmerdam, warmerdam@pobox.com
#
# ******************************************************************************
# Copyright (c) 2005, Frank Warmerdam <warmerdam@pobox.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# ******************************************************************************
import sys
from osgeo import gdal
from osgeo import ogr
from osgeo import osr
def Usage():
print('Usage: gcps2vec.py [-of <ogr_drivername>] [-p] <raster_file> <vector_file>')
sys.exit(1)
# =============================================================================
# Mainline
# =============================================================================
out_format = 'GML'
in_file = None
out_file = None
pixel_out = 0
gdal.AllRegister()
argv = gdal.GeneralCmdLineProcessor(sys.argv)
if argv is None:
sys.exit(0)
# Parse command line arguments.
i = 1
while i < len(argv):
arg = argv[i]
if arg == '-of':
i = i + 1
out_format = argv[i]
elif arg == '-p':
pixel_out = 1
elif in_file is None:
in_file = argv[i]
elif out_file is None:
out_file = argv[i]
else:
Usage()
i = i + 1
if out_file is None:
Usage()
# ----------------------------------------------------------------------------
# Open input file, and fetch GCPs.
# ----------------------------------------------------------------------------
ds = gdal.Open(in_file)
if ds is None:
print('Unable to open %s' % in_file)
sys.exit(1)
gcp_srs = ds.GetGCPProjection()
gcps = ds.GetGCPs()
ds = None
if gcps is None or not gcps:
print('No GCPs on file %s!' % in_file)
sys.exit(1)
# ----------------------------------------------------------------------------
# Create output file, and layer.
# ----------------------------------------------------------------------------
drv = ogr.GetDriverByName(out_format)
if drv is None:
print('No driver named %s available.' % out_format)
sys.exit(1)
ds = drv.CreateDataSource(out_file)
if pixel_out == 0 and gcp_srs != "":
srs = osr.SpatialReference()
srs.ImportFromWkt(gcp_srs)
else:
srs = None
if pixel_out == 0:
geom_type = ogr.wkbPoint25D
else:
geom_type = ogr.wkbPoint
layer = ds.CreateLayer('gcps', srs, geom_type=geom_type)
if pixel_out == 0:
fd = ogr.FieldDefn('Pixel', ogr.OFTReal)
layer.CreateField(fd)
fd = ogr.FieldDefn('Line', ogr.OFTReal)
layer.CreateField(fd)
else:
fd = ogr.FieldDefn('X', ogr.OFTReal)
layer.CreateField(fd)
fd = ogr.FieldDefn('Y', ogr.OFTReal)
layer.CreateField(fd)
fd = ogr.FieldDefn('Z', ogr.OFTReal)
layer.CreateField(fd)
fd = ogr.FieldDefn('Id', ogr.OFTString)
layer.CreateField(fd)
fd = ogr.FieldDefn('Info', ogr.OFTString)
layer.CreateField(fd)
# ----------------------------------------------------------------------------
# Write GCPs.
# ----------------------------------------------------------------------------
for gcp in gcps:
feat = ogr.Feature(layer.GetLayerDefn())
if pixel_out == 0:
geom = ogr.Geometry(geom_type)
feat.SetField('Pixel', gcp.GCPPixel)
feat.SetField('Line', gcp.GCPLine)
geom.SetPoint(0, gcp.GCPX, gcp.GCPY, gcp.GCPZ)
else:
geom = ogr.Geometry(geom_type)
feat.SetField('X', gcp.GCPX)
feat.SetField('Y', gcp.GCPY)
feat.SetField('Z', gcp.GCPZ)
geom.SetPoint(0, gcp.GCPPixel, gcp.GCPLine)
feat.SetField('Id', gcp.Id)
feat.SetField('Info', gcp.Info)
feat.SetGeometryDirectly(geom)
layer.CreateFeature(feat)
feat = None
ds.Destroy()
#!/usr/bin/env python3
# ******************************************************************************
# $Id$
#
# Name: gcps2wld
# Project: GDAL Python Interface
# Purpose: Translate the set of GCPs on a file into first order approximation
# in world file format.
# Author: Frank Warmerdam, warmerdam@pobox.com
#
# ******************************************************************************
# Copyright (c) 2002, Frank Warmerdam
# Copyright (c) 2009-2010, Even Rouault <even dot rouault at spatialys.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# ******************************************************************************
import sys
from osgeo import gdal
if len(sys.argv) < 2:
print("Usage: gcps2wld.py source_file")
sys.exit(1)
filename = sys.argv[1]
dataset = gdal.Open(filename)
if dataset is None:
print('Unable to open %s' % filename)
sys.exit(1)
gcps = dataset.GetGCPs()
if gcps is None or not gcps:
print('No GCPs found on file ' + filename)
sys.exit(1)
geotransform = gdal.GCPsToGeoTransform(gcps)
if geotransform is None:
print('Unable to extract a geotransform.')
sys.exit(1)
print(geotransform[1])
print(geotransform[4])
print(geotransform[2])
print(geotransform[5])
print(geotransform[0] + 0.5 * geotransform[1] + 0.5 * geotransform[2])
print(geotransform[3] + 0.5 * geotransform[4] + 0.5 * geotransform[5])
This diff is collapsed.
#!/usr/bin/env python3
###############################################################################
# $Id$
#
# Project: GDAL
# Purpose: Script to translate GDAL supported raster into XYZ ASCII
# point stream.
# Author: Frank Warmerdam, warmerdam@pobox.com
#
###############################################################################
# Copyright (c) 2002, Frank Warmerdam <warmerdam@pobox.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
###############################################################################
import sys
from osgeo import gdal
try:
import numpy as Numeric
except ImportError:
import Numeric
# =============================================================================
def Usage():
print('Usage: gdal2xyz.py [-skip factor] [-srcwin xoff yoff width height]')
print(' [-band b] [-csv] srcfile [dstfile]')
print('')
sys.exit(1)
# =============================================================================
#
# Program mainline.
#
if __name__ == '__main__':
srcwin = None
skip = 1
srcfile = None
dstfile = None
band_nums = []
delim = ' '
gdal.AllRegister()
argv = gdal.GeneralCmdLineProcessor(sys.argv)
if argv is None:
sys.exit(0)
# Parse command line arguments.
i = 1
while i < len(argv):
arg = argv[i]
if arg == '-srcwin':
srcwin = (int(argv[i + 1]), int(argv[i + 2]),
int(argv[i + 3]), int(argv[i + 4]))
i = i + 4
elif arg == '-skip':
skip = int(argv[i + 1])
i = i + 1
elif arg == '-band':
band_nums.append(int(argv[i + 1]))
i = i + 1
elif arg == '-csv':
delim = ','
elif arg[0] == '-':
Usage()
elif srcfile is None:
srcfile = arg
elif dstfile is None:
dstfile = arg
else:
Usage()
i = i + 1
if srcfile is None:
Usage()
if band_nums == []:
band_nums = [1]
# Open source file.
srcds = gdal.Open(srcfile)
if srcds is None:
print('Could not open %s.' % srcfile)
sys.exit(1)
bands = []
for band_num in band_nums:
band = srcds.GetRasterBand(band_num)
if band is None:
print('Could not get band %d' % band_num)
sys.exit(1)
bands.append(band)
gt = srcds.GetGeoTransform()
# Collect information on all the source files.
if srcwin is None:
srcwin = (0, 0, srcds.RasterXSize, srcds.RasterYSize)
# Open the output file.
if dstfile is not None:
dst_fh = open(dstfile, 'wt')
else:
dst_fh = sys.stdout
dt = srcds.GetRasterBand(1).DataType
if dt == gdal.GDT_Int32 or dt == gdal.GDT_UInt32:
band_format = (("%d" + delim) * len(bands)).rstrip(delim) + '\n'
else:
band_format = (("%g" + delim) * len(bands)).rstrip(delim) + '\n'
# Setup an appropriate print format.
if abs(gt[0]) < 180 and abs(gt[3]) < 180 \
and abs(srcds.RasterXSize * gt[1]) < 180 \
and abs(srcds.RasterYSize * gt[5]) < 180:
frmt = '%.10g' + delim + '%.10g' + delim + '%s'
else:
frmt = '%.3f' + delim + '%.3f' + delim + '%s'
# Loop emitting data.
for y in range(srcwin[1], srcwin[1] + srcwin[3], skip):
data = []
for band in bands:
band_data = band.ReadAsArray(srcwin[0], y, srcwin[2], 1)
band_data = Numeric.reshape(band_data, (srcwin[2],))
data.append(band_data)
for x_i in range(0, srcwin[2], skip):
x = x_i + srcwin[0]
geo_x = gt[0] + (x + 0.5) * gt[1] + (y + 0.5) * gt[2]
geo_y = gt[3] + (x + 0.5) * gt[4] + (y + 0.5) * gt[5]
x_i_data = []
for i in range(len(bands)):
x_i_data.append(data[i][x_i])
band_str = band_format % tuple(x_i_data)
line = frmt % (float(geo_x), float(geo_y), band_str)
dst_fh.write(line)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ******************************************************************************
# $Id$
#
# Project: GDAL
# Purpose: Application for Google web service authentication.
# Author: Frank Warmerdam, warmerdam@pobox.com
#
# ******************************************************************************
# Copyright (c) 2013, Frank Warmerdam <warmerdam@pobox.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# ******************************************************************************
import sys
import time
import webbrowser
from osgeo import gdal
SCOPES = {
'ft': 'https://www.googleapis.com/auth/fusiontables',
'storage': 'https://www.googleapis.com/auth/devstorage.read_only',
'storage-rw': 'https://www.googleapis.com/auth/devstorage.read_write'
}
# =============================================================================
# Usage()
# =============================================================================
def Usage():
print('')
print('Usage: gdal_auth_py [-s scope]')
print(' - interactive use.')
print('')
print('or:')
print('Usage: gdal_auth.py login [-s scope] ')
print('Usage: gdal_auth.py auth2refresh [-s scope] auth_token')
print('Usage: gdal_auth.py refresh2access [-s scope] refresh_token')
print('')
print('scopes: ft/storage/storage-rw/full_url')
print('')
sys.exit(1)
# =============================================================================
# Mainline
# =============================================================================
scope = SCOPES['ft']
token_in = None
command = None
argv = gdal.GeneralCmdLineProcessor(sys.argv)
if argv is None:
sys.exit(0)
# Parse command line arguments.
i = 1
while i < len(argv):
arg = argv[i]
if arg == '-s' and i < len(argv) - 1:
if argv[i + 1] in SCOPES:
scope = SCOPES[argv[i + 1]]
elif argv[i + 1].startswith('http'):
scope = argv[i + 1]
else:
print('Scope %s not recognised.' % argv[i + 1])
Usage()
sys.exit(1)
i = i + 1
elif arg[0] == '-':
Usage()
elif command is None:
command = arg
elif token_in is None:
token_in = arg
else:
Usage()
i = i + 1
if command is None:
command = 'interactive'
if command == 'login':
print(gdal.GOA2GetAuthorizationURL(scope))
elif command == 'auth2refresh':
print(gdal.GOA2GetRefreshToken(token_in, scope))
elif command == 'refresh2access':
print(gdal.GOA2GetAccessToken(token_in, scope))
elif command != 'interactive':
Usage()
else:
# Interactive case
print('Authorization requested for scope:')
print(scope)
print('')
print('Please login and authorize access in web browser...')
webbrowser.open(gdal.GOA2GetAuthorizationURL(scope))
time.sleep(2.0)
print('')
print('Enter authorization token:')
auth_token = sys.stdin.readline()
refresh_token = gdal.GOA2GetRefreshToken(auth_token, scope)
print('Refresh Token:' + refresh_token)
print('')
if scope == SCOPES['ft']:
print('Consider setting a configuration option like:')
print('GFT_REFRESH_TOKEN=' + refresh_token)
elif scope in (SCOPES['storage'], SCOPES['storage-rw']):
print('Consider setting a configuration option like:')
print('GS_OAUTH2_REFRESH_TOKEN=' + refresh_token)
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
#!/usr/bin/env python3
# ******************************************************************************
# $Id$
#
# Name: gdalimport
# Project: GDAL Python Interface
# Purpose: Import a GDAL supported file to Tiled GeoTIFF, and build overviews
# Author: Frank Warmerdam, warmerdam@pobox.com
#
# ******************************************************************************
# Copyright (c) 2000, Frank Warmerdam
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# ******************************************************************************
import os.path
import sys
from osgeo import gdal
gdal.AllRegister()
argv = gdal.GeneralCmdLineProcessor(sys.argv)
if argv is None:
sys.exit(0)
if len(argv) < 2:
print("Usage: gdalimport.py [--help-general] source_file [newfile]")
sys.exit(1)
def progress_cb(complete, message, cb_data):
print('%s %d' % (cb_data, complete))
filename = argv[1]
dataset = gdal.Open(filename)
if dataset is None:
print('Unable to open %s' % filename)
sys.exit(1)
geotiff = gdal.GetDriverByName("GTiff")
if geotiff is None:
print('GeoTIFF driver not registered.')
sys.exit(1)
if len(argv) < 3:
newbase, ext = os.path.splitext(os.path.basename(filename))
newfile = newbase + ".tif"
i = 0
while os.path.isfile(newfile):
i = i + 1
newfile = newbase + "_" + str(i) + ".tif"
else:
newfile = argv[2]
print('Importing to Tiled GeoTIFF file: %s' % newfile)
new_dataset = geotiff.CreateCopy(newfile, dataset, 0,
['TILED=YES', ],
callback=progress_cb,
callback_data='Translate: ')
dataset = None
print('Building overviews')
new_dataset.BuildOverviews("average", callback=progress_cb,
callback_data='Overviews: ')
new_dataset = None
print('Done')
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment