gdal.txt 61 KB

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