gdal.txt 68 KB

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