gdal.txt 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846
  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
  711. parameter defines the raster source, and the second parameter defines if a
  712. raster should be opened in write mode. For newly-created rasters, the second
  713. parameter is ignored and the new raster is always created in write mode.
  714. The first parameter can take three forms: a string representing a file
  715. path, a dictionary with values defining a new raster, or a bytes object
  716. representing a raster file.
  717. If the input is a file path, the raster is opened from there. If the input
  718. is raw data in a dictionary, the parameters ``width``, ``height``, and
  719. ``srid`` are required. If the input is a bytes object, it will be opened
  720. using a GDAL virtual filesystem.
  721. For a detailed description of how to create rasters using dictionary input,
  722. see :ref:`gdal-raster-ds-input`. For a detailed description of how to
  723. create rasters in the virtual filesystem, see :ref:`gdal-raster-vsimem`.
  724. The following example shows how rasters can be created from different input
  725. sources (using the sample data from the GeoDjango tests; see also the
  726. :ref:`gdal_sample_data` section).
  727. >>> from django.contrib.gis.gdal import GDALRaster
  728. >>> rst = GDALRaster('/path/to/your/raster.tif', write=False)
  729. >>> rst.name
  730. '/path/to/your/raster.tif'
  731. >>> rst.width, rst.height # This file has 163 x 174 pixels
  732. (163, 174)
  733. >>> rst = GDALRaster({ # Creates an in-memory raster
  734. ... 'srid': 4326,
  735. ... 'width': 4,
  736. ... 'height': 4,
  737. ... 'datatype': 1,
  738. ... 'bands': [{
  739. ... 'data': (2, 3),
  740. ... 'offset': (1, 1),
  741. ... 'size': (2, 2),
  742. ... 'shape': (2, 1),
  743. ... 'nodata_value': 5,
  744. ... }]
  745. ... })
  746. >>> rst.srs.srid
  747. 4326
  748. >>> rst.width, rst.height
  749. (4, 4)
  750. >>> rst.bands[0].data()
  751. array([[5, 5, 5, 5],
  752. [5, 2, 3, 5],
  753. [5, 2, 3, 5],
  754. [5, 5, 5, 5]], dtype=uint8)
  755. >>> rst_file = open('/path/to/your/raster.tif', 'rb')
  756. >>> rst_bytes = rst_file.read()
  757. >>> rst = GDALRaster(rst_bytes)
  758. >>> rst.is_vsi_based
  759. True
  760. >>> rst.name # Stored in a random path in the vsimem filesystem.
  761. '/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'
  762. .. versionchanged:: 1.11
  763. Added the ability to pass the ``size``, ``shape``, and ``offset``
  764. parameters when creating :class:`GDALRaster` objects. The parameters
  765. can be passed through the ``ds_input`` dictionary. This allows to
  766. finely control initial pixel values. The functionality is similar to
  767. the :meth:`GDALBand.data()<django.contrib.gis.gdal.GDALBand.data>`
  768. method.
  769. .. versionchanged:: 2.0
  770. Added the ability to read and write rasters in GDAL's memory-based
  771. virtual filesystem. ``GDALRaster`` objects can now be converted to and
  772. from binary data in-memory.
  773. .. attribute:: name
  774. The name of the source which is equivalent to the input file path or the name
  775. provided upon instantiation.
  776. >>> GDALRaster({'width': 10, 'height': 10, 'name': 'myraster', 'srid': 4326}).name
  777. 'myraster'
  778. .. attribute:: driver
  779. The name of the GDAL driver used to handle the input file. For ``GDALRaster``\s created
  780. from a file, the driver type is detected automatically. The creation of rasters from
  781. scratch is a in-memory raster by default (``'MEM'``), but can be altered as
  782. needed. For instance, use ``GTiff`` for a ``GeoTiff`` file. For a list of file types,
  783. see also the `GDAL Raster Formats`__ list.
  784. __ http://www.gdal.org/formats_list.html
  785. An in-memory raster is created through the following example:
  786. >>> GDALRaster({'width': 10, 'height': 10, 'srid': 4326}).driver.name
  787. 'MEM'
  788. A file based GeoTiff raster is created through the following example:
  789. >>> import tempfile
  790. >>> rstfile = tempfile.NamedTemporaryFile(suffix='.tif')
  791. >>> rst = GDALRaster({'driver': 'GTiff', 'name': rstfile.name, 'srid': 4326,
  792. ... 'width': 255, 'height': 255, 'nr_of_bands': 1})
  793. >>> rst.name
  794. '/tmp/tmp7x9H4J.tif' # The exact filename will be different on your computer
  795. >>> rst.driver.name
  796. 'GTiff'
  797. .. attribute:: width
  798. The width of the source in pixels (X-axis).
  799. >>> GDALRaster({'width': 10, 'height': 20, 'srid': 4326}).width
  800. 10
  801. .. attribute:: height
  802. The height of the source in pixels (Y-axis).
  803. >>> GDALRaster({'width': 10, 'height': 20, 'srid': 4326}).height
  804. 20
  805. .. attribute:: srs
  806. The spatial reference system of the raster, as a
  807. :class:`SpatialReference` instance. The SRS can be changed by
  808. setting it to an other :class:`SpatialReference` or providing any input
  809. that is accepted by the :class:`SpatialReference` constructor.
  810. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  811. >>> rst.srs.srid
  812. 4326
  813. >>> rst.srs = 3086
  814. >>> rst.srs.srid
  815. 3086
  816. .. attribute:: srid
  817. The Spatial Reference System Identifier (SRID) of the raster. This
  818. property is a shortcut to getting or setting the SRID through the
  819. :attr:`srs` attribute.
  820. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  821. >>> rst.srid
  822. 4326
  823. >>> rst.srid = 3086
  824. >>> rst.srid
  825. 3086
  826. >>> rst.srs.srid # This is equivalent
  827. 3086
  828. .. attribute:: geotransform
  829. The affine transformation matrix used to georeference the source, as a
  830. tuple of six coefficients which map pixel/line coordinates into
  831. georeferenced space using the following relationship::
  832. Xgeo = GT(0) + Xpixel*GT(1) + Yline*GT(2)
  833. Ygeo = GT(3) + Xpixel*GT(4) + Yline*GT(5)
  834. The same values can be retrieved by accessing the :attr:`origin`
  835. (indices 0 and 3), :attr:`scale` (indices 1 and 5) and :attr:`skew`
  836. (indices 2 and 4) properties.
  837. The default is ``[0.0, 1.0, 0.0, 0.0, 0.0, -1.0]``.
  838. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  839. >>> rst.geotransform
  840. [0.0, 1.0, 0.0, 0.0, 0.0, -1.0]
  841. .. attribute:: origin
  842. Coordinates of the top left origin of the raster in the spatial
  843. reference system of the source, as a point object with ``x`` and ``y``
  844. members.
  845. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  846. >>> rst.origin
  847. [0.0, 0.0]
  848. >>> rst.origin.x = 1
  849. >>> rst.origin
  850. [1.0, 0.0]
  851. .. attribute:: scale
  852. Pixel width and height used for georeferencing the raster, as a as a
  853. point object with ``x`` and ``y`` members. See :attr:`geotransform`
  854. for more information.
  855. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  856. >>> rst.scale
  857. [1.0, -1.0]
  858. >>> rst.scale.x = 2
  859. >>> rst.scale
  860. [2.0, -1.0]
  861. .. attribute:: skew
  862. Skew coefficients used to georeference the raster, as a point object
  863. with ``x`` and ``y`` members. In case of north up images, these
  864. coefficients are both ``0``.
  865. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  866. >>> rst.skew
  867. [0.0, 0.0]
  868. >>> rst.skew.x = 3
  869. >>> rst.skew
  870. [3.0, 0.0]
  871. .. attribute:: extent
  872. Extent (boundary values) of the raster source, as a 4-tuple
  873. ``(xmin, ymin, xmax, ymax)`` in the spatial reference system of the
  874. source.
  875. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  876. >>> rst.extent
  877. (0.0, -20.0, 10.0, 0.0)
  878. >>> rst.origin.x = 100
  879. >>> rst.extent
  880. (100.0, -20.0, 110.0, 0.0)
  881. .. attribute:: bands
  882. List of all bands of the source, as :class:`GDALBand` instances.
  883. >>> rst = GDALRaster({"width": 1, "height": 2, 'srid': 4326,
  884. ... "bands": [{"data": [0, 1]}, {"data": [2, 3]}]})
  885. >>> len(rst.bands)
  886. 2
  887. >>> rst.bands[1].data()
  888. array([[ 2., 3.]], dtype=float32)
  889. .. method:: warp(ds_input, resampling='NearestNeighbour', max_error=0.0)
  890. Returns a warped version of this raster.
  891. The warping parameters can be specified through the ``ds_input``
  892. argument. The use of ``ds_input`` is analogous to the corresponding
  893. argument of the class constructor. It is a dictionary with the
  894. characteristics of the target raster. Allowed dictionary key values are
  895. width, height, SRID, origin, scale, skew, datatype, driver, and name
  896. (filename).
  897. By default, the warp functions keeps most parameters equal to the
  898. values of the original source raster, so only parameters that should be
  899. changed need to be specified. Note that this includes the driver, so
  900. for file-based rasters the warp function will create a new raster on
  901. disk.
  902. The only parameter that is set differently from the source raster is the
  903. name. The default value of the the raster name is the name of the source
  904. raster appended with ``'_copy' + source_driver_name``. For file-based
  905. rasters it is recommended to provide the file path of the target raster.
  906. The resampling algorithm used for warping can be specified with the
  907. ``resampling`` argument. The default is ``NearestNeighbor``, and the
  908. other allowed values are ``Bilinear``, ``Cubic``, ``CubicSpline``,
  909. ``Lanczos``, ``Average``, and ``Mode``.
  910. The ``max_error`` argument can be used to specify the maximum error
  911. measured in input pixels that is allowed in approximating the
  912. transformation. The default is 0.0 for exact calculations.
  913. For users familiar with ``GDAL``, this function has a similar
  914. functionality to the ``gdalwarp`` command-line utility.
  915. For example, the warp function can be used for aggregating a raster to
  916. the double of its original pixel scale:
  917. >>> rst = GDALRaster({
  918. ... "width": 6, "height": 6, "srid": 3086,
  919. ... "origin": [500000, 400000],
  920. ... "scale": [100, -100],
  921. ... "bands": [{"data": range(36), "nodata_value": 99}]
  922. ... })
  923. >>> target = rst.warp({"scale": [200, -200], "width": 3, "height": 3})
  924. >>> target.bands[0].data()
  925. array([[ 7., 9., 11.],
  926. [ 19., 21., 23.],
  927. [ 31., 33., 35.]], dtype=float32)
  928. .. method:: transform(srid, driver=None, name=None, resampling='NearestNeighbour', max_error=0.0)
  929. Returns a transformed version of this raster with the specified SRID.
  930. This function transforms the current raster into a new spatial reference
  931. system that can be specified with an ``srid``. It calculates the bounds
  932. and scale of the current raster in the new spatial reference system and
  933. warps the raster using the :attr:`~GDALRaster.warp` function.
  934. By default, the driver of the source raster is used and the name of the
  935. raster is the original name appended with
  936. ``'_copy' + source_driver_name``. A different driver or name can be
  937. specified with the ``driver`` and ``name`` arguments.
  938. The default resampling algorithm is ``NearestNeighbour`` but can be
  939. changed using the ``resampling`` argument. The default maximum allowed
  940. error for resampling is 0.0 and can be changed using the ``max_error``
  941. argument. Consult the :attr:`~GDALRaster.warp` documentation for detail
  942. on those arguments.
  943. >>> rst = GDALRaster({
  944. ... "width": 6, "height": 6, "srid": 3086,
  945. ... "origin": [500000, 400000],
  946. ... "scale": [100, -100],
  947. ... "bands": [{"data": range(36), "nodata_value": 99}]
  948. ... })
  949. >>> target = rst.transform(4326)
  950. >>> target.origin
  951. [-82.98492744885776, 27.601924753080144]
  952. .. attribute:: info
  953. .. versionadded:: 2.0
  954. Returns a string with a summary of the raster. This is equivalent to
  955. the `gdalinfo`__ command line utility.
  956. __ http://www.gdal.org/gdalinfo.html
  957. .. attribute:: metadata
  958. .. versionadded:: 2.0
  959. The metadata of this raster, represented as a nested dictionary. The
  960. first-level key is the metadata domain. The second-level contains the
  961. metadata item names and values from each domain.
  962. To set or update a metadata item, pass the corresponding metadata item
  963. to the method using the nested structure described above. Only keys
  964. that are in the specified dictionary are updated; the rest of the
  965. metadata remains unchanged.
  966. To remove a metadata item, use ``None`` as the metadata value.
  967. >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
  968. >>> rst.metadata
  969. {}
  970. >>> rst.metadata = {'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0'}}
  971. >>> rst.metadata
  972. {'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0'}}
  973. >>> rst.metadata = {'DEFAULT': {'OWNER': None, 'VERSION': '2.0'}}
  974. >>> rst.metadata
  975. {'DEFAULT': {'VERSION': '2.0'}}
  976. .. attribute:: vsi_buffer
  977. .. versionadded:: 2.0
  978. A ``bytes`` representation of this raster. Returns ``None`` for rasters
  979. that are not stored in GDAL's virtual filesystem.
  980. .. attribute:: is_vsi_based
  981. .. versionadded:: 2.0
  982. A boolean indicating if this raster is stored in GDAL's virtual
  983. filesystem.
  984. ``GDALBand``
  985. ------------
  986. .. class:: GDALBand
  987. ``GDALBand`` instances are not created explicitly, but rather obtained
  988. from a :class:`GDALRaster` object, through its :attr:`~GDALRaster.bands`
  989. attribute. The GDALBands contain the actual pixel values of the raster.
  990. .. attribute:: description
  991. The name or description of the band, if any.
  992. .. attribute:: width
  993. The width of the band in pixels (X-axis).
  994. .. attribute:: height
  995. The height of the band in pixels (Y-axis).
  996. .. attribute:: pixel_count
  997. The total number of pixels in this band. Is equal to ``width * height``.
  998. .. method:: statistics(refresh=False, approximate=False)
  999. Compute statistics on the pixel values of this band. The return value
  1000. is a tuple with the following structure:
  1001. ``(minimum, maximum, mean, standard deviation)``.
  1002. If the ``approximate`` argument is set to ``True``, the statistics may
  1003. be computed based on overviews or a subset of image tiles.
  1004. If the ``refresh`` argument is set to ``True``, the statistics will be
  1005. computed from the data directly, and the cache will be updated with the
  1006. result.
  1007. If a persistent cache value is found, that value is returned. For
  1008. raster formats using Persistent Auxiliary Metadata (PAM) services, the
  1009. statistics might be cached in an auxiliary file. In some cases this
  1010. metadata might be out of sync with the pixel values or cause values
  1011. from a previous call to be returned which don't reflect the value of
  1012. the ``approximate`` argument. In such cases, use the ``refresh``
  1013. argument to get updated values and store them in the cache.
  1014. For empty bands (where all pixel values are "no data"), all statistics
  1015. are returned as ``None``.
  1016. The statistics can also be retrieved directly by accessing the
  1017. :attr:`min`, :attr:`max`, :attr:`mean`, and :attr:`std` properties.
  1018. .. attribute:: min
  1019. The minimum pixel value of the band (excluding the "no data" value).
  1020. .. attribute:: max
  1021. The maximum pixel value of the band (excluding the "no data" value).
  1022. .. attribute:: mean
  1023. The mean of all pixel values of the band (excluding the "no data"
  1024. value).
  1025. .. attribute:: std
  1026. The standard deviation of all pixel values of the band (excluding the
  1027. "no data" value).
  1028. .. attribute:: nodata_value
  1029. The "no data" value for a band is generally a special marker value used
  1030. to mark pixels that are not valid data. Such pixels should generally not
  1031. be displayed, nor contribute to analysis operations.
  1032. To delete an existing "no data" value, set this property to ``None``
  1033. (requires GDAL ≥ 2.1).
  1034. .. method:: datatype(as_string=False)
  1035. The data type contained in the band, as an integer constant between 0
  1036. (Unknown) and 11. If ``as_string`` is ``True``, the data type is
  1037. returned as a string with the following possible values:
  1038. ``GDT_Unknown``, ``GDT_Byte``, ``GDT_UInt16``, ``GDT_Int16``,
  1039. ``GDT_UInt32``, ``GDT_Int32``, ``GDT_Float32``, ``GDT_Float64``,
  1040. ``GDT_CInt16``, ``GDT_CInt32``, ``GDT_CFloat32``, and ``GDT_CFloat64``.
  1041. .. method:: data(data=None, offset=None, size=None, shape=None)
  1042. The accessor to the pixel values of the ``GDALBand``. Returns the complete
  1043. data array if no parameters are provided. A subset of the pixel array can
  1044. be requested by specifying an offset and block size as tuples.
  1045. If NumPy is available, the data is returned as NumPy array. For performance
  1046. reasons, it is highly recommended to use NumPy.
  1047. Data is written to the ``GDALBand`` if the ``data`` parameter is provided.
  1048. The input can be of one of the following types - packed string, buffer, list,
  1049. array, and NumPy array. The number of items in the input should normally
  1050. correspond to the total number of pixels in the band, or to the number
  1051. of pixels for a specific block of pixel values if the ``offset`` and
  1052. ``size`` parameters are provided.
  1053. If the number of items in the input is different from the target pixel
  1054. block, the ``shape`` parameter must be specified. The shape is a tuple
  1055. that specifies the width and height of the input data in pixels. The
  1056. data is then replicated to update the pixel values of the selected
  1057. block. This is useful to fill an entire band with a single value, for
  1058. instance.
  1059. For example:
  1060. >>> rst = GDALRaster({'width': 4, 'height': 4, 'srid': 4326, 'datatype': 1, 'nr_of_bands': 1})
  1061. >>> bnd = rst.bands[0]
  1062. >>> bnd.data(range(16))
  1063. >>> bnd.data()
  1064. array([[ 0, 1, 2, 3],
  1065. [ 4, 5, 6, 7],
  1066. [ 8, 9, 10, 11],
  1067. [12, 13, 14, 15]], dtype=int8)
  1068. >>> bnd.data(offset=(1, 1), size=(2, 2))
  1069. array([[ 5, 6],
  1070. [ 9, 10]], dtype=int8)
  1071. >>> bnd.data(data=[-1, -2, -3, -4], offset=(1, 1), size=(2, 2))
  1072. >>> bnd.data()
  1073. array([[ 0, 1, 2, 3],
  1074. [ 4, -1, -2, 7],
  1075. [ 8, -3, -4, 11],
  1076. [12, 13, 14, 15]], dtype=int8)
  1077. >>> bnd.data(data='\x9d\xa8\xb3\xbe', offset=(1, 1), size=(2, 2))
  1078. >>> bnd.data()
  1079. array([[ 0, 1, 2, 3],
  1080. [ 4, -99, -88, 7],
  1081. [ 8, -77, -66, 11],
  1082. [ 12, 13, 14, 15]], dtype=int8)
  1083. >>> bnd.data([1], shape=(1, 1))
  1084. >>> bnd.data()
  1085. array([[1, 1, 1, 1],
  1086. [1, 1, 1, 1],
  1087. [1, 1, 1, 1],
  1088. [1, 1, 1, 1]], dtype=uint8)
  1089. >>> bnd.data(range(4), shape=(1, 4))
  1090. array([[0, 0, 0, 0],
  1091. [1, 1, 1, 1],
  1092. [2, 2, 2, 2],
  1093. [3, 3, 3, 3]], dtype=uint8)
  1094. .. attribute:: metadata
  1095. .. versionadded:: 2.0
  1096. The metadata of this band. The functionality is identical to
  1097. :attr:`GDALRaster.metadata`.
  1098. .. _gdal-raster-ds-input:
  1099. Creating rasters from data
  1100. --------------------------
  1101. This section describes how to create rasters from scratch using the
  1102. ``ds_input`` parameter.
  1103. A new raster is created when a ``dict`` is passed to the :class:`GDALRaster`
  1104. constructor. The dictionary contains defining parameters of the new raster,
  1105. such as the origin, size, or spatial reference system. The dictionary can also
  1106. contain pixel data and information about the format of the new raster. The
  1107. resulting raster can therefore be file-based or memory-based, depending on the
  1108. driver specified.
  1109. There's no standard for describing raster data in a dictionary or JSON flavor.
  1110. The definition of the dictionary input to the :class:`GDALRaster` class is
  1111. therefore specific to Django. It's inspired by the `geojson`__ format, but the
  1112. ``geojson`` standard is currently limited to vector formats.
  1113. Examples of using the different keys when creating rasters can be found in the
  1114. documentation of the corresponding attributes and methods of the
  1115. :class:`GDALRaster` and :class:`GDALBand` classes.
  1116. __ http://geojson.org
  1117. The ``ds_input`` dictionary
  1118. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1119. Only a few keys are required in the ``ds_input`` dictionary to create a raster:
  1120. ``width``, ``height``, and ``srid``. All other parameters have default values
  1121. (see the table below). The list of keys that can be passed in the ``ds_input``
  1122. dictionary is closely related but not identical to the :class:`GDALRaster`
  1123. properties. Many of the parameters are mapped directly to those properties;
  1124. the others are described below.
  1125. The following table describes all keys that can be set in the ``ds_input``
  1126. dictionary.
  1127. ================= ======== ==================================================
  1128. Key Default Usage
  1129. ================= ======== ==================================================
  1130. ``srid`` required Mapped to the :attr:`~GDALRaster.srid` attribute
  1131. ``width`` required Mapped to the :attr:`~GDALRaster.width` attribute
  1132. ``height`` required Mapped to the :attr:`~GDALRaster.height` attribute
  1133. ``driver`` ``MEM`` Mapped to the :attr:`~GDALRaster.driver` attribute
  1134. ``name`` ``''`` See below
  1135. ``origin`` ``0`` Mapped to the :attr:`~GDALRaster.origin` attribute
  1136. ``scale`` ``0`` Mapped to the :attr:`~GDALRaster.scale` attribute
  1137. ``skew`` ``0`` Mapped to the :attr:`~GDALRaster.width` attribute
  1138. ``bands`` ``[]`` See below
  1139. ``nr_of_bands`` ``0`` See below
  1140. ``datatype`` ``6`` See below
  1141. ``papsz_options`` ``{}`` See below
  1142. ================= ======== ==================================================
  1143. .. object:: name
  1144. String representing the name of the raster. When creating a file-based
  1145. raster, this parameter must be the file path for the new raster. If the
  1146. name starts with ``/vsimem/``, the raster is created in GDAL's virtual
  1147. filesystem.
  1148. .. object:: datatype
  1149. Integer representing the data type for all the bands. Defaults to ``6``
  1150. (Float32). All bands of a new raster are required to have the same datatype.
  1151. The value mapping is:
  1152. ===== =============== ===============================
  1153. Value GDAL Pixel Type Description
  1154. ===== =============== ===============================
  1155. 1 GDT_Byte Eight bit unsigned integer
  1156. 2 GDT_UInt16 Sixteen bit unsigned integer
  1157. 3 GDT_Int16 Sixteen bit signed integer
  1158. 4 GDT_UInt32 Thirty-two bit unsigned integer
  1159. 5 GDT_Int32 Thirty-two bit signed integer
  1160. 6 GDT_Float32 Thirty-two bit floating point
  1161. 7 GDT_Float64 Sixty-four bit floating point
  1162. ===== =============== ===============================
  1163. .. object:: nr_of_bands
  1164. Integer representing the number of bands of the raster. A raster can be
  1165. created without passing band data upon creation. If the number of bands
  1166. isn't specified, it's automatically calculated from the length of the
  1167. ``bands`` input. The number of bands can't be changed after creation.
  1168. .. object:: bands
  1169. A list of ``band_input`` dictionaries with band input data. The resulting
  1170. band indices are the same as in the list provided. The definition of the
  1171. band input dictionary is given below. If band data isn't provided, the
  1172. raster bands values are instantiated as an array of zeros and the "no
  1173. data" value is set to ``None``.
  1174. .. object:: papsz_options
  1175. .. versionadded:: 2.0
  1176. A dictionary with raster creation options. The key-value pairs of the
  1177. input dictionary are passed to the driver on creation of the raster.
  1178. The available options are driver-specific and are described in the
  1179. documentation of each driver.
  1180. The values in the dictionary are not case-sensitive and are automatically
  1181. converted to the correct string format upon creation.
  1182. The following example uses some of the options available for the
  1183. `GTiff driver`__. The result is a compressed signed byte raster with an
  1184. internal tiling scheme. The internal tiles have a block size of 23 by 23::
  1185. >>> GDALRaster({
  1186. ... 'driver': 'GTiff',
  1187. ... 'name': '/path/to/new/file.tif',
  1188. ... 'srid': 4326,
  1189. ... 'width': 255,
  1190. ... 'height': 255,
  1191. ... 'nr_of_bands': 1,
  1192. ... 'papsz_options': {
  1193. ... 'compress': 'packbits',
  1194. ... 'pixeltype': 'signedbyte',
  1195. ... 'tiled': 'yes',
  1196. ... 'blockxsize': 23,
  1197. ... 'blockysize': 23,
  1198. ... }
  1199. ... })
  1200. __ http://www.gdal.org/frmt_gtiff.html
  1201. The ``band_input`` dictionary
  1202. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1203. The ``bands`` key in the ``ds_input`` dictionary is a list of ``band_input``
  1204. dictionaries. Each ``band_input`` dictionary can contain pixel values and the
  1205. "no data" value to be set on the bands of the new raster. The data array can
  1206. have the full size of the new raster or be smaller. For arrays that are smaller
  1207. than the full raster, the ``size``, ``shape``, and ``offset`` keys control the
  1208. pixel values. The corresponding keys are passed to the :meth:`~GDALBand.data`
  1209. method. Their functionality is the same as setting the band data with that
  1210. method. The following table describes the keys that can be used.
  1211. ================ ================================= ======================================================
  1212. Key Default Usage
  1213. ================ ================================= ======================================================
  1214. ``nodata_value`` ``None`` Mapped to the :attr:`~GDALBand.nodata_value` attribute
  1215. ``data`` Same as ``nodata_value`` or ``0`` Passed to the :meth:`~GDALBand.data` method
  1216. ``size`` ``(with, height)`` of raster Passed to the :meth:`~GDALBand.data` method
  1217. ``shape`` Same as size Passed to the :meth:`~GDALBand.data` method
  1218. ``offset`` ``(0, 0)`` Passed to the :meth:`~GDALBand.data` method
  1219. ================ ================================= ======================================================
  1220. .. _gdal-raster-vsimem:
  1221. Using GDAL's Virtual Filesystem
  1222. -------------------------------
  1223. GDAL has an internal memory-based filesystem, which allows treating blocks of
  1224. memory as files. It can be used to read and write :class:`GDALRaster` objects
  1225. to and from binary file buffers.
  1226. This is useful in web contexts where rasters might be obtained as a buffer
  1227. from a remote storage or returned from a view without being written to disk.
  1228. :class:`GDALRaster` objects are created in the virtual filesystem when a
  1229. ``bytes`` object is provided as input, or when the file path starts with
  1230. ``/vsimem/``.
  1231. Input provided as ``bytes`` has to be a full binary representation of a file.
  1232. For instance::
  1233. # Read a raster as a file object from a remote source.
  1234. >>> from urllib.request import urlopen
  1235. >>> dat = urlopen('http://example.com/raster.tif').read()
  1236. # Instantiate a raster from the bytes object.
  1237. >>> rst = GDALRaster(dat)
  1238. # The name starts with /vsimem/, indicating that the raster lives in the
  1239. # virtual filesystem.
  1240. >>> rst.name
  1241. '/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'
  1242. To create a new virtual file-based raster from scratch, use the ``ds_input``
  1243. dictionary representation and provide a ``name`` argument that starts with
  1244. ``/vsimem/`` (for detail of the dictionary representation, see
  1245. :ref:`gdal-raster-ds-input`). For virtual file-based rasters, the
  1246. :attr:`~GDALRaster.vsi_buffer` attribute returns the ``bytes`` representation
  1247. of the raster.
  1248. Here's how to create a raster and return it as a file in an
  1249. :class:`~django.http.HttpResponse`::
  1250. >>> from django.http import HttpResponse
  1251. >>> rst = GDALRaster({
  1252. ... 'name': '/vsimem/temporarymemfile',
  1253. ... 'driver': 'tif',
  1254. ... 'width': 6, 'height': 6, 'srid': 3086,
  1255. ... 'origin': [500000, 400000],
  1256. ... 'scale': [100, -100],
  1257. ... 'bands': [{'data': range(36), 'nodata_value': 99}]
  1258. ... })
  1259. >>> HttpResponse(rast.vsi_buffer, 'image/tiff')
  1260. Settings
  1261. ========
  1262. .. setting:: GDAL_LIBRARY_PATH
  1263. ``GDAL_LIBRARY_PATH``
  1264. ---------------------
  1265. A string specifying the location of the GDAL library. Typically,
  1266. this setting is only used if the GDAL library is in a non-standard
  1267. location (e.g., ``/home/john/lib/libgdal.so``).
  1268. Exceptions
  1269. ==========
  1270. .. exception:: GDALException
  1271. The base GDAL exception, indicating a GDAL-related error.
  1272. .. exception:: SRSException
  1273. An exception raised when an error occurs when constructing or using a
  1274. spatial reference system object.