gdal.txt 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  1. ========
  2. GDAL API
  3. ========
  4. .. module:: django.contrib.gis.gdal
  5. :synopsis: GeoDjango's high-level interface to the GDAL library.
  6. `GDAL`__ stands for **Geospatial Data Abstraction Library**,
  7. and is a veritable "Swiss army knife" of GIS data functionality. A subset
  8. of GDAL is the `OGR`__ Simple Features Library, which specializes
  9. in reading and writing vector geographic data in a variety of standard
  10. formats.
  11. GeoDjango provides a high-level Python interface for some of the
  12. capabilities of OGR, including the reading and coordinate transformation
  13. of vector spatial data and minimal support for GDAL's features with respect
  14. to raster (image) data.
  15. .. note::
  16. Although the module is named ``gdal``, GeoDjango only supports some of the
  17. capabilities of OGR and GDAL's raster features at this time.
  18. __ https://www.gdal.org/
  19. __ https://gdal.org/user/vector_data_model.html
  20. Overview
  21. ========
  22. .. _gdal_sample_data:
  23. Sample Data
  24. -----------
  25. The GDAL/OGR tools described here are designed to help you read in
  26. your geospatial data, in order for most of them to be useful you have
  27. to have some data to work with. If you're starting out and don't yet
  28. have any data of your own to use, GeoDjango tests contain a number of
  29. data sets that you can use for testing. You can download them here::
  30. $ wget https://raw.githubusercontent.com/django/django/main/tests/gis_tests/data/cities/cities.{shp,prj,shx,dbf}
  31. $ wget https://raw.githubusercontent.com/django/django/main/tests/gis_tests/data/rasters/raster.tif
  32. Vector Data Source Objects
  33. ==========================
  34. ``DataSource``
  35. --------------
  36. :class:`DataSource` is a wrapper for the OGR data source object that
  37. supports reading data from a variety of OGR-supported geospatial file
  38. formats and data sources using a consistent interface. Each
  39. data source is represented by a :class:`DataSource` object which contains
  40. one or more layers of data. Each layer, represented by a :class:`Layer`
  41. object, contains some number of geographic features (:class:`Feature`),
  42. information about the type of features contained in that layer (e.g.
  43. points, polygons, etc.), as well as the names and types of any
  44. additional fields (:class:`Field`) of data that may be associated with
  45. each feature in that layer.
  46. .. class:: DataSource(ds_input, encoding='utf-8')
  47. The constructor for ``DataSource`` only requires one parameter: the path of
  48. the file you want to read. However, OGR also supports a variety of more
  49. complex data sources, including databases, that may be accessed by passing
  50. a special name string instead of a path. For more information, see the
  51. `OGR Vector Formats`__ documentation. The :attr:`name` property of a
  52. ``DataSource`` instance gives the OGR name of the underlying data source
  53. that it is using.
  54. The optional ``encoding`` parameter allows you to specify a non-standard
  55. encoding of the strings in the source. This is typically useful when you
  56. obtain ``DjangoUnicodeDecodeError`` exceptions while reading field values.
  57. Once you've created your ``DataSource``, you can find out how many layers
  58. of data it contains by accessing the :attr:`layer_count` property, or
  59. (equivalently) by using the ``len()`` function. For information on
  60. accessing the layers of data themselves, see the next section::
  61. >>> from django.contrib.gis.gdal import DataSource
  62. >>> ds = DataSource('/path/to/your/cities.shp')
  63. >>> ds.name
  64. '/path/to/your/cities.shp'
  65. >>> ds.layer_count # This file only contains one layer
  66. 1
  67. .. attribute:: layer_count
  68. Returns the number of layers in the data source.
  69. .. attribute:: name
  70. Returns the name of the data source.
  71. .. versionchanged:: 3.2
  72. Support for :class:`pathlib.Path` ``ds_input`` was added.
  73. __ https://gdal.org/drivers/vector/
  74. ``Layer``
  75. ---------
  76. .. class:: Layer
  77. ``Layer`` is a wrapper for a layer of data in a ``DataSource`` object. You
  78. never create a ``Layer`` object directly. Instead, you retrieve them from
  79. a :class:`DataSource` object, which is essentially a standard Python
  80. container of ``Layer`` objects. For example, you can access a specific
  81. layer by its index (e.g. ``ds[0]`` to access the first layer), or you can
  82. iterate over all the layers in the container in a ``for`` loop. The
  83. ``Layer`` itself acts as a container for geometric features.
  84. Typically, all the features in a given layer have the same geometry type.
  85. The :attr:`geom_type` property of a layer is an :class:`OGRGeomType` that
  86. identifies the feature type. We can use it to print out some basic
  87. information about each layer in a :class:`DataSource`::
  88. >>> for layer in ds:
  89. ... print('Layer "%s": %i %ss' % (layer.name, len(layer), layer.geom_type.name))
  90. ...
  91. Layer "cities": 3 Points
  92. The example output is from the cities data source, loaded above, which
  93. evidently contains one layer, called ``"cities"``, which contains three
  94. point features. For simplicity, the examples below assume that you've
  95. stored that layer in the variable ``layer``::
  96. >>> layer = ds[0]
  97. .. attribute:: name
  98. Returns the name of this layer in the data source.
  99. >>> layer.name
  100. 'cities'
  101. .. attribute:: num_feat
  102. Returns the number of features in the layer. Same as ``len(layer)``::
  103. >>> layer.num_feat
  104. 3
  105. .. attribute:: geom_type
  106. Returns the geometry type of the layer, as an :class:`OGRGeomType` object::
  107. >>> layer.geom_type.name
  108. 'Point'
  109. .. attribute:: num_fields
  110. Returns the number of fields in the layer, i.e the number of fields of
  111. data associated with each feature in the layer::
  112. >>> layer.num_fields
  113. 4
  114. .. attribute:: fields
  115. Returns a list of the names of each of the fields in this layer::
  116. >>> layer.fields
  117. ['Name', 'Population', 'Density', 'Created']
  118. .. attribute field_types
  119. Returns a list of the data types of each of the fields in this layer. These
  120. are subclasses of ``Field``, discussed below::
  121. >>> [ft.__name__ for ft in layer.field_types]
  122. ['OFTString', 'OFTReal', 'OFTReal', 'OFTDate']
  123. .. attribute:: field_widths
  124. Returns a list of the maximum field widths for each of the fields in this
  125. layer::
  126. >>> layer.field_widths
  127. [80, 11, 24, 10]
  128. .. attribute:: field_precisions
  129. Returns a list of the numeric precisions for each of the fields in this
  130. layer. This is meaningless (and set to zero) for non-numeric fields::
  131. >>> layer.field_precisions
  132. [0, 0, 15, 0]
  133. .. attribute:: extent
  134. Returns the spatial extent of this layer, as an :class:`Envelope` object::
  135. >>> layer.extent.tuple
  136. (-104.609252, 29.763374, -95.23506, 38.971823)
  137. .. attribute:: srs
  138. Property that returns the :class:`SpatialReference` associated with this
  139. layer::
  140. >>> print(layer.srs)
  141. GEOGCS["GCS_WGS_1984",
  142. DATUM["WGS_1984",
  143. SPHEROID["WGS_1984",6378137,298.257223563]],
  144. PRIMEM["Greenwich",0],
  145. UNIT["Degree",0.017453292519943295]]
  146. If the :class:`Layer` has no spatial reference information associated
  147. with it, ``None`` is returned.
  148. .. attribute:: spatial_filter
  149. Property that may be used to retrieve or set a spatial filter for this
  150. layer. A spatial filter can only be set with an :class:`OGRGeometry`
  151. instance, a 4-tuple extent, or ``None``. When set with something other than
  152. ``None``, only features that intersect the filter will be returned when
  153. iterating over the layer::
  154. >>> print(layer.spatial_filter)
  155. None
  156. >>> print(len(layer))
  157. 3
  158. >>> [feat.get('Name') for feat in layer]
  159. ['Pueblo', 'Lawrence', 'Houston']
  160. >>> ks_extent = (-102.051, 36.99, -94.59, 40.00) # Extent for state of Kansas
  161. >>> layer.spatial_filter = ks_extent
  162. >>> len(layer)
  163. 1
  164. >>> [feat.get('Name') for feat in layer]
  165. ['Lawrence']
  166. >>> layer.spatial_filter = None
  167. >>> len(layer)
  168. 3
  169. .. method:: get_fields()
  170. A method that returns a list of the values of a given field for each
  171. feature in the layer::
  172. >>> layer.get_fields('Name')
  173. ['Pueblo', 'Lawrence', 'Houston']
  174. .. method:: get_geoms(geos=False)
  175. A method that returns a list containing the geometry of each feature in the
  176. layer. If the optional argument ``geos`` is set to ``True`` then the
  177. geometries are converted to :class:`~django.contrib.gis.geos.GEOSGeometry`
  178. objects. Otherwise, they are returned as :class:`OGRGeometry` objects::
  179. >>> [pt.tuple for pt in layer.get_geoms()]
  180. [(-104.609252, 38.255001), (-95.23506, 38.971823), (-95.363151, 29.763374)]
  181. .. method:: test_capability(capability)
  182. Returns a boolean indicating whether this layer supports the given
  183. capability (a string). Examples of valid capability strings include:
  184. ``'RandomRead'``, ``'SequentialWrite'``, ``'RandomWrite'``,
  185. ``'FastSpatialFilter'``, ``'FastFeatureCount'``, ``'FastGetExtent'``,
  186. ``'CreateField'``, ``'Transactions'``, ``'DeleteFeature'``, and
  187. ``'FastSetNextByIndex'``.
  188. ``Feature``
  189. -----------
  190. .. class:: Feature
  191. ``Feature`` wraps an OGR feature. You never create a ``Feature`` object
  192. directly. Instead, you retrieve them from a :class:`Layer` object. Each
  193. feature consists of a geometry and a set of fields containing additional
  194. properties. The geometry of a field is accessible via its ``geom`` property,
  195. which returns an :class:`OGRGeometry` object. A ``Feature`` behaves like a
  196. standard Python container for its fields, which it returns as :class:`Field`
  197. objects: you can access a field directly by its index or name, or you can
  198. iterate over a feature's fields, e.g. in a ``for`` loop.
  199. .. attribute:: geom
  200. Returns the geometry for this feature, as an ``OGRGeometry`` object::
  201. >>> city.geom.tuple
  202. (-104.609252, 38.255001)
  203. .. attribute:: get
  204. A method that returns the value of the given field (specified by name)
  205. for this feature, **not** a ``Field`` wrapper object::
  206. >>> city.get('Population')
  207. 102121
  208. .. attribute:: geom_type
  209. Returns the type of geometry for this feature, as an :class:`OGRGeomType`
  210. object. This will be the same for all features in a given layer and is
  211. equivalent to the :attr:`Layer.geom_type` property of the :class:`Layer`
  212. object the feature came from.
  213. .. attribute:: num_fields
  214. Returns the number of fields of data associated with the feature. This will
  215. be the same for all features in a given layer and is equivalent to the
  216. :attr:`Layer.num_fields` property of the :class:`Layer` object the feature
  217. came from.
  218. .. attribute:: fields
  219. Returns a list of the names of the fields of data associated with the
  220. feature. This will be the same for all features in a given layer and is
  221. equivalent to the :attr:`Layer.fields` property of the :class:`Layer`
  222. object the feature came from.
  223. .. attribute:: fid
  224. Returns the feature identifier within the layer::
  225. >>> city.fid
  226. 0
  227. .. attribute:: layer_name
  228. Returns the name of the :class:`Layer` that the feature came from. This
  229. will be the same for all features in a given layer::
  230. >>> city.layer_name
  231. 'cities'
  232. .. attribute:: index
  233. A method that returns the index of the given field name. This will be the
  234. same for all features in a given layer::
  235. >>> city.index('Population')
  236. 1
  237. ``Field``
  238. ---------
  239. .. class:: Field
  240. .. attribute:: name
  241. Returns the name of this field::
  242. >>> city['Name'].name
  243. 'Name'
  244. .. attribute:: type
  245. Returns the OGR type of this field, as an integer. The ``FIELD_CLASSES``
  246. dictionary maps these values onto subclasses of ``Field``::
  247. >>> city['Density'].type
  248. 2
  249. .. attribute:: type_name
  250. Returns a string with the name of the data type of this field::
  251. >>> city['Name'].type_name
  252. 'String'
  253. .. attribute:: value
  254. Returns the value of this field. The ``Field`` class itself returns the
  255. value as a string, but each subclass returns the value in the most
  256. appropriate form::
  257. >>> city['Population'].value
  258. 102121
  259. .. attribute:: width
  260. Returns the width of this field::
  261. >>> city['Name'].width
  262. 80
  263. .. attribute:: precision
  264. Returns the numeric precision of this field. This is meaningless (and set
  265. to zero) for non-numeric fields::
  266. >>> city['Density'].precision
  267. 15
  268. .. method:: as_double()
  269. Returns the value of the field as a double (float)::
  270. >>> city['Density'].as_double()
  271. 874.7
  272. .. method:: as_int()
  273. Returns the value of the field as an integer::
  274. >>> city['Population'].as_int()
  275. 102121
  276. .. method:: as_string()
  277. Returns the value of the field as a string::
  278. >>> city['Name'].as_string()
  279. 'Pueblo'
  280. .. method:: as_datetime()
  281. Returns the value of the field as a tuple of date and time components::
  282. >>> city['Created'].as_datetime()
  283. (c_long(1999), c_long(5), c_long(23), c_long(0), c_long(0), c_long(0), c_long(0))
  284. ``Driver``
  285. ----------
  286. .. class:: Driver(dr_input)
  287. The ``Driver`` class is used internally to wrap an OGR :class:`DataSource`
  288. driver.
  289. .. attribute:: driver_count
  290. Returns the number of OGR vector drivers currently registered.
  291. OGR Geometries
  292. ==============
  293. ``OGRGeometry``
  294. ---------------
  295. :class:`OGRGeometry` objects share similar functionality with
  296. :class:`~django.contrib.gis.geos.GEOSGeometry` objects and are thin wrappers
  297. around OGR's internal geometry representation. Thus, they allow for more
  298. efficient access to data when using :class:`DataSource`. Unlike its GEOS
  299. counterpart, :class:`OGRGeometry` supports spatial reference systems and
  300. coordinate transformation::
  301. >>> from django.contrib.gis.gdal import OGRGeometry
  302. >>> polygon = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5))')
  303. .. class:: OGRGeometry(geom_input, srs=None)
  304. This object is a wrapper for the `OGR Geometry`__ class. These objects are
  305. instantiated directly from the given ``geom_input`` parameter, which may be
  306. a string containing WKT, HEX, GeoJSON, a ``buffer`` containing WKB data, or
  307. an :class:`OGRGeomType` object. These objects are also returned from the
  308. :class:`Feature.geom` attribute, when reading vector data from
  309. :class:`Layer` (which is in turn a part of a :class:`DataSource`).
  310. __ https://gdal.org/api/ogrgeometry_cpp.html#ogrgeometry-class
  311. .. classmethod:: from_gml(gml_string)
  312. Constructs an :class:`OGRGeometry` from the given GML string.
  313. .. classmethod:: from_bbox(bbox)
  314. Constructs a :class:`Polygon` from the given bounding-box (a 4-tuple).
  315. .. method:: __len__()
  316. Returns the number of points in a :class:`LineString`, the number of rings
  317. in a :class:`Polygon`, or the number of geometries in a
  318. :class:`GeometryCollection`. Not applicable to other geometry types.
  319. .. method:: __iter__()
  320. Iterates over the points in a :class:`LineString`, the rings in a
  321. :class:`Polygon`, or the geometries in a :class:`GeometryCollection`.
  322. Not applicable to other geometry types.
  323. .. method:: __getitem__()
  324. Returns the point at the specified index for a :class:`LineString`, the
  325. interior ring at the specified index for a :class:`Polygon`, or the geometry
  326. at the specified index in a :class:`GeometryCollection`. Not applicable to
  327. other geometry types.
  328. .. attribute:: dimension
  329. Returns the number of coordinated dimensions of the geometry, i.e. 0
  330. for points, 1 for lines, and so forth::
  331. >> polygon.dimension
  332. 2
  333. .. attribute:: coord_dim
  334. Returns or sets the coordinate dimension of this geometry. For example, the
  335. value would be 2 for two-dimensional geometries.
  336. .. attribute:: geom_count
  337. Returns the number of elements in this geometry::
  338. >>> polygon.geom_count
  339. 1
  340. .. attribute:: point_count
  341. Returns the number of points used to describe this geometry::
  342. >>> polygon.point_count
  343. 4
  344. .. attribute:: num_points
  345. Alias for :attr:`point_count`.
  346. .. attribute:: num_coords
  347. Alias for :attr:`point_count`.
  348. .. attribute:: geom_type
  349. Returns the type of this geometry, as an :class:`OGRGeomType` object.
  350. .. attribute:: geom_name
  351. Returns the name of the type of this geometry::
  352. >>> polygon.geom_name
  353. 'POLYGON'
  354. .. attribute:: area
  355. Returns the area of this geometry, or 0 for geometries that do not contain
  356. an area::
  357. >>> polygon.area
  358. 25.0
  359. .. attribute:: envelope
  360. Returns the envelope of this geometry, as an :class:`Envelope` object.
  361. .. attribute:: extent
  362. Returns the envelope of this geometry as a 4-tuple, instead of as an
  363. :class:`Envelope` object::
  364. >>> point.extent
  365. (0.0, 0.0, 5.0, 5.0)
  366. .. attribute:: srs
  367. This property controls the spatial reference for this geometry, or
  368. ``None`` if no spatial reference system has been assigned to it.
  369. If assigned, accessing this property returns a :class:`SpatialReference`
  370. object. It may be set with another :class:`SpatialReference` object,
  371. or any input that :class:`SpatialReference` accepts. Example::
  372. >>> city.geom.srs.name
  373. 'GCS_WGS_1984'
  374. .. attribute:: srid
  375. Returns or sets the spatial reference identifier corresponding to
  376. :class:`SpatialReference` of this geometry. Returns ``None`` if
  377. there is no spatial reference information associated with this
  378. geometry, or if an SRID cannot be determined.
  379. .. attribute:: geos
  380. Returns a :class:`~django.contrib.gis.geos.GEOSGeometry` object
  381. corresponding to this geometry.
  382. .. attribute:: gml
  383. Returns a string representation of this geometry in GML format::
  384. >>> OGRGeometry('POINT(1 2)').gml
  385. '<gml:Point><gml:coordinates>1,2</gml:coordinates></gml:Point>'
  386. .. attribute:: hex
  387. Returns a string representation of this geometry in HEX WKB format::
  388. >>> OGRGeometry('POINT(1 2)').hex
  389. '0101000000000000000000F03F0000000000000040'
  390. .. attribute:: json
  391. Returns a string representation of this geometry in JSON format::
  392. >>> OGRGeometry('POINT(1 2)').json
  393. '{ "type": "Point", "coordinates": [ 1.000000, 2.000000 ] }'
  394. .. attribute:: kml
  395. Returns a string representation of this geometry in KML format.
  396. .. attribute:: wkb_size
  397. Returns the size of the WKB buffer needed to hold a WKB representation
  398. of this geometry::
  399. >>> OGRGeometry('POINT(1 2)').wkb_size
  400. 21
  401. .. attribute:: wkb
  402. Returns a ``buffer`` containing a WKB representation of this geometry.
  403. .. attribute:: wkt
  404. Returns a string representation of this geometry in WKT format.
  405. .. attribute:: ewkt
  406. Returns the EWKT representation of this geometry.
  407. .. method:: clone()
  408. Returns a new :class:`OGRGeometry` clone of this geometry object.
  409. .. method:: close_rings()
  410. If there are any rings within this geometry that have not been closed,
  411. this routine will do so by adding the starting point to the end::
  412. >>> triangle = OGRGeometry('LINEARRING (0 0,0 1,1 0)')
  413. >>> triangle.close_rings()
  414. >>> triangle.wkt
  415. 'LINEARRING (0 0,0 1,1 0,0 0)'
  416. .. method:: transform(coord_trans, clone=False)
  417. Transforms this geometry to a different spatial reference system. May take
  418. a :class:`CoordTransform` object, a :class:`SpatialReference` object, or
  419. any other input accepted by :class:`SpatialReference` (including spatial
  420. reference WKT and PROJ strings, or an integer SRID).
  421. By default nothing is returned and the geometry is transformed in-place.
  422. However, if the ``clone`` keyword is set to ``True`` then a transformed
  423. clone of this geometry is returned instead.
  424. .. method:: intersects(other)
  425. Returns ``True`` if this geometry intersects the other, otherwise returns
  426. ``False``.
  427. .. method:: equals(other)
  428. Returns ``True`` if this geometry is equivalent to the other, otherwise
  429. returns ``False``.
  430. .. method:: disjoint(other)
  431. Returns ``True`` if this geometry is spatially disjoint to (i.e. does
  432. not intersect) the other, otherwise returns ``False``.
  433. .. method:: touches(other)
  434. Returns ``True`` if this geometry touches the other, otherwise returns
  435. ``False``.
  436. .. method:: crosses(other)
  437. Returns ``True`` if this geometry crosses the other, otherwise returns
  438. ``False``.
  439. .. method:: within(other)
  440. Returns ``True`` if this geometry is contained within the other, otherwise
  441. returns ``False``.
  442. .. method:: contains(other)
  443. Returns ``True`` if this geometry contains the other, otherwise returns
  444. ``False``.
  445. .. method:: overlaps(other)
  446. Returns ``True`` if this geometry overlaps the other, otherwise returns
  447. ``False``.
  448. .. method:: boundary()
  449. The boundary of this geometry, as a new :class:`OGRGeometry` object.
  450. .. attribute:: convex_hull
  451. The smallest convex polygon that contains this geometry, as a new
  452. :class:`OGRGeometry` object.
  453. .. method:: difference()
  454. Returns the region consisting of the difference of this geometry and
  455. the other, as a new :class:`OGRGeometry` object.
  456. .. method:: intersection()
  457. Returns the region consisting of the intersection of this geometry and
  458. the other, as a new :class:`OGRGeometry` object.
  459. .. method:: sym_difference()
  460. Returns the region consisting of the symmetric difference of this
  461. geometry and the other, as a new :class:`OGRGeometry` object.
  462. .. method:: union()
  463. Returns the region consisting of the union of this geometry and
  464. the other, as a new :class:`OGRGeometry` object.
  465. .. attribute:: tuple
  466. Returns the coordinates of a point geometry as a tuple, the
  467. coordinates of a line geometry as a tuple of tuples, and so forth::
  468. >>> OGRGeometry('POINT (1 2)').tuple
  469. (1.0, 2.0)
  470. >>> OGRGeometry('LINESTRING (1 2,3 4)').tuple
  471. ((1.0, 2.0), (3.0, 4.0))
  472. .. attribute:: coords
  473. An alias for :attr:`tuple`.
  474. .. class:: Point
  475. .. attribute:: x
  476. Returns the X coordinate of this point::
  477. >>> OGRGeometry('POINT (1 2)').x
  478. 1.0
  479. .. attribute:: y
  480. Returns the Y coordinate of this point::
  481. >>> OGRGeometry('POINT (1 2)').y
  482. 2.0
  483. .. attribute:: z
  484. Returns the Z coordinate of this point, or ``None`` if the point does not
  485. have a Z coordinate::
  486. >>> OGRGeometry('POINT (1 2 3)').z
  487. 3.0
  488. .. class:: LineString
  489. .. attribute:: x
  490. Returns a list of X coordinates in this line::
  491. >>> OGRGeometry('LINESTRING (1 2,3 4)').x
  492. [1.0, 3.0]
  493. .. attribute:: y
  494. Returns a list of Y coordinates in this line::
  495. >>> OGRGeometry('LINESTRING (1 2,3 4)').y
  496. [2.0, 4.0]
  497. .. attribute:: z
  498. Returns a list of Z coordinates in this line, or ``None`` if the line does
  499. not have Z coordinates::
  500. >>> OGRGeometry('LINESTRING (1 2 3,4 5 6)').z
  501. [3.0, 6.0]
  502. .. class:: Polygon
  503. .. attribute:: shell
  504. Returns the shell or exterior ring of this polygon, as a ``LinearRing``
  505. geometry.
  506. .. attribute:: exterior_ring
  507. An alias for :attr:`shell`.
  508. .. attribute:: centroid
  509. Returns a :class:`Point` representing the centroid of this polygon.
  510. .. class:: GeometryCollection
  511. .. method:: add(geom)
  512. Adds a geometry to this geometry collection. Not applicable to other
  513. geometry types.
  514. ``OGRGeomType``
  515. ---------------
  516. .. class:: OGRGeomType(type_input)
  517. This class allows for the representation of an OGR geometry type
  518. in any of several ways::
  519. >>> from django.contrib.gis.gdal import OGRGeomType
  520. >>> gt1 = OGRGeomType(3) # Using an integer for the type
  521. >>> gt2 = OGRGeomType('Polygon') # Using a string
  522. >>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive
  523. >>> print(gt1 == 3, gt1 == 'Polygon') # Equivalence works w/non-OGRGeomType objects
  524. True True
  525. .. attribute:: name
  526. Returns a short-hand string form of the OGR Geometry type::
  527. >>> gt1.name
  528. 'Polygon'
  529. .. attribute:: num
  530. Returns the number corresponding to the OGR geometry type::
  531. >>> gt1.num
  532. 3
  533. .. attribute:: django
  534. Returns the Django field type (a subclass of GeometryField) to use for
  535. storing this OGR type, or ``None`` if there is no appropriate Django type::
  536. >>> gt1.django
  537. 'PolygonField'
  538. ``Envelope``
  539. ------------
  540. .. class:: Envelope(*args)
  541. Represents an OGR Envelope structure that contains the minimum and maximum
  542. X, Y coordinates for a rectangle bounding box. The naming of the variables
  543. is compatible with the OGR Envelope C structure.
  544. .. attribute:: min_x
  545. The value of the minimum X coordinate.
  546. .. attribute:: min_y
  547. The value of the maximum X coordinate.
  548. .. attribute:: max_x
  549. The value of the minimum Y coordinate.
  550. .. attribute:: max_y
  551. The value of the maximum Y coordinate.
  552. .. attribute:: ur
  553. The upper-right coordinate, as a tuple.
  554. .. attribute:: ll
  555. The lower-left coordinate, as a tuple.
  556. .. attribute:: tuple
  557. A tuple representing the envelope.
  558. .. attribute:: wkt
  559. A string representing this envelope as a polygon in WKT format.
  560. .. method:: expand_to_include(*args)
  561. Coordinate System Objects
  562. =========================
  563. ``SpatialReference``
  564. --------------------
  565. .. class:: SpatialReference(srs_input)
  566. Spatial reference objects are initialized on the given ``srs_input``,
  567. which may be one of the following:
  568. * OGC Well Known Text (WKT) (a string)
  569. * EPSG code (integer or string)
  570. * PROJ string
  571. * A shorthand string for well-known standards (``'WGS84'``, ``'WGS72'``,
  572. ``'NAD27'``, ``'NAD83'``)
  573. Example::
  574. >>> wgs84 = SpatialReference('WGS84') # shorthand string
  575. >>> wgs84 = SpatialReference(4326) # EPSG code
  576. >>> wgs84 = SpatialReference('EPSG:4326') # EPSG string
  577. >>> proj = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs '
  578. >>> wgs84 = SpatialReference(proj) # PROJ string
  579. >>> wgs84 = SpatialReference("""GEOGCS["WGS 84",
  580. DATUM["WGS_1984",
  581. SPHEROID["WGS 84",6378137,298.257223563,
  582. AUTHORITY["EPSG","7030"]],
  583. AUTHORITY["EPSG","6326"]],
  584. PRIMEM["Greenwich",0,
  585. AUTHORITY["EPSG","8901"]],
  586. UNIT["degree",0.01745329251994328,
  587. AUTHORITY["EPSG","9122"]],
  588. AUTHORITY["EPSG","4326"]]""") # OGC WKT
  589. .. method:: __getitem__(target)
  590. Returns the value of the given string attribute node, ``None`` if the node
  591. doesn't exist. Can also take a tuple as a parameter, (target, child), where
  592. child is the index of the attribute in the WKT. For example::
  593. >>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]')
  594. >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326
  595. >>> print(srs['GEOGCS'])
  596. WGS 84
  597. >>> print(srs['DATUM'])
  598. WGS_1984
  599. >>> print(srs['AUTHORITY'])
  600. EPSG
  601. >>> print(srs['AUTHORITY', 1]) # The authority value
  602. 4326
  603. >>> print(srs['TOWGS84', 4]) # the fourth value in this wkt
  604. 0
  605. >>> print(srs['UNIT|AUTHORITY']) # For the units authority, have to use the pipe symbol.
  606. EPSG
  607. >>> print(srs['UNIT|AUTHORITY', 1]) # The authority value for the units
  608. 9122
  609. .. method:: attr_value(target, index=0)
  610. The attribute value for the given target node (e.g. ``'PROJCS'``).
  611. The index keyword specifies an index of the child node to return.
  612. .. method:: auth_name(target)
  613. Returns the authority name for the given string target node.
  614. .. method:: auth_code(target)
  615. Returns the authority code for the given string target node.
  616. .. method:: clone()
  617. Returns a clone of this spatial reference object.
  618. .. method:: identify_epsg()
  619. This method inspects the WKT of this ``SpatialReference`` and will add EPSG
  620. authority nodes where an EPSG identifier is applicable.
  621. .. method:: from_esri()
  622. Morphs this SpatialReference from ESRI's format to EPSG
  623. .. method:: to_esri()
  624. Morphs this SpatialReference to ESRI's format.
  625. .. method:: validate()
  626. Checks to see if the given spatial reference is valid, if not
  627. an exception will be raised.
  628. .. method:: import_epsg(epsg)
  629. Import spatial reference from EPSG code.
  630. .. method:: import_proj(proj)
  631. Import spatial reference from PROJ string.
  632. .. method:: import_user_input(user_input)
  633. .. method:: import_wkt(wkt)
  634. Import spatial reference from WKT.
  635. .. method:: import_xml(xml)
  636. Import spatial reference from XML.
  637. .. attribute:: name
  638. Returns the name of this Spatial Reference.
  639. .. attribute:: srid
  640. Returns the SRID of top-level authority, or ``None`` if undefined.
  641. .. attribute:: linear_name
  642. Returns the name of the linear units.
  643. .. attribute:: linear_units
  644. Returns the value of the linear units.
  645. .. attribute:: angular_name
  646. Returns the name of the angular units."
  647. .. attribute:: angular_units
  648. Returns the value of the angular units.
  649. .. attribute:: units
  650. Returns a 2-tuple of the units value and the units name and will
  651. automatically determines whether to return the linear or angular units.
  652. .. attribute:: ellipsoid
  653. Returns a tuple of the ellipsoid parameters for this spatial reference:
  654. (semimajor axis, semiminor axis, and inverse flattening).
  655. .. attribute:: semi_major
  656. Returns the semi major axis of the ellipsoid for this spatial reference.
  657. .. attribute:: semi_minor
  658. Returns the semi minor axis of the ellipsoid for this spatial reference.
  659. .. attribute:: inverse_flattening
  660. Returns the inverse flattening of the ellipsoid for this spatial reference.
  661. .. attribute:: geographic
  662. Returns ``True`` if this spatial reference is geographic (root node is
  663. ``GEOGCS``).
  664. .. attribute:: local
  665. Returns ``True`` if this spatial reference is local (root node is
  666. ``LOCAL_CS``).
  667. .. attribute:: projected
  668. Returns ``True`` if this spatial reference is a projected coordinate system
  669. (root node is ``PROJCS``).
  670. .. attribute:: wkt
  671. Returns the WKT representation of this spatial reference.
  672. .. attribute:: pretty_wkt
  673. Returns the 'pretty' representation of the WKT.
  674. .. attribute:: proj
  675. Returns the PROJ representation for this spatial reference.
  676. .. attribute:: proj4
  677. Alias for :attr:`SpatialReference.proj`.
  678. .. attribute:: xml
  679. Returns the XML representation of this spatial reference.
  680. ``CoordTransform``
  681. ------------------
  682. .. class:: CoordTransform(source, target)
  683. Represents a coordinate system transform. It is initialized with two
  684. :class:`SpatialReference`, representing the source and target coordinate
  685. systems, respectively. These objects should be used when performing the same
  686. coordinate transformation repeatedly on different geometries::
  687. >>> ct = CoordTransform(SpatialReference('WGS84'), SpatialReference('NAD83'))
  688. >>> for feat in layer:
  689. ... geom = feat.geom # getting clone of feature geometry
  690. ... geom.transform(ct) # transforming
  691. .. _raster-data-source-objects:
  692. Raster Data Objects
  693. ===================
  694. ``GDALRaster``
  695. ----------------
  696. :class:`GDALRaster` is a wrapper for the GDAL raster source object that
  697. supports reading data from a variety of GDAL-supported geospatial file
  698. formats and data sources using a consistent interface. Each
  699. data source is represented by a :class:`GDALRaster` object which contains
  700. one or more layers of data named bands. Each band, represented by a
  701. :class:`GDALBand` object, contains georeferenced image data. For example, an RGB
  702. image is represented as three bands: one for red, one for green, and one for
  703. blue.
  704. .. note::
  705. For raster data there is no difference between a raster instance and its
  706. data source. Unlike for the Geometry objects, :class:`GDALRaster` objects are
  707. always a data source. Temporary rasters can be instantiated in memory
  708. using the corresponding driver, but they will be of the same class as file-based
  709. raster sources.
  710. .. class:: GDALRaster(ds_input, write=False)
  711. The constructor for ``GDALRaster`` accepts two parameters. The first
  712. parameter defines the raster source, and the second parameter defines if a
  713. raster should be opened in write mode. For newly-created rasters, the second
  714. parameter is ignored and the new raster is always created in write mode.
  715. The first parameter can take three forms: a string representing a file
  716. path, a dictionary with values defining a new raster, or a bytes object
  717. representing a raster file.
  718. If the input is a file path, the raster is opened from there. If the input
  719. is raw data in a dictionary, the parameters ``width``, ``height``, and
  720. ``srid`` are required. If the input is a bytes object, it will be opened
  721. using a GDAL virtual filesystem.
  722. For a detailed description of how to create rasters using dictionary input,
  723. see :ref:`gdal-raster-ds-input`. For a detailed description of how to
  724. create rasters in the virtual filesystem, see :ref:`gdal-raster-vsimem`.
  725. The following example shows how rasters can be created from different input
  726. sources (using the sample data from the GeoDjango tests; see also the
  727. :ref:`gdal_sample_data` section).
  728. >>> from django.contrib.gis.gdal import GDALRaster
  729. >>> rst = GDALRaster('/path/to/your/raster.tif', write=False)
  730. >>> rst.name
  731. '/path/to/your/raster.tif'
  732. >>> rst.width, rst.height # This file has 163 x 174 pixels
  733. (163, 174)
  734. >>> rst = GDALRaster({ # Creates an in-memory raster
  735. ... 'srid': 4326,
  736. ... 'width': 4,
  737. ... 'height': 4,
  738. ... 'datatype': 1,
  739. ... 'bands': [{
  740. ... 'data': (2, 3),
  741. ... 'offset': (1, 1),
  742. ... 'size': (2, 2),
  743. ... 'shape': (2, 1),
  744. ... 'nodata_value': 5,
  745. ... }]
  746. ... })
  747. >>> rst.srs.srid
  748. 4326
  749. >>> rst.width, rst.height
  750. (4, 4)
  751. >>> rst.bands[0].data()
  752. array([[5, 5, 5, 5],
  753. [5, 2, 3, 5],
  754. [5, 2, 3, 5],
  755. [5, 5, 5, 5]], dtype=uint8)
  756. >>> rst_file = open('/path/to/your/raster.tif', 'rb')
  757. >>> rst_bytes = rst_file.read()
  758. >>> rst = GDALRaster(rst_bytes)
  759. >>> rst.is_vsi_based
  760. True
  761. >>> rst.name # Stored in a random path in the vsimem filesystem.
  762. '/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'
  763. .. attribute:: name
  764. The name of the source which is equivalent to the input file path or the name
  765. provided upon instantiation.
  766. >>> GDALRaster({'width': 10, 'height': 10, 'name': 'myraster', 'srid': 4326}).name
  767. 'myraster'
  768. .. attribute:: driver
  769. The name of the GDAL driver used to handle the input file. For ``GDALRaster``\s created
  770. from a file, the driver type is detected automatically. The creation of rasters from
  771. scratch is an in-memory raster by default (``'MEM'``), but can be
  772. altered as needed. For instance, use ``GTiff`` for a ``GeoTiff`` file.
  773. For a list of file types, see also the `GDAL Raster Formats`__ list.
  774. __ https://gdal.org/drivers/raster/
  775. An in-memory raster is created through the following example:
  776. >>> GDALRaster({'width': 10, 'height': 10, 'srid': 4326}).driver.name
  777. 'MEM'
  778. A file based GeoTiff raster is created through the following example:
  779. >>> import tempfile
  780. >>> rstfile = tempfile.NamedTemporaryFile(suffix='.tif')
  781. >>> rst = GDALRaster({'driver': 'GTiff', 'name': rstfile.name, 'srid': 4326,
  782. ... 'width': 255, 'height': 255, 'nr_of_bands': 1})
  783. >>> rst.name
  784. '/tmp/tmp7x9H4J.tif' # The exact filename will be different on your computer
  785. >>> rst.driver.name
  786. 'GTiff'
  787. .. attribute:: width
  788. The width of the source in pixels (X-axis).
  789. >>> GDALRaster({'width': 10, 'height': 20, 'srid': 4326}).width
  790. 10
  791. .. attribute:: height
  792. The height of the source in pixels (Y-axis).
  793. >>> GDALRaster({'width': 10, 'height': 20, 'srid': 4326}).height
  794. 20
  795. .. attribute:: srs
  796. The spatial reference system of the raster, as a
  797. :class:`SpatialReference` instance. The SRS can be changed by
  798. setting it to an other :class:`SpatialReference` or providing any input
  799. that is accepted by the :class:`SpatialReference` constructor.
  800. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  801. >>> rst.srs.srid
  802. 4326
  803. >>> rst.srs = 3086
  804. >>> rst.srs.srid
  805. 3086
  806. .. attribute:: srid
  807. The Spatial Reference System Identifier (SRID) of the raster. This
  808. property is a shortcut to getting or setting the SRID through the
  809. :attr:`srs` attribute.
  810. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  811. >>> rst.srid
  812. 4326
  813. >>> rst.srid = 3086
  814. >>> rst.srid
  815. 3086
  816. >>> rst.srs.srid # This is equivalent
  817. 3086
  818. .. attribute:: geotransform
  819. The affine transformation matrix used to georeference the source, as a
  820. tuple of six coefficients which map pixel/line coordinates into
  821. georeferenced space using the following relationship::
  822. Xgeo = GT(0) + Xpixel*GT(1) + Yline*GT(2)
  823. Ygeo = GT(3) + Xpixel*GT(4) + Yline*GT(5)
  824. The same values can be retrieved by accessing the :attr:`origin`
  825. (indices 0 and 3), :attr:`scale` (indices 1 and 5) and :attr:`skew`
  826. (indices 2 and 4) properties.
  827. The default is ``[0.0, 1.0, 0.0, 0.0, 0.0, -1.0]``.
  828. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  829. >>> rst.geotransform
  830. [0.0, 1.0, 0.0, 0.0, 0.0, -1.0]
  831. .. attribute:: origin
  832. Coordinates of the top left origin of the raster in the spatial
  833. reference system of the source, as a point object with ``x`` and ``y``
  834. members.
  835. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  836. >>> rst.origin
  837. [0.0, 0.0]
  838. >>> rst.origin.x = 1
  839. >>> rst.origin
  840. [1.0, 0.0]
  841. .. attribute:: scale
  842. Pixel width and height used for georeferencing the raster, as a point
  843. object with ``x`` and ``y`` members. See :attr:`geotransform` for more
  844. information.
  845. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  846. >>> rst.scale
  847. [1.0, -1.0]
  848. >>> rst.scale.x = 2
  849. >>> rst.scale
  850. [2.0, -1.0]
  851. .. attribute:: skew
  852. Skew coefficients used to georeference the raster, as a point object
  853. with ``x`` and ``y`` members. In case of north up images, these
  854. coefficients are both ``0``.
  855. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  856. >>> rst.skew
  857. [0.0, 0.0]
  858. >>> rst.skew.x = 3
  859. >>> rst.skew
  860. [3.0, 0.0]
  861. .. attribute:: extent
  862. Extent (boundary values) of the raster source, as a 4-tuple
  863. ``(xmin, ymin, xmax, ymax)`` in the spatial reference system of the
  864. source.
  865. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  866. >>> rst.extent
  867. (0.0, -20.0, 10.0, 0.0)
  868. >>> rst.origin.x = 100
  869. >>> rst.extent
  870. (100.0, -20.0, 110.0, 0.0)
  871. .. attribute:: bands
  872. List of all bands of the source, as :class:`GDALBand` instances.
  873. >>> rst = GDALRaster({"width": 1, "height": 2, 'srid': 4326,
  874. ... "bands": [{"data": [0, 1]}, {"data": [2, 3]}]})
  875. >>> len(rst.bands)
  876. 2
  877. >>> rst.bands[1].data()
  878. array([[ 2., 3.]], dtype=float32)
  879. .. method:: warp(ds_input, resampling='NearestNeighbour', max_error=0.0)
  880. Returns a warped version of this raster.
  881. The warping parameters can be specified through the ``ds_input``
  882. argument. The use of ``ds_input`` is analogous to the corresponding
  883. argument of the class constructor. It is a dictionary with the
  884. characteristics of the target raster. Allowed dictionary key values are
  885. width, height, SRID, origin, scale, skew, datatype, driver, and name
  886. (filename).
  887. By default, the warp functions keeps most parameters equal to the
  888. values of the original source raster, so only parameters that should be
  889. changed need to be specified. Note that this includes the driver, so
  890. for file-based rasters the warp function will create a new raster on
  891. disk.
  892. The only parameter that is set differently from the source raster is the
  893. name. The default value of the raster name is the name of the source
  894. raster appended with ``'_copy' + source_driver_name``. For file-based
  895. rasters it is recommended to provide the file path of the target raster.
  896. The resampling algorithm used for warping can be specified with the
  897. ``resampling`` argument. The default is ``NearestNeighbor``, and the
  898. other allowed values are ``Bilinear``, ``Cubic``, ``CubicSpline``,
  899. ``Lanczos``, ``Average``, and ``Mode``.
  900. The ``max_error`` argument can be used to specify the maximum error
  901. measured in input pixels that is allowed in approximating the
  902. transformation. The default is 0.0 for exact calculations.
  903. For users familiar with ``GDAL``, this function has a similar
  904. functionality to the ``gdalwarp`` command-line utility.
  905. For example, the warp function can be used for aggregating a raster to
  906. the double of its original pixel scale:
  907. >>> rst = GDALRaster({
  908. ... "width": 6, "height": 6, "srid": 3086,
  909. ... "origin": [500000, 400000],
  910. ... "scale": [100, -100],
  911. ... "bands": [{"data": range(36), "nodata_value": 99}]
  912. ... })
  913. >>> target = rst.warp({"scale": [200, -200], "width": 3, "height": 3})
  914. >>> target.bands[0].data()
  915. array([[ 7., 9., 11.],
  916. [ 19., 21., 23.],
  917. [ 31., 33., 35.]], dtype=float32)
  918. .. method:: transform(srs, driver=None, name=None, resampling='NearestNeighbour', max_error=0.0)
  919. Transforms this raster to a different spatial reference system
  920. (``srs``), which may be a :class:`SpatialReference` object, or any
  921. other input accepted by :class:`SpatialReference` (including spatial
  922. reference WKT and PROJ strings, or an integer SRID).
  923. It calculates the bounds and scale of the current raster in the new
  924. spatial reference system and warps the raster using the
  925. :attr:`~GDALRaster.warp` function.
  926. By default, the driver of the source raster is used and the name of the
  927. raster is the original name appended with
  928. ``'_copy' + source_driver_name``. A different driver or name can be
  929. specified with the ``driver`` and ``name`` arguments.
  930. The default resampling algorithm is ``NearestNeighbour`` but can be
  931. changed using the ``resampling`` argument. The default maximum allowed
  932. error for resampling is 0.0 and can be changed using the ``max_error``
  933. argument. Consult the :attr:`~GDALRaster.warp` documentation for detail
  934. on those arguments.
  935. >>> rst = GDALRaster({
  936. ... "width": 6, "height": 6, "srid": 3086,
  937. ... "origin": [500000, 400000],
  938. ... "scale": [100, -100],
  939. ... "bands": [{"data": range(36), "nodata_value": 99}]
  940. ... })
  941. >>> target_srs = SpatialReference(4326)
  942. >>> target = rst.transform(target_srs)
  943. >>> target.origin
  944. [-82.98492744885776, 27.601924753080144]
  945. .. versionchanged:: 3.2
  946. Support for :class:`SpatialReference` ``srs`` was added
  947. .. attribute:: info
  948. Returns a string with a summary of the raster. This is equivalent to
  949. the `gdalinfo`__ command line utility.
  950. __ https://gdal.org/programs/gdalinfo.html
  951. .. attribute:: metadata
  952. The metadata of this raster, represented as a nested dictionary. The
  953. first-level key is the metadata domain. The second-level contains the
  954. metadata item names and values from each domain.
  955. To set or update a metadata item, pass the corresponding metadata item
  956. to the method using the nested structure described above. Only keys
  957. that are in the specified dictionary are updated; the rest of the
  958. metadata remains unchanged.
  959. To remove a metadata item, use ``None`` as the metadata value.
  960. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  961. >>> rst.metadata
  962. {}
  963. >>> rst.metadata = {'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0'}}
  964. >>> rst.metadata
  965. {'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0'}}
  966. >>> rst.metadata = {'DEFAULT': {'OWNER': None, 'VERSION': '2.0'}}
  967. >>> rst.metadata
  968. {'DEFAULT': {'VERSION': '2.0'}}
  969. .. attribute:: vsi_buffer
  970. A ``bytes`` representation of this raster. Returns ``None`` for rasters
  971. that are not stored in GDAL's virtual filesystem.
  972. .. attribute:: is_vsi_based
  973. A boolean indicating if this raster is stored in GDAL's virtual
  974. filesystem.
  975. ``GDALBand``
  976. ------------
  977. .. class:: GDALBand
  978. ``GDALBand`` instances are not created explicitly, but rather obtained
  979. from a :class:`GDALRaster` object, through its :attr:`~GDALRaster.bands`
  980. attribute. The GDALBands contain the actual pixel values of the raster.
  981. .. attribute:: description
  982. The name or description of the band, if any.
  983. .. attribute:: width
  984. The width of the band in pixels (X-axis).
  985. .. attribute:: height
  986. The height of the band in pixels (Y-axis).
  987. .. attribute:: pixel_count
  988. The total number of pixels in this band. Is equal to ``width * height``.
  989. .. method:: statistics(refresh=False, approximate=False)
  990. Compute statistics on the pixel values of this band. The return value
  991. is a tuple with the following structure:
  992. ``(minimum, maximum, mean, standard deviation)``.
  993. If the ``approximate`` argument is set to ``True``, the statistics may
  994. be computed based on overviews or a subset of image tiles.
  995. If the ``refresh`` argument is set to ``True``, the statistics will be
  996. computed from the data directly, and the cache will be updated with the
  997. result.
  998. If a persistent cache value is found, that value is returned. For
  999. raster formats using Persistent Auxiliary Metadata (PAM) services, the
  1000. statistics might be cached in an auxiliary file. In some cases this
  1001. metadata might be out of sync with the pixel values or cause values
  1002. from a previous call to be returned which don't reflect the value of
  1003. the ``approximate`` argument. In such cases, use the ``refresh``
  1004. argument to get updated values and store them in the cache.
  1005. For empty bands (where all pixel values are "no data"), all statistics
  1006. are returned as ``None``.
  1007. The statistics can also be retrieved directly by accessing the
  1008. :attr:`min`, :attr:`max`, :attr:`mean`, and :attr:`std` properties.
  1009. .. attribute:: min
  1010. The minimum pixel value of the band (excluding the "no data" value).
  1011. .. attribute:: max
  1012. The maximum pixel value of the band (excluding the "no data" value).
  1013. .. attribute:: mean
  1014. The mean of all pixel values of the band (excluding the "no data"
  1015. value).
  1016. .. attribute:: std
  1017. The standard deviation of all pixel values of the band (excluding the
  1018. "no data" value).
  1019. .. attribute:: nodata_value
  1020. The "no data" value for a band is generally a special marker value used
  1021. to mark pixels that are not valid data. Such pixels should generally not
  1022. be displayed, nor contribute to analysis operations.
  1023. To delete an existing "no data" value, set this property to ``None``
  1024. (requires GDAL ≥ 2.1).
  1025. .. method:: datatype(as_string=False)
  1026. The data type contained in the band, as an integer constant between 0
  1027. (Unknown) and 11. If ``as_string`` is ``True``, the data type is
  1028. returned as a string with the following possible values:
  1029. ``GDT_Unknown``, ``GDT_Byte``, ``GDT_UInt16``, ``GDT_Int16``,
  1030. ``GDT_UInt32``, ``GDT_Int32``, ``GDT_Float32``, ``GDT_Float64``,
  1031. ``GDT_CInt16``, ``GDT_CInt32``, ``GDT_CFloat32``, and ``GDT_CFloat64``.
  1032. .. method:: color_interp(as_string=False)
  1033. The color interpretation for the band, as an integer between 0and 16.
  1034. If ``as_string`` is ``True``, the data type is returned as a string
  1035. with the following possible values:
  1036. ``GCI_Undefined``, ``GCI_GrayIndex``, ``GCI_PaletteIndex``,
  1037. ``GCI_RedBand``, ``GCI_GreenBand``, ``GCI_BlueBand``, ``GCI_AlphaBand``,
  1038. ``GCI_HueBand``, ``GCI_SaturationBand``, ``GCI_LightnessBand``,
  1039. ``GCI_CyanBand``, ``GCI_MagentaBand``, ``GCI_YellowBand``,
  1040. ``GCI_BlackBand``, ``GCI_YCbCr_YBand``, ``GCI_YCbCr_CbBand``, and
  1041. ``GCI_YCbCr_CrBand``. ``GCI_YCbCr_CrBand`` also represents ``GCI_Max``
  1042. because both correspond to the integer 16, but only ``GCI_YCbCr_CrBand``
  1043. is returned as a string.
  1044. .. method:: data(data=None, offset=None, size=None, shape=None)
  1045. The accessor to the pixel values of the ``GDALBand``. Returns the complete
  1046. data array if no parameters are provided. A subset of the pixel array can
  1047. be requested by specifying an offset and block size as tuples.
  1048. If NumPy is available, the data is returned as NumPy array. For performance
  1049. reasons, it is highly recommended to use NumPy.
  1050. Data is written to the ``GDALBand`` if the ``data`` parameter is provided.
  1051. The input can be of one of the following types - packed string, buffer, list,
  1052. array, and NumPy array. The number of items in the input should normally
  1053. correspond to the total number of pixels in the band, or to the number
  1054. of pixels for a specific block of pixel values if the ``offset`` and
  1055. ``size`` parameters are provided.
  1056. If the number of items in the input is different from the target pixel
  1057. block, the ``shape`` parameter must be specified. The shape is a tuple
  1058. that specifies the width and height of the input data in pixels. The
  1059. data is then replicated to update the pixel values of the selected
  1060. block. This is useful to fill an entire band with a single value, for
  1061. instance.
  1062. For example:
  1063. >>> rst = GDALRaster({'width': 4, 'height': 4, 'srid': 4326, 'datatype': 1, 'nr_of_bands': 1})
  1064. >>> bnd = rst.bands[0]
  1065. >>> bnd.data(range(16))
  1066. >>> bnd.data()
  1067. array([[ 0, 1, 2, 3],
  1068. [ 4, 5, 6, 7],
  1069. [ 8, 9, 10, 11],
  1070. [12, 13, 14, 15]], dtype=int8)
  1071. >>> bnd.data(offset=(1, 1), size=(2, 2))
  1072. array([[ 5, 6],
  1073. [ 9, 10]], dtype=int8)
  1074. >>> bnd.data(data=[-1, -2, -3, -4], offset=(1, 1), size=(2, 2))
  1075. >>> bnd.data()
  1076. array([[ 0, 1, 2, 3],
  1077. [ 4, -1, -2, 7],
  1078. [ 8, -3, -4, 11],
  1079. [12, 13, 14, 15]], dtype=int8)
  1080. >>> bnd.data(data='\x9d\xa8\xb3\xbe', offset=(1, 1), size=(2, 2))
  1081. >>> bnd.data()
  1082. array([[ 0, 1, 2, 3],
  1083. [ 4, -99, -88, 7],
  1084. [ 8, -77, -66, 11],
  1085. [ 12, 13, 14, 15]], dtype=int8)
  1086. >>> bnd.data([1], shape=(1, 1))
  1087. >>> bnd.data()
  1088. array([[1, 1, 1, 1],
  1089. [1, 1, 1, 1],
  1090. [1, 1, 1, 1],
  1091. [1, 1, 1, 1]], dtype=uint8)
  1092. >>> bnd.data(range(4), shape=(1, 4))
  1093. array([[0, 0, 0, 0],
  1094. [1, 1, 1, 1],
  1095. [2, 2, 2, 2],
  1096. [3, 3, 3, 3]], dtype=uint8)
  1097. .. attribute:: metadata
  1098. The metadata of this band. The functionality is identical to
  1099. :attr:`GDALRaster.metadata`.
  1100. .. _gdal-raster-ds-input:
  1101. Creating rasters from data
  1102. --------------------------
  1103. This section describes how to create rasters from scratch using the
  1104. ``ds_input`` parameter.
  1105. A new raster is created when a ``dict`` is passed to the :class:`GDALRaster`
  1106. constructor. The dictionary contains defining parameters of the new raster,
  1107. such as the origin, size, or spatial reference system. The dictionary can also
  1108. contain pixel data and information about the format of the new raster. The
  1109. resulting raster can therefore be file-based or memory-based, depending on the
  1110. driver specified.
  1111. There's no standard for describing raster data in a dictionary or JSON flavor.
  1112. The definition of the dictionary input to the :class:`GDALRaster` class is
  1113. therefore specific to Django. It's inspired by the `geojson`__ format, but the
  1114. ``geojson`` standard is currently limited to vector formats.
  1115. Examples of using the different keys when creating rasters can be found in the
  1116. documentation of the corresponding attributes and methods of the
  1117. :class:`GDALRaster` and :class:`GDALBand` classes.
  1118. __ https://geojson.org
  1119. The ``ds_input`` dictionary
  1120. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1121. Only a few keys are required in the ``ds_input`` dictionary to create a raster:
  1122. ``width``, ``height``, and ``srid``. All other parameters have default values
  1123. (see the table below). The list of keys that can be passed in the ``ds_input``
  1124. dictionary is closely related but not identical to the :class:`GDALRaster`
  1125. properties. Many of the parameters are mapped directly to those properties;
  1126. the others are described below.
  1127. The following table describes all keys that can be set in the ``ds_input``
  1128. dictionary.
  1129. ================= ======== ==================================================
  1130. Key Default Usage
  1131. ================= ======== ==================================================
  1132. ``srid`` required Mapped to the :attr:`~GDALRaster.srid` attribute
  1133. ``width`` required Mapped to the :attr:`~GDALRaster.width` attribute
  1134. ``height`` required Mapped to the :attr:`~GDALRaster.height` attribute
  1135. ``driver`` ``MEM`` Mapped to the :attr:`~GDALRaster.driver` attribute
  1136. ``name`` ``''`` See below
  1137. ``origin`` ``0`` Mapped to the :attr:`~GDALRaster.origin` attribute
  1138. ``scale`` ``0`` Mapped to the :attr:`~GDALRaster.scale` attribute
  1139. ``skew`` ``0`` Mapped to the :attr:`~GDALRaster.width` attribute
  1140. ``bands`` ``[]`` See below
  1141. ``nr_of_bands`` ``0`` See below
  1142. ``datatype`` ``6`` See below
  1143. ``papsz_options`` ``{}`` See below
  1144. ================= ======== ==================================================
  1145. .. object:: name
  1146. String representing the name of the raster. When creating a file-based
  1147. raster, this parameter must be the file path for the new raster. If the
  1148. name starts with ``/vsimem/``, the raster is created in GDAL's virtual
  1149. filesystem.
  1150. .. object:: datatype
  1151. Integer representing the data type for all the bands. Defaults to ``6``
  1152. (Float32). All bands of a new raster are required to have the same datatype.
  1153. The value mapping is:
  1154. ===== =============== ===============================
  1155. Value GDAL Pixel Type Description
  1156. ===== =============== ===============================
  1157. 1 GDT_Byte Eight bit unsigned integer
  1158. 2 GDT_UInt16 Sixteen bit unsigned integer
  1159. 3 GDT_Int16 Sixteen bit signed integer
  1160. 4 GDT_UInt32 Thirty-two bit unsigned integer
  1161. 5 GDT_Int32 Thirty-two bit signed integer
  1162. 6 GDT_Float32 Thirty-two bit floating point
  1163. 7 GDT_Float64 Sixty-four bit floating point
  1164. ===== =============== ===============================
  1165. .. object:: nr_of_bands
  1166. Integer representing the number of bands of the raster. A raster can be
  1167. created without passing band data upon creation. If the number of bands
  1168. isn't specified, it's automatically calculated from the length of the
  1169. ``bands`` input. The number of bands can't be changed after creation.
  1170. .. object:: bands
  1171. A list of ``band_input`` dictionaries with band input data. The resulting
  1172. band indices are the same as in the list provided. The definition of the
  1173. band input dictionary is given below. If band data isn't provided, the
  1174. raster bands values are instantiated as an array of zeros and the "no
  1175. data" value is set to ``None``.
  1176. .. object:: papsz_options
  1177. A dictionary with raster creation options. The key-value pairs of the
  1178. input dictionary are passed to the driver on creation of the raster.
  1179. The available options are driver-specific and are described in the
  1180. documentation of each driver.
  1181. The values in the dictionary are not case-sensitive and are automatically
  1182. converted to the correct string format upon creation.
  1183. The following example uses some of the options available for the
  1184. `GTiff driver`__. The result is a compressed signed byte raster with an
  1185. internal tiling scheme. The internal tiles have a block size of 23 by 23::
  1186. >>> GDALRaster({
  1187. ... 'driver': 'GTiff',
  1188. ... 'name': '/path/to/new/file.tif',
  1189. ... 'srid': 4326,
  1190. ... 'width': 255,
  1191. ... 'height': 255,
  1192. ... 'nr_of_bands': 1,
  1193. ... 'papsz_options': {
  1194. ... 'compress': 'packbits',
  1195. ... 'pixeltype': 'signedbyte',
  1196. ... 'tiled': 'yes',
  1197. ... 'blockxsize': 23,
  1198. ... 'blockysize': 23,
  1199. ... }
  1200. ... })
  1201. __ https://gdal.org/drivers/raster/gtiff.html
  1202. The ``band_input`` dictionary
  1203. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1204. The ``bands`` key in the ``ds_input`` dictionary is a list of ``band_input``
  1205. dictionaries. Each ``band_input`` dictionary can contain pixel values and the
  1206. "no data" value to be set on the bands of the new raster. The data array can
  1207. have the full size of the new raster or be smaller. For arrays that are smaller
  1208. than the full raster, the ``size``, ``shape``, and ``offset`` keys control the
  1209. pixel values. The corresponding keys are passed to the :meth:`~GDALBand.data`
  1210. method. Their functionality is the same as setting the band data with that
  1211. method. The following table describes the keys that can be used.
  1212. ================ ================================= ======================================================
  1213. Key Default Usage
  1214. ================ ================================= ======================================================
  1215. ``nodata_value`` ``None`` Mapped to the :attr:`~GDALBand.nodata_value` attribute
  1216. ``data`` Same as ``nodata_value`` or ``0`` Passed to the :meth:`~GDALBand.data` method
  1217. ``size`` ``(with, height)`` of raster Passed to the :meth:`~GDALBand.data` method
  1218. ``shape`` Same as size Passed to the :meth:`~GDALBand.data` method
  1219. ``offset`` ``(0, 0)`` Passed to the :meth:`~GDALBand.data` method
  1220. ================ ================================= ======================================================
  1221. .. _gdal-raster-vsimem:
  1222. Using GDAL's Virtual Filesystem
  1223. -------------------------------
  1224. GDAL has an internal memory-based filesystem, which allows treating blocks of
  1225. memory as files. It can be used to read and write :class:`GDALRaster` objects
  1226. to and from binary file buffers.
  1227. This is useful in web contexts where rasters might be obtained as a buffer
  1228. from a remote storage or returned from a view without being written to disk.
  1229. :class:`GDALRaster` objects are created in the virtual filesystem when a
  1230. ``bytes`` object is provided as input, or when the file path starts with
  1231. ``/vsimem/``.
  1232. Input provided as ``bytes`` has to be a full binary representation of a file.
  1233. For instance::
  1234. # Read a raster as a file object from a remote source.
  1235. >>> from urllib.request import urlopen
  1236. >>> dat = urlopen('http://example.com/raster.tif').read()
  1237. # Instantiate a raster from the bytes object.
  1238. >>> rst = GDALRaster(dat)
  1239. # The name starts with /vsimem/, indicating that the raster lives in the
  1240. # virtual filesystem.
  1241. >>> rst.name
  1242. '/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'
  1243. To create a new virtual file-based raster from scratch, use the ``ds_input``
  1244. dictionary representation and provide a ``name`` argument that starts with
  1245. ``/vsimem/`` (for detail of the dictionary representation, see
  1246. :ref:`gdal-raster-ds-input`). For virtual file-based rasters, the
  1247. :attr:`~GDALRaster.vsi_buffer` attribute returns the ``bytes`` representation
  1248. of the raster.
  1249. Here's how to create a raster and return it as a file in an
  1250. :class:`~django.http.HttpResponse`::
  1251. >>> from django.http import HttpResponse
  1252. >>> rst = GDALRaster({
  1253. ... 'name': '/vsimem/temporarymemfile',
  1254. ... 'driver': 'tif',
  1255. ... 'width': 6, 'height': 6, 'srid': 3086,
  1256. ... 'origin': [500000, 400000],
  1257. ... 'scale': [100, -100],
  1258. ... 'bands': [{'data': range(36), 'nodata_value': 99}]
  1259. ... })
  1260. >>> HttpResponse(rast.vsi_buffer, 'image/tiff')
  1261. Settings
  1262. ========
  1263. .. setting:: GDAL_LIBRARY_PATH
  1264. ``GDAL_LIBRARY_PATH``
  1265. ---------------------
  1266. A string specifying the location of the GDAL library. Typically,
  1267. this setting is only used if the GDAL library is in a non-standard
  1268. location (e.g., ``/home/john/lib/libgdal.so``).
  1269. Exceptions
  1270. ==========
  1271. .. exception:: GDALException
  1272. The base GDAL exception, indicating a GDAL-related error.
  1273. .. exception:: SRSException
  1274. An exception raised when an error occurs when constructing or using a
  1275. spatial reference system object.