gdal.txt 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744
  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. __ http://www.gdal.org/
  19. __ http://www.gdal.org/ogr_arch.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. simple 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 simple, 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. __ http://www.gdal.org/ogr_formats.html
  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. __ http://www.gdal.org/classOGRGeometry.html
  309. .. classmethod:: from_gml(gml_string)
  310. .. versionadded:: 1.11
  311. Constructs an :class:`OGRGeometry` from the given GML string.
  312. .. classmethod:: from_bbox(bbox)
  313. Constructs a :class:`Polygon` from the given bounding-box (a 4-tuple).
  314. .. method:: __len__()
  315. Returns the number of points in a :class:`LineString`, the number of rings
  316. in a :class:`Polygon`, or the number of geometries in a
  317. :class:`GeometryCollection`. Not applicable to other geometry types.
  318. .. method:: __iter__()
  319. Iterates over the points in a :class:`LineString`, the rings in a
  320. :class:`Polygon`, or the geometries in a :class:`GeometryCollection`.
  321. Not applicable to other geometry types.
  322. .. method:: __getitem__()
  323. Returns the point at the specified index for a :class:`LineString`, the
  324. interior ring at the specified index for a :class:`Polygon`, or the geometry
  325. at the specified index in a :class:`GeometryCollection`. Not applicable to
  326. other geometry types.
  327. .. attribute:: dimension
  328. Returns the number of coordinated dimensions of the geometry, i.e. 0
  329. for points, 1 for lines, and so forth::
  330. >> polygon.dimension
  331. 2
  332. .. attribute:: coord_dim
  333. Returns or sets the coordinate dimension of this geometry. For example, the
  334. value would be 2 for two-dimensional geometries.
  335. .. attribute:: geom_count
  336. Returns the number of elements in this geometry::
  337. >>> polygon.geom_count
  338. 1
  339. .. attribute:: point_count
  340. Returns the number of points used to describe this geometry::
  341. >>> polygon.point_count
  342. 4
  343. .. attribute:: num_points
  344. Alias for :attr:`point_count`.
  345. .. attribute:: num_coords
  346. Alias for :attr:`point_count`.
  347. .. attribute:: geom_type
  348. Returns the type of this geometry, as an :class:`OGRGeomType` object.
  349. .. attribute:: geom_name
  350. Returns the name of the type of this geometry::
  351. >>> polygon.geom_name
  352. 'POLYGON'
  353. .. attribute:: area
  354. Returns the area of this geometry, or 0 for geometries that do not contain
  355. an area::
  356. >>> polygon.area
  357. 25.0
  358. .. attribute:: envelope
  359. Returns the envelope of this geometry, as an :class:`Envelope` object.
  360. .. attribute:: extent
  361. Returns the envelope of this geometry as a 4-tuple, instead of as an
  362. :class:`Envelope` object::
  363. >>> point.extent
  364. (0.0, 0.0, 5.0, 5.0)
  365. .. attribute:: srs
  366. This property controls the spatial reference for this geometry, or
  367. ``None`` if no spatial reference system has been assigned to it.
  368. If assigned, accessing this property returns a :class:`SpatialReference`
  369. object. It may be set with another :class:`SpatialReference` object,
  370. or any input that :class:`SpatialReference` accepts. Example::
  371. >>> city.geom.srs.name
  372. 'GCS_WGS_1984'
  373. .. attribute:: srid
  374. Returns or sets the spatial reference identifier corresponding to
  375. :class:`SpatialReference` of this geometry. Returns ``None`` if
  376. there is no spatial reference information associated with this
  377. geometry, or if an SRID cannot be determined.
  378. .. attribute:: geos
  379. Returns a :class:`~django.contrib.gis.geos.GEOSGeometry` object
  380. corresponding to this geometry.
  381. .. attribute:: gml
  382. Returns a string representation of this geometry in GML format::
  383. >>> OGRGeometry('POINT(1 2)').gml
  384. '<gml:Point><gml:coordinates>1,2</gml:coordinates></gml:Point>'
  385. .. attribute:: hex
  386. Returns a string representation of this geometry in HEX WKB format::
  387. >>> OGRGeometry('POINT(1 2)').hex
  388. '0101000000000000000000F03F0000000000000040'
  389. .. attribute:: json
  390. Returns a string representation of this geometry in JSON format::
  391. >>> OGRGeometry('POINT(1 2)').json
  392. '{ "type": "Point", "coordinates": [ 1.000000, 2.000000 ] }'
  393. .. attribute:: kml
  394. Returns a string representation of this geometry in KML format.
  395. .. attribute:: wkb_size
  396. Returns the size of the WKB buffer needed to hold a WKB representation
  397. of this geometry::
  398. >>> OGRGeometry('POINT(1 2)').wkb_size
  399. 21
  400. .. attribute:: wkb
  401. Returns a ``buffer`` containing a WKB representation of this geometry.
  402. .. attribute:: wkt
  403. Returns a string representation of this geometry in WKT format.
  404. .. attribute:: ewkt
  405. Returns the EWKT representation of this geometry.
  406. .. method:: clone()
  407. Returns a new :class:`OGRGeometry` clone of this geometry object.
  408. .. method:: close_rings()
  409. If there are any rings within this geometry that have not been closed,
  410. this routine will do so by adding the starting point to the end::
  411. >>> triangle = OGRGeometry('LINEARRING (0 0,0 1,1 0)')
  412. >>> triangle.close_rings()
  413. >>> triangle.wkt
  414. 'LINEARRING (0 0,0 1,1 0,0 0)'
  415. .. method:: transform(coord_trans, clone=False)
  416. Transforms this geometry to a different spatial reference system. May take
  417. a :class:`CoordTransform` object, a :class:`SpatialReference` object, or
  418. any other input accepted by :class:`SpatialReference` (including spatial
  419. reference WKT and PROJ.4 strings, or an integer SRID).
  420. By default nothing is returned and the geometry is transformed in-place.
  421. However, if the ``clone`` keyword is set to ``True`` then a transformed
  422. clone of this geometry is returned instead.
  423. .. method:: intersects(other)
  424. Returns ``True`` if this geometry intersects the other, otherwise returns
  425. ``False``.
  426. .. method:: equals(other)
  427. Returns ``True`` if this geometry is equivalent to the other, otherwise
  428. returns ``False``.
  429. .. method:: disjoint(other)
  430. Returns ``True`` if this geometry is spatially disjoint to (i.e. does
  431. not intersect) the other, otherwise returns ``False``.
  432. .. method:: touches(other)
  433. Returns ``True`` if this geometry touches the other, otherwise returns
  434. ``False``.
  435. .. method:: crosses(other)
  436. Returns ``True`` if this geometry crosses the other, otherwise returns
  437. ``False``.
  438. .. method:: within(other)
  439. Returns ``True`` if this geometry is contained within the other, otherwise
  440. returns ``False``.
  441. .. method:: contains(other)
  442. Returns ``True`` if this geometry contains the other, otherwise returns
  443. ``False``.
  444. .. method:: overlaps(other)
  445. Returns ``True`` if this geometry overlaps the other, otherwise returns
  446. ``False``.
  447. .. method:: boundary()
  448. The boundary of this geometry, as a new :class:`OGRGeometry` object.
  449. .. attribute:: convex_hull
  450. The smallest convex polygon that contains this geometry, as a new
  451. :class:`OGRGeometry` object.
  452. .. method:: difference()
  453. Returns the region consisting of the difference of this geometry and
  454. the other, as a new :class:`OGRGeometry` object.
  455. .. method:: intersection()
  456. Returns the region consisting of the intersection of this geometry and
  457. the other, as a new :class:`OGRGeometry` object.
  458. .. method:: sym_difference()
  459. Returns the region consisting of the symmetric difference of this
  460. geometry and the other, as a new :class:`OGRGeometry` object.
  461. .. method:: union()
  462. Returns the region consisting of the union of this geometry and
  463. the other, as a new :class:`OGRGeometry` object.
  464. .. attribute:: tuple
  465. Returns the coordinates of a point geometry as a tuple, the
  466. coordinates of a line geometry as a tuple of tuples, and so forth::
  467. >>> OGRGeometry('POINT (1 2)').tuple
  468. (1.0, 2.0)
  469. >>> OGRGeometry('LINESTRING (1 2,3 4)').tuple
  470. ((1.0, 2.0), (3.0, 4.0))
  471. .. attribute:: coords
  472. An alias for :attr:`tuple`.
  473. .. class:: Point
  474. .. attribute:: x
  475. Returns the X coordinate of this point::
  476. >>> OGRGeometry('POINT (1 2)').x
  477. 1.0
  478. .. attribute:: y
  479. Returns the Y coordinate of this point::
  480. >>> OGRGeometry('POINT (1 2)').y
  481. 2.0
  482. .. attribute:: z
  483. Returns the Z coordinate of this point, or ``None`` if the point does not
  484. have a Z coordinate::
  485. >>> OGRGeometry('POINT (1 2 3)').z
  486. 3.0
  487. .. class:: LineString
  488. .. attribute:: x
  489. Returns a list of X coordinates in this line::
  490. >>> OGRGeometry('LINESTRING (1 2,3 4)').x
  491. [1.0, 3.0]
  492. .. attribute:: y
  493. Returns a list of Y coordinates in this line::
  494. >>> OGRGeometry('LINESTRING (1 2,3 4)').y
  495. [2.0, 4.0]
  496. .. attribute:: z
  497. Returns a list of Z coordinates in this line, or ``None`` if the line does
  498. not have Z coordinates::
  499. >>> OGRGeometry('LINESTRING (1 2 3,4 5 6)').z
  500. [3.0, 6.0]
  501. .. class:: Polygon
  502. .. attribute:: shell
  503. Returns the shell or exterior ring of this polygon, as a ``LinearRing``
  504. geometry.
  505. .. attribute:: exterior_ring
  506. An alias for :attr:`shell`.
  507. .. attribute:: centroid
  508. Returns a :class:`Point` representing the centroid of this polygon.
  509. .. class:: GeometryCollection
  510. .. method:: add(geom)
  511. Adds a geometry to this geometry collection. Not applicable to other
  512. geometry types.
  513. ``OGRGeomType``
  514. ---------------
  515. .. class:: OGRGeomType(type_input)
  516. This class allows for the representation of an OGR geometry type
  517. in any of several ways::
  518. >>> from django.contrib.gis.gdal import OGRGeomType
  519. >>> gt1 = OGRGeomType(3) # Using an integer for the type
  520. >>> gt2 = OGRGeomType('Polygon') # Using a string
  521. >>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive
  522. >>> print(gt1 == 3, gt1 == 'Polygon') # Equivalence works w/non-OGRGeomType objects
  523. True True
  524. .. attribute:: name
  525. Returns a short-hand string form of the OGR Geometry type::
  526. >>> gt1.name
  527. 'Polygon'
  528. .. attribute:: num
  529. Returns the number corresponding to the OGR geometry type::
  530. >>> gt1.num
  531. 3
  532. .. attribute:: django
  533. Returns the Django field type (a subclass of GeometryField) to use for
  534. storing this OGR type, or ``None`` if there is no appropriate Django type::
  535. >>> gt1.django
  536. 'PolygonField'
  537. ``Envelope``
  538. ------------
  539. .. class:: Envelope(*args)
  540. Represents an OGR Envelope structure that contains the minimum and maximum
  541. X, Y coordinates for a rectangle bounding box. The naming of the variables
  542. is compatible with the OGR Envelope C structure.
  543. .. attribute:: min_x
  544. The value of the minimum X coordinate.
  545. .. attribute:: min_y
  546. The value of the maximum X coordinate.
  547. .. attribute:: max_x
  548. The value of the minimum Y coordinate.
  549. .. attribute:: max_y
  550. The value of the maximum Y coordinate.
  551. .. attribute:: ur
  552. The upper-right coordinate, as a tuple.
  553. .. attribute:: ll
  554. The lower-left coordinate, as a tuple.
  555. .. attribute:: tuple
  556. A tuple representing the envelope.
  557. .. attribute:: wkt
  558. A string representing this envelope as a polygon in WKT format.
  559. .. method:: expand_to_include(*args)
  560. Coordinate System Objects
  561. =========================
  562. ``SpatialReference``
  563. --------------------
  564. .. class:: SpatialReference(srs_input)
  565. Spatial reference objects are initialized on the given ``srs_input``,
  566. which may be one of the following:
  567. * OGC Well Known Text (WKT) (a string)
  568. * EPSG code (integer or string)
  569. * PROJ.4 string
  570. * A shorthand string for well-known standards (``'WGS84'``, ``'WGS72'``,
  571. ``'NAD27'``, ``'NAD83'``)
  572. Example::
  573. >>> wgs84 = SpatialReference('WGS84') # shorthand string
  574. >>> wgs84 = SpatialReference(4326) # EPSG code
  575. >>> wgs84 = SpatialReference('EPSG:4326') # EPSG string
  576. >>> proj4 = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs '
  577. >>> wgs84 = SpatialReference(proj4) # PROJ.4 string
  578. >>> wgs84 = SpatialReference("""GEOGCS["WGS 84",
  579. DATUM["WGS_1984",
  580. SPHEROID["WGS 84",6378137,298.257223563,
  581. AUTHORITY["EPSG","7030"]],
  582. AUTHORITY["EPSG","6326"]],
  583. PRIMEM["Greenwich",0,
  584. AUTHORITY["EPSG","8901"]],
  585. UNIT["degree",0.01745329251994328,
  586. AUTHORITY["EPSG","9122"]],
  587. AUTHORITY["EPSG","4326"]]""") # OGC WKT
  588. .. method:: __getitem__(target)
  589. Returns the value of the given string attribute node, ``None`` if the node
  590. doesn't exist. Can also take a tuple as a parameter, (target, child), where
  591. child is the index of the attribute in the WKT. For example::
  592. >>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]')
  593. >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326
  594. >>> print(srs['GEOGCS'])
  595. WGS 84
  596. >>> print(srs['DATUM'])
  597. WGS_1984
  598. >>> print(srs['AUTHORITY'])
  599. EPSG
  600. >>> print(srs['AUTHORITY', 1]) # The authority value
  601. 4326
  602. >>> print(srs['TOWGS84', 4]) # the fourth value in this wkt
  603. 0
  604. >>> print(srs['UNIT|AUTHORITY']) # For the units authority, have to use the pipe symbol.
  605. EPSG
  606. >>> print(srs['UNIT|AUTHORITY', 1]) # The authority value for the units
  607. 9122
  608. .. method:: attr_value(target, index=0)
  609. The attribute value for the given target node (e.g. ``'PROJCS'``).
  610. The index keyword specifies an index of the child node to return.
  611. .. method:: auth_name(target)
  612. Returns the authority name for the given string target node.
  613. .. method:: auth_code(target)
  614. Returns the authority code for the given string target node.
  615. .. method:: clone()
  616. Returns a clone of this spatial reference object.
  617. .. method:: identify_epsg()
  618. This method inspects the WKT of this ``SpatialReference`` and will add EPSG
  619. authority nodes where an EPSG identifier is applicable.
  620. .. method:: from_esri()
  621. Morphs this SpatialReference from ESRI's format to EPSG
  622. .. method:: to_esri()
  623. Morphs this SpatialReference to ESRI's format.
  624. .. method:: validate()
  625. Checks to see if the given spatial reference is valid, if not
  626. an exception will be raised.
  627. .. method:: import_epsg(epsg)
  628. Import spatial reference from EPSG code.
  629. .. method:: import_proj(proj)
  630. Import spatial reference from PROJ.4 string.
  631. .. method:: import_user_input(user_input)
  632. .. method:: import_wkt(wkt)
  633. Import spatial reference from WKT.
  634. .. method:: import_xml(xml)
  635. Import spatial reference from XML.
  636. .. attribute:: name
  637. Returns the name of this Spatial Reference.
  638. .. attribute:: srid
  639. Returns the SRID of top-level authority, or ``None`` if undefined.
  640. .. attribute:: linear_name
  641. Returns the name of the linear units.
  642. .. attribute:: linear_units
  643. Returns the value of the linear units.
  644. .. attribute:: angular_name
  645. Returns the name of the angular units."
  646. .. attribute:: angular_units
  647. Returns the value of the angular units.
  648. .. attribute:: units
  649. Returns a 2-tuple of the units value and the units name and will
  650. automatically determines whether to return the linear or angular units.
  651. .. attribute:: ellipsoid
  652. Returns a tuple of the ellipsoid parameters for this spatial reference:
  653. (semimajor axis, semiminor axis, and inverse flattening).
  654. .. attribute:: semi_major
  655. Returns the semi major axis of the ellipsoid for this spatial reference.
  656. .. attribute:: semi_minor
  657. Returns the semi minor axis of the ellipsoid for this spatial reference.
  658. .. attribute:: inverse_flattening
  659. Returns the inverse flattening of the ellipsoid for this spatial reference.
  660. .. attribute:: geographic
  661. Returns ``True`` if this spatial reference is geographic (root node is
  662. ``GEOGCS``).
  663. .. attribute:: local
  664. Returns ``True`` if this spatial reference is local (root node is
  665. ``LOCAL_CS``).
  666. .. attribute:: projected
  667. Returns ``True`` if this spatial reference is a projected coordinate system
  668. (root node is ``PROJCS``).
  669. .. attribute:: wkt
  670. Returns the WKT representation of this spatial reference.
  671. .. attribute:: pretty_wkt
  672. Returns the 'pretty' representation of the WKT.
  673. .. attribute:: proj
  674. Returns the PROJ.4 representation for this spatial reference.
  675. .. attribute:: proj4
  676. Alias for :attr:`SpatialReference.proj`.
  677. .. attribute:: xml
  678. Returns the XML representation of this spatial reference.
  679. ``CoordTransform``
  680. ------------------
  681. .. class:: CoordTransform(source, target)
  682. Represents a coordinate system transform. It is initialized with two
  683. :class:`SpatialReference`, representing the source and target coordinate
  684. systems, respectively. These objects should be used when performing the same
  685. coordinate transformation repeatedly on different geometries::
  686. >>> ct = CoordTransform(SpatialReference('WGS84'), SpatialReference('NAD83'))
  687. >>> for feat in layer:
  688. ... geom = feat.geom # getting clone of feature geometry
  689. ... geom.transform(ct) # transforming
  690. .. _raster-data-source-objects:
  691. Raster Data Objects
  692. ===================
  693. ``GDALRaster``
  694. ----------------
  695. :class:`GDALRaster` is a wrapper for the GDAL raster source object that
  696. supports reading data from a variety of GDAL-supported geospatial file
  697. formats and data sources using a simple, consistent interface. Each
  698. data source is represented by a :class:`GDALRaster` object which contains
  699. one or more layers of data named bands. Each band, represented by a
  700. :class:`GDALBand` object, contains georeferenced image data. For example, an RGB
  701. image is represented as three bands: one for red, one for green, and one for
  702. blue.
  703. .. note::
  704. For raster data there is no difference between a raster instance and its
  705. data source. Unlike for the Geometry objects, :class:`GDALRaster` objects are
  706. always a data source. Temporary rasters can be instantiated in memory
  707. using the corresponding driver, but they will be of the same class as file-based
  708. raster sources.
  709. .. class:: GDALRaster(ds_input, write=False)
  710. The constructor for ``GDALRaster`` accepts two parameters. The first parameter
  711. defines the raster source, it is either a path to a file or spatial data with
  712. values defining the properties of a new raster (such as size and name). If the
  713. input is a file path, the second parameter specifies if the raster should
  714. be opened with write access. If the input is raw data, the parameters ``width``,
  715. ``height``, and ``srid`` are required. The following example shows how rasters
  716. can be created from different input sources (using the sample data from the
  717. GeoDjango tests, see also the :ref:`gdal_sample_data` section). For a
  718. detailed description of how to create rasters using dictionary input, see
  719. the :ref:`gdal-raster-ds-input` section.
  720. >>> from django.contrib.gis.gdal import GDALRaster
  721. >>> rst = GDALRaster('/path/to/your/raster.tif', write=False)
  722. >>> rst.name
  723. '/path/to/your/raster.tif'
  724. >>> rst.width, rst.height # This file has 163 x 174 pixels
  725. (163, 174)
  726. >>> rst = GDALRaster({ # Creates an in-memory raster
  727. ... 'srid': 4326,
  728. ... 'width': 4,
  729. ... 'height': 4,
  730. ... 'datatype': 1,
  731. ... 'bands': [{
  732. ... 'data': (2, 3),
  733. ... 'offset': (1, 1),
  734. ... 'size': (2, 2),
  735. ... 'shape': (2, 1),
  736. ... 'nodata_value': 5,
  737. ... }]
  738. ... })
  739. >>> rst.srs.srid
  740. 4326
  741. >>> rst.width, rst.height
  742. (4, 4)
  743. >>> rst.bands[0].data()
  744. array([[5, 5, 5, 5],
  745. [5, 2, 3, 5],
  746. [5, 2, 3, 5],
  747. [5, 5, 5, 5]], dtype=uint8)
  748. .. versionchanged:: 1.11
  749. Added the ability to pass the ``size``, ``shape``, and ``offset``
  750. parameters when creating :class:`GDALRaster` objects. The parameters
  751. can be passed through the ``ds_input`` dictionary. This allows to
  752. finely control initial pixel values. The functionality is similar to
  753. the :meth:`GDALBand.data()<django.contrib.gis.gdal.GDALBand.data>`
  754. method.
  755. .. attribute:: name
  756. The name of the source which is equivalent to the input file path or the name
  757. provided upon instantiation.
  758. >>> GDALRaster({'width': 10, 'height': 10, 'name': 'myraster', 'srid': 4326}).name
  759. 'myraster'
  760. .. attribute:: driver
  761. The name of the GDAL driver used to handle the input file. For ``GDALRaster``\s created
  762. from a file, the driver type is detected automatically. The creation of rasters from
  763. scratch is a in-memory raster by default (``'MEM'``), but can be altered as
  764. needed. For instance, use ``GTiff`` for a ``GeoTiff`` file. For a list of file types,
  765. see also the `GDAL Raster Formats`__ list.
  766. __ http://www.gdal.org/formats_list.html
  767. An in-memory raster is created through the following example:
  768. >>> GDALRaster({'width': 10, 'height': 10, 'srid': 4326}).driver.name
  769. 'MEM'
  770. A file based GeoTiff raster is created through the following example:
  771. >>> import tempfile
  772. >>> rstfile = tempfile.NamedTemporaryFile(suffix='.tif')
  773. >>> rst = GDALRaster({'driver': 'GTiff', 'name': rstfile.name, 'srid': 4326,
  774. ... 'width': 255, 'height': 255, 'nr_of_bands': 1})
  775. >>> rst.name
  776. '/tmp/tmp7x9H4J.tif' # The exact filename will be different on your computer
  777. >>> rst.driver.name
  778. 'GTiff'
  779. .. attribute:: width
  780. The width of the source in pixels (X-axis).
  781. >>> GDALRaster({'width': 10, 'height': 20, 'srid': 4326}).width
  782. 10
  783. .. attribute:: height
  784. The height of the source in pixels (Y-axis).
  785. >>> GDALRaster({'width': 10, 'height': 20, 'srid': 4326}).height
  786. 20
  787. .. attribute:: srs
  788. The spatial reference system of the raster, as a
  789. :class:`SpatialReference` instance. The SRS can be changed by
  790. setting it to an other :class:`SpatialReference` or providing any input
  791. that is accepted by the :class:`SpatialReference` constructor.
  792. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  793. >>> rst.srs.srid
  794. 4326
  795. >>> rst.srs = 3086
  796. >>> rst.srs.srid
  797. 3086
  798. .. attribute:: srid
  799. The Spatial Reference System Identifier (SRID) of the raster. This
  800. property is a shortcut to getting or setting the SRID through the
  801. :attr:`srs` attribute.
  802. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  803. >>> rst.srid
  804. 4326
  805. >>> rst.srid = 3086
  806. >>> rst.srid
  807. 3086
  808. >>> rst.srs.srid # This is equivalent
  809. 3086
  810. .. attribute:: geotransform
  811. The affine transformation matrix used to georeference the source, as a
  812. tuple of six coefficients which map pixel/line coordinates into
  813. georeferenced space using the following relationship::
  814. Xgeo = GT(0) + Xpixel*GT(1) + Yline*GT(2)
  815. Ygeo = GT(3) + Xpixel*GT(4) + Yline*GT(5)
  816. The same values can be retrieved by accessing the :attr:`origin`
  817. (indices 0 and 3), :attr:`scale` (indices 1 and 5) and :attr:`skew`
  818. (indices 2 and 4) properties.
  819. The default is ``[0.0, 1.0, 0.0, 0.0, 0.0, -1.0]``.
  820. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  821. >>> rst.geotransform
  822. [0.0, 1.0, 0.0, 0.0, 0.0, -1.0]
  823. .. attribute:: origin
  824. Coordinates of the top left origin of the raster in the spatial
  825. reference system of the source, as a point object with ``x`` and ``y``
  826. members.
  827. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  828. >>> rst.origin
  829. [0.0, 0.0]
  830. >>> rst.origin.x = 1
  831. >>> rst.origin
  832. [1.0, 0.0]
  833. .. attribute:: scale
  834. Pixel width and height used for georeferencing the raster, as a as a
  835. point object with ``x`` and ``y`` members. See :attr:`geotransform`
  836. for more information.
  837. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  838. >>> rst.scale
  839. [1.0, -1.0]
  840. >>> rst.scale.x = 2
  841. >>> rst.scale
  842. [2.0, -1.0]
  843. .. attribute:: skew
  844. Skew coefficients used to georeference the raster, as a point object
  845. with ``x`` and ``y`` members. In case of north up images, these
  846. coefficients are both ``0``.
  847. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  848. >>> rst.skew
  849. [0.0, 0.0]
  850. >>> rst.skew.x = 3
  851. >>> rst.skew
  852. [3.0, 0.0]
  853. .. attribute:: extent
  854. Extent (boundary values) of the raster source, as a 4-tuple
  855. ``(xmin, ymin, xmax, ymax)`` in the spatial reference system of the
  856. source.
  857. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  858. >>> rst.extent
  859. (0.0, -20.0, 10.0, 0.0)
  860. >>> rst.origin.x = 100
  861. >>> rst.extent
  862. (100.0, -20.0, 110.0, 0.0)
  863. .. attribute:: bands
  864. List of all bands of the source, as :class:`GDALBand` instances.
  865. >>> rst = GDALRaster({"width": 1, "height": 2, 'srid': 4326,
  866. ... "bands": [{"data": [0, 1]}, {"data": [2, 3]}]})
  867. >>> len(rst.bands)
  868. 2
  869. >>> rst.bands[1].data()
  870. array([[ 2., 3.]], dtype=float32)
  871. .. method:: warp(ds_input, resampling='NearestNeighbour', max_error=0.0)
  872. Returns a warped version of this raster.
  873. The warping parameters can be specified through the ``ds_input``
  874. argument. The use of ``ds_input`` is analogous to the corresponding
  875. argument of the class constructor. It is a dictionary with the
  876. characteristics of the target raster. Allowed dictionary key values are
  877. width, height, SRID, origin, scale, skew, datatype, driver, and name
  878. (filename).
  879. By default, the warp functions keeps most parameters equal to the
  880. values of the original source raster, so only parameters that should be
  881. changed need to be specified. Note that this includes the driver, so
  882. for file-based rasters the warp function will create a new raster on
  883. disk.
  884. The only parameter that is set differently from the source raster is the
  885. name. The default value of the the raster name is the name of the source
  886. raster appended with ``'_copy' + source_driver_name``. For file-based
  887. rasters it is recommended to provide the file path of the target raster.
  888. The resampling algorithm used for warping can be specified with the
  889. ``resampling`` argument. The default is ``NearestNeighbor``, and the
  890. other allowed values are ``Bilinear``, ``Cubic``, ``CubicSpline``,
  891. ``Lanczos``, ``Average``, and ``Mode``.
  892. The ``max_error`` argument can be used to specify the maximum error
  893. measured in input pixels that is allowed in approximating the
  894. transformation. The default is 0.0 for exact calculations.
  895. For users familiar with ``GDAL``, this function has a similar
  896. functionality to the ``gdalwarp`` command-line utility.
  897. For example, the warp function can be used for aggregating a raster to
  898. the double of its original pixel scale:
  899. >>> rst = GDALRaster({
  900. ... "width": 6, "height": 6, "srid": 3086,
  901. ... "origin": [500000, 400000],
  902. ... "scale": [100, -100],
  903. ... "bands": [{"data": range(36), "nodata_value": 99}]
  904. ... })
  905. >>> target = rst.warp({"scale": [200, -200], "width": 3, "height": 3})
  906. >>> target.bands[0].data()
  907. array([[ 7., 9., 11.],
  908. [ 19., 21., 23.],
  909. [ 31., 33., 35.]], dtype=float32)
  910. .. method:: transform(srid, driver=None, name=None, resampling='NearestNeighbour', max_error=0.0)
  911. Returns a transformed version of this raster with the specified SRID.
  912. This function transforms the current raster into a new spatial reference
  913. system that can be specified with an ``srid``. It calculates the bounds
  914. and scale of the current raster in the new spatial reference system and
  915. warps the raster using the :attr:`~GDALRaster.warp` function.
  916. By default, the driver of the source raster is used and the name of the
  917. raster is the original name appended with
  918. ``'_copy' + source_driver_name``. A different driver or name can be
  919. specified with the ``driver`` and ``name`` arguments.
  920. The default resampling algorithm is ``NearestNeighbour`` but can be
  921. changed using the ``resampling`` argument. The default maximum allowed
  922. error for resampling is 0.0 and can be changed using the ``max_error``
  923. argument. Consult the :attr:`~GDALRaster.warp` documentation for detail
  924. on those arguments.
  925. >>> rst = GDALRaster({
  926. ... "width": 6, "height": 6, "srid": 3086,
  927. ... "origin": [500000, 400000],
  928. ... "scale": [100, -100],
  929. ... "bands": [{"data": range(36), "nodata_value": 99}]
  930. ... })
  931. >>> target = rst.transform(4326)
  932. >>> target.origin
  933. [-82.98492744885776, 27.601924753080144]
  934. .. attribute:: info
  935. .. versionadded:: 2.0
  936. Returns a string with a summary of the raster. This is equivalent to
  937. the `gdalinfo`__ command line utility.
  938. __ http://www.gdal.org/gdalinfo.html
  939. .. attribute:: metadata
  940. .. versionadded:: 2.0
  941. The metadata of this raster, represented as a nested dictionary. The
  942. first-level key is the metadata domain. The second-level contains the
  943. metadata item names and values from each domain.
  944. To set or update a metadata item, pass the corresponding metadata item
  945. to the method using the nested structure described above. Only keys
  946. that are in the specified dictionary are updated; the rest of the
  947. metadata remains unchanged.
  948. To remove a metadata item, use ``None`` as the metadata value.
  949. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  950. >>> rst.metadata
  951. {}
  952. >>> rst.metadata = {'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0'}}
  953. >>> rst.metadata
  954. {'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0'}}
  955. >>> rst.metadata = {'DEFAULT': {'OWNER': None, 'VERSION': '2.0'}}
  956. >>> rst.metadata
  957. {'DEFAULT': {'VERSION': '2.0'}}
  958. ``GDALBand``
  959. ------------
  960. .. class:: GDALBand
  961. ``GDALBand`` instances are not created explicitly, but rather obtained
  962. from a :class:`GDALRaster` object, through its :attr:`~GDALRaster.bands`
  963. attribute. The GDALBands contain the actual pixel values of the raster.
  964. .. attribute:: description
  965. The name or description of the band, if any.
  966. .. attribute:: width
  967. The width of the band in pixels (X-axis).
  968. .. attribute:: height
  969. The height of the band in pixels (Y-axis).
  970. .. attribute:: pixel_count
  971. The total number of pixels in this band. Is equal to ``width * height``.
  972. .. method:: statistics(refresh=False, approximate=False)
  973. Compute statistics on the pixel values of this band. The return value
  974. is a tuple with the following structure:
  975. ``(minimum, maximum, mean, standard deviation)``.
  976. If the ``approximate`` argument is set to ``True``, the statistics may
  977. be computed based on overviews or a subset of image tiles.
  978. If the ``refresh`` argument is set to ``True``, the statistics will be
  979. computed from the data directly, and the cache will be updated with the
  980. result.
  981. If a persistent cache value is found, that value is returned. For
  982. raster formats using Persistent Auxiliary Metadata (PAM) services, the
  983. statistics might be cached in an auxiliary file. In some cases this
  984. metadata might be out of sync with the pixel values or cause values
  985. from a previous call to be returned which don't reflect the value of
  986. the ``approximate`` argument. In such cases, use the ``refresh``
  987. argument to get updated values and store them in the cache.
  988. For empty bands (where all pixel values are "no data"), all statistics
  989. are returned as ``None``.
  990. The statistics can also be retrieved directly by accessing the
  991. :attr:`min`, :attr:`max`, :attr:`mean`, and :attr:`std` properties.
  992. .. attribute:: min
  993. The minimum pixel value of the band (excluding the "no data" value).
  994. .. attribute:: max
  995. The maximum pixel value of the band (excluding the "no data" value).
  996. .. attribute:: mean
  997. The mean of all pixel values of the band (excluding the "no data"
  998. value).
  999. .. attribute:: std
  1000. The standard deviation of all pixel values of the band (excluding the
  1001. "no data" value).
  1002. .. attribute:: nodata_value
  1003. The "no data" value for a band is generally a special marker value used
  1004. to mark pixels that are not valid data. Such pixels should generally not
  1005. be displayed, nor contribute to analysis operations.
  1006. To delete an existing "no data" value, set this property to ``None``
  1007. (requires GDAL ≥ 2.1).
  1008. .. method:: datatype(as_string=False)
  1009. The data type contained in the band, as an integer constant between 0
  1010. (Unknown) and 11. If ``as_string`` is ``True``, the data type is
  1011. returned as a string with the following possible values:
  1012. ``GDT_Unknown``, ``GDT_Byte``, ``GDT_UInt16``, ``GDT_Int16``,
  1013. ``GDT_UInt32``, ``GDT_Int32``, ``GDT_Float32``, ``GDT_Float64``,
  1014. ``GDT_CInt16``, ``GDT_CInt32``, ``GDT_CFloat32``, and ``GDT_CFloat64``.
  1015. .. method:: data(data=None, offset=None, size=None, shape=None)
  1016. The accessor to the pixel values of the ``GDALBand``. Returns the complete
  1017. data array if no parameters are provided. A subset of the pixel array can
  1018. be requested by specifying an offset and block size as tuples.
  1019. If NumPy is available, the data is returned as NumPy array. For performance
  1020. reasons, it is highly recommended to use NumPy.
  1021. Data is written to the ``GDALBand`` if the ``data`` parameter is provided.
  1022. The input can be of one of the following types - packed string, buffer, list,
  1023. array, and NumPy array. The number of items in the input should normally
  1024. correspond to the total number of pixels in the band, or to the number
  1025. of pixels for a specific block of pixel values if the ``offset`` and
  1026. ``size`` parameters are provided.
  1027. If the number of items in the input is different from the target pixel
  1028. block, the ``shape`` parameter must be specified. The shape is a tuple
  1029. that specifies the width and height of the input data in pixels. The
  1030. data is then replicated to update the pixel values of the selected
  1031. block. This is useful to fill an entire band with a single value, for
  1032. instance.
  1033. For example:
  1034. >>> rst = GDALRaster({'width': 4, 'height': 4, 'srid': 4326, 'datatype': 1, 'nr_of_bands': 1})
  1035. >>> bnd = rst.bands[0]
  1036. >>> bnd.data(range(16))
  1037. >>> bnd.data()
  1038. array([[ 0, 1, 2, 3],
  1039. [ 4, 5, 6, 7],
  1040. [ 8, 9, 10, 11],
  1041. [12, 13, 14, 15]], dtype=int8)
  1042. >>> bnd.data(offset=(1, 1), size=(2, 2))
  1043. array([[ 5, 6],
  1044. [ 9, 10]], dtype=int8)
  1045. >>> bnd.data(data=[-1, -2, -3, -4], offset=(1, 1), size=(2, 2))
  1046. >>> bnd.data()
  1047. array([[ 0, 1, 2, 3],
  1048. [ 4, -1, -2, 7],
  1049. [ 8, -3, -4, 11],
  1050. [12, 13, 14, 15]], dtype=int8)
  1051. >>> bnd.data(data='\x9d\xa8\xb3\xbe', offset=(1, 1), size=(2, 2))
  1052. >>> bnd.data()
  1053. array([[ 0, 1, 2, 3],
  1054. [ 4, -99, -88, 7],
  1055. [ 8, -77, -66, 11],
  1056. [ 12, 13, 14, 15]], dtype=int8)
  1057. >>> bnd.data([1], shape=(1, 1))
  1058. >>> bnd.data()
  1059. array([[1, 1, 1, 1],
  1060. [1, 1, 1, 1],
  1061. [1, 1, 1, 1],
  1062. [1, 1, 1, 1]], dtype=uint8)
  1063. >>> bnd.data(range(4), shape=(1, 4))
  1064. array([[0, 0, 0, 0],
  1065. [1, 1, 1, 1],
  1066. [2, 2, 2, 2],
  1067. [3, 3, 3, 3]], dtype=uint8)
  1068. .. attribute:: metadata
  1069. .. versionadded:: 2.0
  1070. The metadata of this band. The functionality is identical to
  1071. :attr:`GDALRaster.metadata`.
  1072. .. _gdal-raster-ds-input:
  1073. Creating rasters from data
  1074. --------------------------
  1075. This section describes how to create rasters from scratch using the
  1076. ``ds_input`` parameter.
  1077. A new raster is created when a ``dict`` is passed to the :class:`GDALRaster`
  1078. constructor. The dictionary contains defining parameters of the new raster,
  1079. such as the origin, size, or spatial reference system. The dictionary can also
  1080. contain pixel data and information about the format of the new raster. The
  1081. resulting raster can therefore be file-based or memory-based, depending on the
  1082. driver specified.
  1083. There's no standard for describing raster data in a dictionary or JSON flavor.
  1084. The definition of the dictionary input to the :class:`GDALRaster` class is
  1085. therefore specific to Django. It's inspired by the `geojson`__ format, but the
  1086. ``geojson`` standard is currently limited to vector formats.
  1087. Examples of using the different keys when creating rasters can be found in the
  1088. documentation of the corresponding attributes and methods of the
  1089. :class:`GDALRaster` and :class:`GDALBand` classes.
  1090. __ http://geojson.org
  1091. The ``ds_input`` dictionary
  1092. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1093. Only a few keys are required in the ``ds_input`` dictionary to create a raster:
  1094. ``width``, ``height``, and ``srid``. All other parameters have default values
  1095. (see the table below). The list of keys that can be passed in the ``ds_input``
  1096. dictionary is closely related but not identical to the :class:`GDALRaster`
  1097. properties. Many of the parameters are mapped directly to those properties;
  1098. the others are described below.
  1099. The following table describes all keys that can be set in the ``ds_input``
  1100. dictionary.
  1101. ================= ======== ==================================================
  1102. Key Default Usage
  1103. ================= ======== ==================================================
  1104. ``srid`` required Mapped to the :attr:`~GDALRaster.srid` attribute
  1105. ``width`` required Mapped to the :attr:`~GDALRaster.width` attribute
  1106. ``height`` required Mapped to the :attr:`~GDALRaster.height` attribute
  1107. ``driver`` ``MEM`` Mapped to the :attr:`~GDALRaster.driver` attribute
  1108. ``name`` ``''`` See below
  1109. ``origin`` ``0`` Mapped to the :attr:`~GDALRaster.origin` attribute
  1110. ``scale`` ``0`` Mapped to the :attr:`~GDALRaster.scale` attribute
  1111. ``skew`` ``0`` Mapped to the :attr:`~GDALRaster.width` attribute
  1112. ``bands`` ``[]`` See below
  1113. ``nr_of_bands`` ``0`` See below
  1114. ``datatype`` ``6`` See below
  1115. ``papsz_options`` ``{}`` See below
  1116. ================= ======== ==================================================
  1117. .. object:: name
  1118. String representing the name of the raster. When creating a file-based
  1119. raster, this parameter must be the file path for the new raster.
  1120. .. object:: datatype
  1121. Integer representing the data type for all the bands. Defaults to ``6``
  1122. (Float32). All bands of a new raster are required to have the same datatype.
  1123. The value mapping is:
  1124. ===== =============== ===============================
  1125. Value GDAL Pixel Type Description
  1126. ===== =============== ===============================
  1127. 1 GDT_Byte Eight bit unsigned integer
  1128. 2 GDT_UInt16 Sixteen bit unsigned integer
  1129. 3 GDT_Int16 Sixteen bit signed integer
  1130. 4 GDT_UInt32 Thirty-two bit unsigned integer
  1131. 5 GDT_Int32 Thirty-two bit signed integer
  1132. 6 GDT_Float32 Thirty-two bit floating point
  1133. 7 GDT_Float64 Sixty-four bit floating point
  1134. ===== =============== ===============================
  1135. .. object:: nr_of_bands
  1136. Integer representing the number of bands of the raster. A raster can be
  1137. created without passing band data upon creation. If the number of bands
  1138. isn't specified, it's automatically calculated from the length of the
  1139. ``bands`` input. The number of bands can't be changed after creation.
  1140. .. object:: bands
  1141. A list of ``band_input`` dictionaries with band input data. The resulting
  1142. band indices are the same as in the list provided. The definition of the
  1143. band input dictionary is given below. If band data isn't provided, the
  1144. raster bands values are instantiated as an array of zeros and the "no
  1145. data" value is set to ``None``.
  1146. .. object:: papsz_options
  1147. .. versionadded:: 2.0
  1148. A dictionary with raster creation options. The key-value pairs of the
  1149. input dictionary are passed to the driver on creation of the raster.
  1150. The available options are driver-specific and are described in the
  1151. documentation of each driver.
  1152. The values in the dictionary are not case-sensitive and are automatically
  1153. converted to the correct string format upon creation.
  1154. The following example uses some of the options available for the
  1155. `GTiff driver`__. The result is a compressed signed byte raster with an
  1156. internal tiling scheme. The internal tiles have a block size of 23 by 23::
  1157. >>> GDALRaster({
  1158. ... 'driver': 'GTiff',
  1159. ... 'name': '/path/to/new/file.tif',
  1160. ... 'srid': 4326,
  1161. ... 'width': 255,
  1162. ... 'height': 255,
  1163. ... 'nr_of_bands': 1,
  1164. ... 'papsz_options': {
  1165. ... 'compress': 'packbits',
  1166. ... 'pixeltype': 'signedbyte',
  1167. ... 'tiled': 'yes',
  1168. ... 'blockxsize': 23,
  1169. ... 'blockysize': 23,
  1170. ... }
  1171. ... })
  1172. __ http://www.gdal.org/frmt_gtiff.html
  1173. The ``band_input`` dictionary
  1174. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1175. The ``bands`` key in the ``ds_input`` dictionary is a list of ``band_input``
  1176. dictionaries. Each ``band_input`` dictionary can contain pixel values and the
  1177. "no data" value to be set on the bands of the new raster. The data array can
  1178. have the full size of the new raster or be smaller. For arrays that are smaller
  1179. than the full raster, the ``size``, ``shape``, and ``offset`` keys control the
  1180. pixel values. The corresponding keys are passed to the :meth:`~GDALBand.data`
  1181. method. Their functionality is the same as setting the band data with that
  1182. method. The following table describes the keys that can be used.
  1183. ================ ================================= ======================================================
  1184. Key Default Usage
  1185. ================ ================================= ======================================================
  1186. ``nodata_value`` ``None`` Mapped to the :attr:`~GDALBand.nodata_value` attribute
  1187. ``data`` Same as ``nodata_value`` or ``0`` Passed to the :meth:`~GDALBand.data` method
  1188. ``size`` ``(with, height)`` of raster Passed to the :meth:`~GDALBand.data` method
  1189. ``shape`` Same as size Passed to the :meth:`~GDALBand.data` method
  1190. ``offset`` ``(0, 0)`` Passed to the :meth:`~GDALBand.data` method
  1191. ================ ================================= ======================================================
  1192. Settings
  1193. ========
  1194. .. setting:: GDAL_LIBRARY_PATH
  1195. ``GDAL_LIBRARY_PATH``
  1196. ---------------------
  1197. A string specifying the location of the GDAL library. Typically,
  1198. this setting is only used if the GDAL library is in a non-standard
  1199. location (e.g., ``/home/john/lib/libgdal.so``).