gdal.txt 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157
  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:: is_3d
  366. A boolean indicating if this geometry has Z coordinates.
  367. .. method:: set_3d(value)
  368. A method that adds or removes the Z coordinate dimension.
  369. .. code-block:: pycon
  370. >>> p = OGRGeometry("POINT (1 2 3)")
  371. >>> p.is_3d
  372. True
  373. >>> p.set_3d(False)
  374. >>> p.wkt
  375. "POINT (1 2)"
  376. .. attribute:: is_measured
  377. A boolean indicating if this geometry has M coordinates.
  378. .. method:: set_measured(value)
  379. A method to add or remove the M coordinate dimension.
  380. .. code-block:: pycon
  381. >>> p = OGRGeometry("POINT (1 2)")
  382. >>> p.is_measured
  383. False
  384. >>> p.set_measured(True)
  385. >>> p.wkt
  386. "POINT M (1 2 0)"
  387. .. attribute:: geom_count
  388. Returns the number of elements in this geometry:
  389. .. code-block:: pycon
  390. >>> polygon.geom_count
  391. 1
  392. .. attribute:: has_curve
  393. .. versionadded:: 5.2
  394. A boolean indicating if this geometry is or contains a curve geometry.
  395. .. method:: get_linear_geometry
  396. .. versionadded:: 5.2
  397. Returns a linear version of the geometry. If no conversion can be made, the
  398. original geometry is returned.
  399. .. method:: get_curve_geometry
  400. .. versionadded:: 5.2
  401. Returns a curved version of the geometry. If no conversion can be made, the
  402. original geometry is returned.
  403. .. attribute:: point_count
  404. Returns the number of points used to describe this geometry:
  405. .. code-block:: pycon
  406. >>> polygon.point_count
  407. 4
  408. .. attribute:: num_points
  409. Alias for :attr:`point_count`.
  410. .. attribute:: num_coords
  411. Alias for :attr:`point_count`.
  412. .. attribute:: geom_type
  413. Returns the type of this geometry, as an :class:`OGRGeomType` object.
  414. .. attribute:: geom_name
  415. Returns the name of the type of this geometry:
  416. .. code-block:: pycon
  417. >>> polygon.geom_name
  418. 'POLYGON'
  419. .. attribute:: area
  420. Returns the area of this geometry, or 0 for geometries that do not contain
  421. an area:
  422. .. code-block:: pycon
  423. >>> polygon.area
  424. 25.0
  425. .. attribute:: envelope
  426. Returns the envelope of this geometry, as an :class:`Envelope` object.
  427. .. attribute:: extent
  428. Returns the envelope of this geometry as a 4-tuple, instead of as an
  429. :class:`Envelope` object:
  430. .. code-block:: pycon
  431. >>> point.extent
  432. (0.0, 0.0, 5.0, 5.0)
  433. .. attribute:: srs
  434. This property controls the spatial reference for this geometry, or
  435. ``None`` if no spatial reference system has been assigned to it.
  436. If assigned, accessing this property returns a :class:`SpatialReference`
  437. object. It may be set with another :class:`SpatialReference` object,
  438. or any input that :class:`SpatialReference` accepts. Example:
  439. .. code-block:: pycon
  440. >>> city.geom.srs.name
  441. 'GCS_WGS_1984'
  442. .. attribute:: srid
  443. Returns or sets the spatial reference identifier corresponding to
  444. :class:`SpatialReference` of this geometry. Returns ``None`` if
  445. there is no spatial reference information associated with this
  446. geometry, or if an SRID cannot be determined.
  447. .. attribute:: geos
  448. Returns a :class:`~django.contrib.gis.geos.GEOSGeometry` object
  449. corresponding to this geometry.
  450. .. attribute:: gml
  451. Returns a string representation of this geometry in GML format:
  452. .. code-block:: pycon
  453. >>> OGRGeometry("POINT(1 2)").gml
  454. '<gml:Point><gml:coordinates>1,2</gml:coordinates></gml:Point>'
  455. .. attribute:: hex
  456. Returns a string representation of this geometry in HEX WKB format:
  457. .. code-block:: pycon
  458. >>> OGRGeometry("POINT(1 2)").hex
  459. '0101000000000000000000F03F0000000000000040'
  460. .. attribute:: json
  461. Returns a string representation of this geometry in JSON format:
  462. .. code-block:: pycon
  463. >>> OGRGeometry("POINT(1 2)").json
  464. '{ "type": "Point", "coordinates": [ 1.000000, 2.000000 ] }'
  465. .. attribute:: kml
  466. Returns a string representation of this geometry in KML format.
  467. .. attribute:: wkb_size
  468. Returns the size of the WKB buffer needed to hold a WKB representation
  469. of this geometry:
  470. .. code-block:: pycon
  471. >>> OGRGeometry("POINT(1 2)").wkb_size
  472. 21
  473. .. attribute:: wkb
  474. Returns a ``buffer`` containing a WKB representation of this geometry.
  475. .. attribute:: wkt
  476. Returns a string representation of this geometry in WKT format.
  477. .. attribute:: ewkt
  478. Returns the EWKT representation of this geometry.
  479. .. method:: clone()
  480. Returns a new :class:`OGRGeometry` clone of this geometry object.
  481. .. method:: close_rings()
  482. If there are any rings within this geometry that have not been closed,
  483. this routine will do so by adding the starting point to the end:
  484. .. code-block:: pycon
  485. >>> triangle = OGRGeometry("LINEARRING (0 0,0 1,1 0)")
  486. >>> triangle.close_rings()
  487. >>> triangle.wkt
  488. 'LINEARRING (0 0,0 1,1 0,0 0)'
  489. .. method:: transform(coord_trans, clone=False)
  490. Transforms this geometry to a different spatial reference system. May take
  491. a :class:`CoordTransform` object, a :class:`SpatialReference` object, or
  492. any other input accepted by :class:`SpatialReference` (including spatial
  493. reference WKT and PROJ strings, or an integer SRID).
  494. By default nothing is returned and the geometry is transformed in-place.
  495. However, if the ``clone`` keyword is set to ``True`` then a transformed
  496. clone of this geometry is returned instead.
  497. .. method:: intersects(other)
  498. Returns ``True`` if this geometry intersects the other, otherwise returns
  499. ``False``.
  500. .. method:: equals(other)
  501. Returns ``True`` if this geometry is equivalent to the other, otherwise
  502. returns ``False``.
  503. .. method:: disjoint(other)
  504. Returns ``True`` if this geometry is spatially disjoint to (i.e. does
  505. not intersect) the other, otherwise returns ``False``.
  506. .. method:: touches(other)
  507. Returns ``True`` if this geometry touches the other, otherwise returns
  508. ``False``.
  509. .. method:: crosses(other)
  510. Returns ``True`` if this geometry crosses the other, otherwise returns
  511. ``False``.
  512. .. method:: within(other)
  513. Returns ``True`` if this geometry is contained within the other, otherwise
  514. returns ``False``.
  515. .. method:: contains(other)
  516. Returns ``True`` if this geometry contains the other, otherwise returns
  517. ``False``.
  518. .. method:: overlaps(other)
  519. Returns ``True`` if this geometry overlaps the other, otherwise returns
  520. ``False``.
  521. .. method:: boundary()
  522. The boundary of this geometry, as a new :class:`OGRGeometry` object.
  523. .. attribute:: convex_hull
  524. The smallest convex polygon that contains this geometry, as a new
  525. :class:`OGRGeometry` object.
  526. .. method:: difference()
  527. Returns the region consisting of the difference of this geometry and
  528. the other, as a new :class:`OGRGeometry` object.
  529. .. method:: intersection()
  530. Returns the region consisting of the intersection of this geometry and
  531. the other, as a new :class:`OGRGeometry` object.
  532. .. method:: sym_difference()
  533. Returns the region consisting of the symmetric difference of this
  534. geometry and the other, as a new :class:`OGRGeometry` object.
  535. .. method:: union()
  536. Returns the region consisting of the union of this geometry and
  537. the other, as a new :class:`OGRGeometry` object.
  538. .. attribute:: centroid
  539. Returns a :class:`Point` representing the centroid of this geometry.
  540. .. attribute:: tuple
  541. Returns the coordinates of a point geometry as a tuple, the
  542. coordinates of a line geometry as a tuple of tuples, and so forth:
  543. .. code-block:: pycon
  544. >>> OGRGeometry("POINT (1 2)").tuple
  545. (1.0, 2.0)
  546. >>> OGRGeometry("LINESTRING (1 2,3 4)").tuple
  547. ((1.0, 2.0), (3.0, 4.0))
  548. .. attribute:: coords
  549. An alias for :attr:`tuple`.
  550. .. class:: Point
  551. .. attribute:: x
  552. Returns the X coordinate of this point:
  553. .. code-block:: pycon
  554. >>> OGRGeometry("POINT (1 2)").x
  555. 1.0
  556. .. attribute:: y
  557. Returns the Y coordinate of this point:
  558. .. code-block:: pycon
  559. >>> OGRGeometry("POINT (1 2)").y
  560. 2.0
  561. .. attribute:: z
  562. Returns the Z coordinate of this point, or ``None`` if the point does not
  563. have a Z coordinate:
  564. .. code-block:: pycon
  565. >>> OGRGeometry("POINT (1 2 3)").z
  566. 3.0
  567. .. attribute:: m
  568. Returns the M coordinate of this point, or ``None`` if the Point does not
  569. have an M coordinate:
  570. .. code-block:: pycon
  571. >>> OGRGeometry("POINT ZM (1 2 3 4)").m
  572. 4.0
  573. .. class:: LineString
  574. .. attribute:: x
  575. Returns a list of X coordinates in this line:
  576. .. code-block:: pycon
  577. >>> OGRGeometry("LINESTRING (1 2,3 4)").x
  578. [1.0, 3.0]
  579. .. attribute:: y
  580. Returns a list of Y coordinates in this line:
  581. .. code-block:: pycon
  582. >>> OGRGeometry("LINESTRING (1 2,3 4)").y
  583. [2.0, 4.0]
  584. .. attribute:: z
  585. Returns a list of Z coordinates in this line, or ``None`` if the line does
  586. not have Z coordinates:
  587. .. code-block:: pycon
  588. >>> OGRGeometry("LINESTRING (1 2 3,4 5 6)").z
  589. [3.0, 6.0]
  590. .. attribute:: m
  591. Returns a list of M coordinates in this line or ``None`` if the line does
  592. not have M coordinates:
  593. .. code-block:: pycon
  594. >>> OGRGeometry("LINESTRING(0 1 2 10, 1 2 3 11, 2 3 4 12)").m
  595. [10.0, 11.0, 12.0]
  596. .. class:: Polygon
  597. .. attribute:: shell
  598. Returns the shell or exterior ring of this polygon, as a ``LinearRing``
  599. geometry.
  600. .. attribute:: exterior_ring
  601. An alias for :attr:`shell`.
  602. .. class:: GeometryCollection
  603. .. method:: add(geom)
  604. Adds a geometry to this geometry collection. Not applicable to other
  605. geometry types.
  606. ``OGRGeomType``
  607. ---------------
  608. .. class:: OGRGeomType(type_input)
  609. This class allows for the representation of an OGR geometry type
  610. in any of several ways:
  611. .. code-block:: pycon
  612. >>> from django.contrib.gis.gdal import OGRGeomType
  613. >>> gt1 = OGRGeomType(3) # Using an integer for the type
  614. >>> gt2 = OGRGeomType("Polygon") # Using a string
  615. >>> gt3 = OGRGeomType("POLYGON") # It's case-insensitive
  616. >>> print(gt1 == 3, gt1 == "Polygon") # Equivalence works w/non-OGRGeomType objects
  617. True True
  618. .. attribute:: name
  619. Returns a short-hand string form of the OGR Geometry type:
  620. .. code-block:: pycon
  621. >>> gt1.name
  622. 'Polygon'
  623. .. attribute:: num
  624. Returns the number corresponding to the OGR geometry type:
  625. .. code-block:: pycon
  626. >>> gt1.num
  627. 3
  628. .. attribute:: django
  629. Returns the Django field type (a subclass of GeometryField) to use for
  630. storing this OGR type, or ``None`` if there is no appropriate Django type:
  631. .. code-block:: pycon
  632. >>> gt1.django
  633. 'PolygonField'
  634. ``Envelope``
  635. ------------
  636. .. class:: Envelope(*args)
  637. Represents an OGR Envelope structure that contains the minimum and maximum
  638. X, Y coordinates for a rectangle bounding box. The naming of the variables
  639. is compatible with the OGR Envelope C structure.
  640. .. attribute:: min_x
  641. The value of the minimum X coordinate.
  642. .. attribute:: min_y
  643. The value of the maximum X coordinate.
  644. .. attribute:: max_x
  645. The value of the minimum Y coordinate.
  646. .. attribute:: max_y
  647. The value of the maximum Y coordinate.
  648. .. attribute:: ur
  649. The upper-right coordinate, as a tuple.
  650. .. attribute:: ll
  651. The lower-left coordinate, as a tuple.
  652. .. attribute:: tuple
  653. A tuple representing the envelope.
  654. .. attribute:: wkt
  655. A string representing this envelope as a polygon in WKT format.
  656. .. method:: expand_to_include(*args)
  657. Coordinate System Objects
  658. =========================
  659. ``SpatialReference``
  660. --------------------
  661. .. class:: SpatialReference(srs_input)
  662. Spatial reference objects are initialized on the given ``srs_input``,
  663. which may be one of the following:
  664. * OGC Well Known Text (WKT) (a string)
  665. * EPSG code (integer or string)
  666. * PROJ string
  667. * A shorthand string for well-known standards (``'WGS84'``, ``'WGS72'``,
  668. ``'NAD27'``, ``'NAD83'``)
  669. Example:
  670. .. code-block:: pycon
  671. >>> wgs84 = SpatialReference("WGS84") # shorthand string
  672. >>> wgs84 = SpatialReference(4326) # EPSG code
  673. >>> wgs84 = SpatialReference("EPSG:4326") # EPSG string
  674. >>> proj = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs "
  675. >>> wgs84 = SpatialReference(proj) # PROJ string
  676. >>> wgs84 = SpatialReference(
  677. ... """GEOGCS["WGS 84",
  678. ... DATUM["WGS_1984",
  679. ... SPHEROID["WGS 84",6378137,298.257223563,
  680. ... AUTHORITY["EPSG","7030"]],
  681. ... AUTHORITY["EPSG","6326"]],
  682. ... PRIMEM["Greenwich",0,
  683. ... AUTHORITY["EPSG","8901"]],
  684. ... UNIT["degree",0.01745329251994328,
  685. ... AUTHORITY["EPSG","9122"]],
  686. ... AUTHORITY["EPSG","4326"]]"""
  687. ... ) # OGC WKT
  688. .. method:: __getitem__(target)
  689. Returns the value of the given string attribute node, ``None`` if the node
  690. doesn't exist. Can also take a tuple as a parameter, (target, child), where
  691. child is the index of the attribute in the WKT. For example:
  692. .. code-block:: pycon
  693. >>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]'
  694. >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326
  695. >>> print(srs["GEOGCS"])
  696. WGS 84
  697. >>> print(srs["DATUM"])
  698. WGS_1984
  699. >>> print(srs["AUTHORITY"])
  700. EPSG
  701. >>> print(srs["AUTHORITY", 1]) # The authority value
  702. 4326
  703. >>> print(srs["TOWGS84", 4]) # the fourth value in this wkt
  704. 0
  705. >>> print(srs["UNIT|AUTHORITY"]) # For the units authority, have to use the pipe symbol.
  706. EPSG
  707. >>> print(srs["UNIT|AUTHORITY", 1]) # The authority value for the units
  708. 9122
  709. .. method:: attr_value(target, index=0)
  710. The attribute value for the given target node (e.g. ``'PROJCS'``).
  711. The index keyword specifies an index of the child node to return.
  712. .. method:: auth_name(target)
  713. Returns the authority name for the given string target node.
  714. .. method:: auth_code(target)
  715. Returns the authority code for the given string target node.
  716. .. method:: clone()
  717. Returns a clone of this spatial reference object.
  718. .. method:: identify_epsg()
  719. This method inspects the WKT of this ``SpatialReference`` and will add EPSG
  720. authority nodes where an EPSG identifier is applicable.
  721. .. method:: from_esri()
  722. Morphs this SpatialReference from ESRI's format to EPSG
  723. .. method:: to_esri()
  724. Morphs this SpatialReference to ESRI's format.
  725. .. method:: validate()
  726. Checks to see if the given spatial reference is valid, if not
  727. an exception will be raised.
  728. .. method:: import_epsg(epsg)
  729. Import spatial reference from EPSG code.
  730. .. method:: import_proj(proj)
  731. Import spatial reference from PROJ string.
  732. .. method:: import_user_input(user_input)
  733. .. method:: import_wkt(wkt)
  734. Import spatial reference from WKT.
  735. .. method:: import_xml(xml)
  736. Import spatial reference from XML.
  737. .. attribute:: name
  738. Returns the name of this Spatial Reference.
  739. .. attribute:: srid
  740. Returns the SRID of top-level authority, or ``None`` if undefined.
  741. .. attribute:: linear_name
  742. Returns the name of the linear units.
  743. .. attribute:: linear_units
  744. Returns the value of the linear units.
  745. .. attribute:: angular_name
  746. Returns the name of the angular units."
  747. .. attribute:: angular_units
  748. Returns the value of the angular units.
  749. .. attribute:: units
  750. Returns a 2-tuple of the units value and the units name and will
  751. automatically determines whether to return the linear or angular units.
  752. .. attribute:: ellipsoid
  753. Returns a tuple of the ellipsoid parameters for this spatial reference:
  754. (semimajor axis, semiminor axis, and inverse flattening).
  755. .. attribute:: semi_major
  756. Returns the semi major axis of the ellipsoid for this spatial reference.
  757. .. attribute:: semi_minor
  758. Returns the semi minor axis of the ellipsoid for this spatial reference.
  759. .. attribute:: inverse_flattening
  760. Returns the inverse flattening of the ellipsoid for this spatial reference.
  761. .. attribute:: geographic
  762. Returns ``True`` if this spatial reference is geographic (root node is
  763. ``GEOGCS``).
  764. .. attribute:: local
  765. Returns ``True`` if this spatial reference is local (root node is
  766. ``LOCAL_CS``).
  767. .. attribute:: projected
  768. Returns ``True`` if this spatial reference is a projected coordinate system
  769. (root node is ``PROJCS``).
  770. .. attribute:: wkt
  771. Returns the WKT representation of this spatial reference.
  772. .. attribute:: pretty_wkt
  773. Returns the 'pretty' representation of the WKT.
  774. .. attribute:: proj
  775. Returns the PROJ representation for this spatial reference.
  776. .. attribute:: proj4
  777. Alias for :attr:`SpatialReference.proj`.
  778. .. attribute:: xml
  779. Returns the XML representation of this spatial reference.
  780. ``CoordTransform``
  781. ------------------
  782. .. class:: CoordTransform(source, target)
  783. Represents a coordinate system transform. It is initialized with two
  784. :class:`SpatialReference`, representing the source and target coordinate
  785. systems, respectively. These objects should be used when performing the same
  786. coordinate transformation repeatedly on different geometries:
  787. .. code-block:: pycon
  788. >>> ct = CoordTransform(SpatialReference("WGS84"), SpatialReference("NAD83"))
  789. >>> for feat in layer:
  790. ... geom = feat.geom # getting clone of feature geometry
  791. ... geom.transform(ct) # transforming
  792. ...
  793. .. _raster-data-source-objects:
  794. Raster Data Objects
  795. ===================
  796. ``GDALRaster``
  797. ----------------
  798. :class:`GDALRaster` is a wrapper for the GDAL raster source object that
  799. supports reading data from a variety of GDAL-supported geospatial file
  800. formats and data sources using a consistent interface. Each
  801. data source is represented by a :class:`GDALRaster` object which contains
  802. one or more layers of data named bands. Each band, represented by a
  803. :class:`GDALBand` object, contains georeferenced image data. For example, an RGB
  804. image is represented as three bands: one for red, one for green, and one for
  805. blue.
  806. .. note::
  807. For raster data there is no difference between a raster instance and its
  808. data source. Unlike for the Geometry objects, :class:`GDALRaster` objects are
  809. always a data source. Temporary rasters can be instantiated in memory
  810. using the corresponding driver, but they will be of the same class as file-based
  811. raster sources.
  812. .. class:: GDALRaster(ds_input, write=False)
  813. The constructor for ``GDALRaster`` accepts two parameters. The first
  814. parameter defines the raster source, and the second parameter defines if a
  815. raster should be opened in write mode. For newly-created rasters, the second
  816. parameter is ignored and the new raster is always created in write mode.
  817. The first parameter can take three forms: a string or
  818. :class:`~pathlib.Path` representing a file path (filesystem or GDAL virtual
  819. filesystem), a dictionary with values defining a new raster, or a bytes
  820. object representing a raster file.
  821. If the input is a file path, the raster is opened from there. If the input
  822. is raw data in a dictionary, the parameters ``width``, ``height``, and
  823. ``srid`` are required. If the input is a bytes object, it will be opened
  824. using a GDAL virtual filesystem.
  825. For a detailed description of how to create rasters using dictionary input,
  826. see :ref:`gdal-raster-ds-input`. For a detailed description of how to
  827. create rasters in the virtual filesystem, see :ref:`gdal-raster-vsimem`.
  828. The following example shows how rasters can be created from different input
  829. sources (using the sample data from the GeoDjango tests; see also the
  830. :ref:`gdal_sample_data` section).
  831. .. code-block:: pycon
  832. >>> from django.contrib.gis.gdal import GDALRaster
  833. >>> rst = GDALRaster("/path/to/your/raster.tif", write=False)
  834. >>> rst.name
  835. '/path/to/your/raster.tif'
  836. >>> rst.width, rst.height # This file has 163 x 174 pixels
  837. (163, 174)
  838. >>> rst = GDALRaster(
  839. ... { # Creates an in-memory raster
  840. ... "srid": 4326,
  841. ... "width": 4,
  842. ... "height": 4,
  843. ... "datatype": 1,
  844. ... "bands": [
  845. ... {
  846. ... "data": (2, 3),
  847. ... "offset": (1, 1),
  848. ... "size": (2, 2),
  849. ... "shape": (2, 1),
  850. ... "nodata_value": 5,
  851. ... }
  852. ... ],
  853. ... }
  854. ... )
  855. >>> rst.srs.srid
  856. 4326
  857. >>> rst.width, rst.height
  858. (4, 4)
  859. >>> rst.bands[0].data()
  860. array([[5, 5, 5, 5],
  861. [5, 2, 3, 5],
  862. [5, 2, 3, 5],
  863. [5, 5, 5, 5]], dtype=uint8)
  864. >>> rst_file = open("/path/to/your/raster.tif", "rb")
  865. >>> rst_bytes = rst_file.read()
  866. >>> rst = GDALRaster(rst_bytes)
  867. >>> rst.is_vsi_based
  868. True
  869. >>> rst.name # Stored in a random path in the vsimem filesystem.
  870. '/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'
  871. .. attribute:: name
  872. The name of the source which is equivalent to the input file path or the name
  873. provided upon instantiation.
  874. .. code-block:: pycon
  875. >>> GDALRaster({"width": 10, "height": 10, "name": "myraster", "srid": 4326}).name
  876. 'myraster'
  877. .. attribute:: driver
  878. The name of the GDAL driver used to handle the input file. For ``GDALRaster``\s created
  879. from a file, the driver type is detected automatically. The creation of rasters from
  880. scratch is an in-memory raster by default (``'MEM'``), but can be
  881. altered as needed. For instance, use ``GTiff`` for a ``GeoTiff`` file.
  882. For a list of file types, see also the `GDAL Raster Formats`__ list.
  883. __ https://gdal.org/drivers/raster/
  884. An in-memory raster is created through the following example:
  885. .. code-block:: pycon
  886. >>> GDALRaster({"width": 10, "height": 10, "srid": 4326}).driver.name
  887. 'MEM'
  888. A file based GeoTiff raster is created through the following example:
  889. .. code-block:: pycon
  890. >>> import tempfile
  891. >>> rstfile = tempfile.NamedTemporaryFile(suffix=".tif")
  892. >>> rst = GDALRaster(
  893. ... {
  894. ... "driver": "GTiff",
  895. ... "name": rstfile.name,
  896. ... "srid": 4326,
  897. ... "width": 255,
  898. ... "height": 255,
  899. ... "nr_of_bands": 1,
  900. ... }
  901. ... )
  902. >>> rst.name
  903. '/tmp/tmp7x9H4J.tif' # The exact filename will be different on your computer
  904. >>> rst.driver.name
  905. 'GTiff'
  906. .. attribute:: width
  907. The width of the source in pixels (X-axis).
  908. .. code-block:: pycon
  909. >>> GDALRaster({"width": 10, "height": 20, "srid": 4326}).width
  910. 10
  911. .. attribute:: height
  912. The height of the source in pixels (Y-axis).
  913. .. code-block:: pycon
  914. >>> GDALRaster({"width": 10, "height": 20, "srid": 4326}).height
  915. 20
  916. .. attribute:: srs
  917. The spatial reference system of the raster, as a
  918. :class:`SpatialReference` instance. The SRS can be changed by
  919. setting it to an other :class:`SpatialReference` or providing any input
  920. that is accepted by the :class:`SpatialReference` constructor.
  921. .. code-block:: pycon
  922. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  923. >>> rst.srs.srid
  924. 4326
  925. >>> rst.srs = 3086
  926. >>> rst.srs.srid
  927. 3086
  928. .. attribute:: srid
  929. The Spatial Reference System Identifier (SRID) of the raster. This
  930. property is a shortcut to getting or setting the SRID through the
  931. :attr:`srs` attribute.
  932. .. code-block:: pycon
  933. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  934. >>> rst.srid
  935. 4326
  936. >>> rst.srid = 3086
  937. >>> rst.srid
  938. 3086
  939. >>> rst.srs.srid # This is equivalent
  940. 3086
  941. .. attribute:: geotransform
  942. The affine transformation matrix used to georeference the source, as a
  943. tuple of six coefficients which map pixel/line coordinates into
  944. georeferenced space using the following relationship::
  945. Xgeo = GT(0) + Xpixel * GT(1) + Yline * GT(2)
  946. Ygeo = GT(3) + Xpixel * GT(4) + Yline * GT(5)
  947. The same values can be retrieved by accessing the :attr:`origin`
  948. (indices 0 and 3), :attr:`scale` (indices 1 and 5) and :attr:`skew`
  949. (indices 2 and 4) properties.
  950. The default is ``[0.0, 1.0, 0.0, 0.0, 0.0, -1.0]``.
  951. .. code-block:: pycon
  952. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  953. >>> rst.geotransform
  954. [0.0, 1.0, 0.0, 0.0, 0.0, -1.0]
  955. .. attribute:: origin
  956. Coordinates of the top left origin of the raster in the spatial
  957. reference system of the source, as a point object with ``x`` and ``y``
  958. members.
  959. .. code-block:: pycon
  960. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  961. >>> rst.origin
  962. [0.0, 0.0]
  963. >>> rst.origin.x = 1
  964. >>> rst.origin
  965. [1.0, 0.0]
  966. .. attribute:: scale
  967. Pixel width and height used for georeferencing the raster, as a point
  968. object with ``x`` and ``y`` members. See :attr:`geotransform` for more
  969. information.
  970. .. code-block:: pycon
  971. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  972. >>> rst.scale
  973. [1.0, -1.0]
  974. >>> rst.scale.x = 2
  975. >>> rst.scale
  976. [2.0, -1.0]
  977. .. attribute:: skew
  978. Skew coefficients used to georeference the raster, as a point object
  979. with ``x`` and ``y`` members. In case of north up images, these
  980. coefficients are both ``0``.
  981. .. code-block:: pycon
  982. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  983. >>> rst.skew
  984. [0.0, 0.0]
  985. >>> rst.skew.x = 3
  986. >>> rst.skew
  987. [3.0, 0.0]
  988. .. attribute:: extent
  989. Extent (boundary values) of the raster source, as a 4-tuple
  990. ``(xmin, ymin, xmax, ymax)`` in the spatial reference system of the
  991. source.
  992. .. code-block:: pycon
  993. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  994. >>> rst.extent
  995. (0.0, -20.0, 10.0, 0.0)
  996. >>> rst.origin.x = 100
  997. >>> rst.extent
  998. (100.0, -20.0, 110.0, 0.0)
  999. .. attribute:: bands
  1000. List of all bands of the source, as :class:`GDALBand` instances.
  1001. .. code-block:: pycon
  1002. >>> rst = GDALRaster(
  1003. ... {
  1004. ... "width": 1,
  1005. ... "height": 2,
  1006. ... "srid": 4326,
  1007. ... "bands": [{"data": [0, 1]}, {"data": [2, 3]}],
  1008. ... }
  1009. ... )
  1010. >>> len(rst.bands)
  1011. 2
  1012. >>> rst.bands[1].data()
  1013. array([[ 2., 3.]], dtype=float32)
  1014. .. method:: warp(ds_input, resampling='NearestNeighbour', max_error=0.0)
  1015. Returns a warped version of this raster.
  1016. The warping parameters can be specified through the ``ds_input``
  1017. argument. The use of ``ds_input`` is analogous to the corresponding
  1018. argument of the class constructor. It is a dictionary with the
  1019. characteristics of the target raster. Allowed dictionary key values are
  1020. width, height, SRID, origin, scale, skew, datatype, driver, and name
  1021. (filename).
  1022. By default, the warp functions keeps most parameters equal to the
  1023. values of the original source raster, so only parameters that should be
  1024. changed need to be specified. Note that this includes the driver, so
  1025. for file-based rasters the warp function will create a new raster on
  1026. disk.
  1027. The only parameter that is set differently from the source raster is the
  1028. name. The default value of the raster name is the name of the source
  1029. raster appended with ``'_copy' + source_driver_name``. For file-based
  1030. rasters it is recommended to provide the file path of the target raster.
  1031. The resampling algorithm used for warping can be specified with the
  1032. ``resampling`` argument. The default is ``NearestNeighbor``, and the
  1033. other allowed values are ``Bilinear``, ``Cubic``, ``CubicSpline``,
  1034. ``Lanczos``, ``Average``, and ``Mode``.
  1035. The ``max_error`` argument can be used to specify the maximum error
  1036. measured in input pixels that is allowed in approximating the
  1037. transformation. The default is 0.0 for exact calculations.
  1038. For users familiar with ``GDAL``, this function has a similar
  1039. functionality to the ``gdalwarp`` command-line utility.
  1040. For example, the warp function can be used for aggregating a raster to
  1041. the double of its original pixel scale:
  1042. .. code-block:: pycon
  1043. >>> rst = GDALRaster(
  1044. ... {
  1045. ... "width": 6,
  1046. ... "height": 6,
  1047. ... "srid": 3086,
  1048. ... "origin": [500000, 400000],
  1049. ... "scale": [100, -100],
  1050. ... "bands": [{"data": range(36), "nodata_value": 99}],
  1051. ... }
  1052. ... )
  1053. >>> target = rst.warp({"scale": [200, -200], "width": 3, "height": 3})
  1054. >>> target.bands[0].data()
  1055. array([[ 7., 9., 11.],
  1056. [ 19., 21., 23.],
  1057. [ 31., 33., 35.]], dtype=float32)
  1058. .. method:: transform(srs, driver=None, name=None, resampling='NearestNeighbour', max_error=0.0)
  1059. Transforms this raster to a different spatial reference system
  1060. (``srs``), which may be a :class:`SpatialReference` object, or any
  1061. other input accepted by :class:`SpatialReference` (including spatial
  1062. reference WKT and PROJ strings, or an integer SRID).
  1063. It calculates the bounds and scale of the current raster in the new
  1064. spatial reference system and warps the raster using the
  1065. :attr:`~GDALRaster.warp` function.
  1066. By default, the driver of the source raster is used and the name of the
  1067. raster is the original name appended with
  1068. ``'_copy' + source_driver_name``. A different driver or name can be
  1069. specified with the ``driver`` and ``name`` arguments.
  1070. The default resampling algorithm is ``NearestNeighbour`` but can be
  1071. changed using the ``resampling`` argument. The default maximum allowed
  1072. error for resampling is 0.0 and can be changed using the ``max_error``
  1073. argument. Consult the :attr:`~GDALRaster.warp` documentation for detail
  1074. on those arguments.
  1075. .. code-block:: pycon
  1076. >>> rst = GDALRaster(
  1077. ... {
  1078. ... "width": 6,
  1079. ... "height": 6,
  1080. ... "srid": 3086,
  1081. ... "origin": [500000, 400000],
  1082. ... "scale": [100, -100],
  1083. ... "bands": [{"data": range(36), "nodata_value": 99}],
  1084. ... }
  1085. ... )
  1086. >>> target_srs = SpatialReference(4326)
  1087. >>> target = rst.transform(target_srs)
  1088. >>> target.origin
  1089. [-82.98492744885776, 27.601924753080144]
  1090. .. attribute:: info
  1091. Returns a string with a summary of the raster. This is equivalent to
  1092. the `gdalinfo`__ command line utility.
  1093. __ https://gdal.org/programs/gdalinfo.html
  1094. .. attribute:: metadata
  1095. The metadata of this raster, represented as a nested dictionary. The
  1096. first-level key is the metadata domain. The second-level contains the
  1097. metadata item names and values from each domain.
  1098. To set or update a metadata item, pass the corresponding metadata item
  1099. to the method using the nested structure described above. Only keys
  1100. that are in the specified dictionary are updated; the rest of the
  1101. metadata remains unchanged.
  1102. To remove a metadata item, use ``None`` as the metadata value.
  1103. .. code-block:: pycon
  1104. >>> rst = GDALRaster({"width": 10, "height": 20, "srid": 4326})
  1105. >>> rst.metadata
  1106. {}
  1107. >>> rst.metadata = {"DEFAULT": {"OWNER": "Django", "VERSION": "1.0"}}
  1108. >>> rst.metadata
  1109. {'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0'}}
  1110. >>> rst.metadata = {"DEFAULT": {"OWNER": None, "VERSION": "2.0"}}
  1111. >>> rst.metadata
  1112. {'DEFAULT': {'VERSION': '2.0'}}
  1113. .. attribute:: vsi_buffer
  1114. A ``bytes`` representation of this raster. Returns ``None`` for rasters
  1115. that are not stored in GDAL's virtual filesystem.
  1116. .. attribute:: is_vsi_based
  1117. A boolean indicating if this raster is stored in GDAL's virtual
  1118. filesystem.
  1119. ``GDALBand``
  1120. ------------
  1121. .. class:: GDALBand
  1122. ``GDALBand`` instances are not created explicitly, but rather obtained
  1123. from a :class:`GDALRaster` object, through its :attr:`~GDALRaster.bands`
  1124. attribute. The GDALBands contain the actual pixel values of the raster.
  1125. .. attribute:: description
  1126. The name or description of the band, if any.
  1127. .. attribute:: width
  1128. The width of the band in pixels (X-axis).
  1129. .. attribute:: height
  1130. The height of the band in pixels (Y-axis).
  1131. .. attribute:: pixel_count
  1132. The total number of pixels in this band. Is equal to ``width * height``.
  1133. .. method:: statistics(refresh=False, approximate=False)
  1134. Compute statistics on the pixel values of this band. The return value
  1135. is a tuple with the following structure:
  1136. ``(minimum, maximum, mean, standard deviation)``.
  1137. If the ``approximate`` argument is set to ``True``, the statistics may
  1138. be computed based on overviews or a subset of image tiles.
  1139. If the ``refresh`` argument is set to ``True``, the statistics will be
  1140. computed from the data directly, and the cache will be updated with the
  1141. result.
  1142. If a persistent cache value is found, that value is returned. For
  1143. raster formats using Persistent Auxiliary Metadata (PAM) services, the
  1144. statistics might be cached in an auxiliary file. In some cases this
  1145. metadata might be out of sync with the pixel values or cause values
  1146. from a previous call to be returned which don't reflect the value of
  1147. the ``approximate`` argument. In such cases, use the ``refresh``
  1148. argument to get updated values and store them in the cache.
  1149. For empty bands (where all pixel values are "no data"), all statistics
  1150. are returned as ``None``.
  1151. The statistics can also be retrieved directly by accessing the
  1152. :attr:`min`, :attr:`max`, :attr:`mean`, and :attr:`std` properties.
  1153. .. attribute:: min
  1154. The minimum pixel value of the band (excluding the "no data" value).
  1155. .. attribute:: max
  1156. The maximum pixel value of the band (excluding the "no data" value).
  1157. .. attribute:: mean
  1158. The mean of all pixel values of the band (excluding the "no data"
  1159. value).
  1160. .. attribute:: std
  1161. The standard deviation of all pixel values of the band (excluding the
  1162. "no data" value).
  1163. .. attribute:: nodata_value
  1164. The "no data" value for a band is generally a special marker value used
  1165. to mark pixels that are not valid data. Such pixels should generally not
  1166. be displayed, nor contribute to analysis operations.
  1167. To delete an existing "no data" value, set this property to ``None``.
  1168. .. method:: datatype(as_string=False)
  1169. The data type contained in the band, as an integer constant between 0
  1170. (Unknown) and 14. If ``as_string`` is ``True``, the data type is
  1171. returned as a string. Check out the "GDAL Pixel Type" column in the
  1172. :ref:`datatype value table <gdal-raster-datatype>` for possible values.
  1173. .. method:: color_interp(as_string=False)
  1174. The color interpretation for the band, as an integer between 0and 16.
  1175. If ``as_string`` is ``True``, the data type is returned as a string
  1176. with the following possible values:
  1177. ``GCI_Undefined``, ``GCI_GrayIndex``, ``GCI_PaletteIndex``,
  1178. ``GCI_RedBand``, ``GCI_GreenBand``, ``GCI_BlueBand``, ``GCI_AlphaBand``,
  1179. ``GCI_HueBand``, ``GCI_SaturationBand``, ``GCI_LightnessBand``,
  1180. ``GCI_CyanBand``, ``GCI_MagentaBand``, ``GCI_YellowBand``,
  1181. ``GCI_BlackBand``, ``GCI_YCbCr_YBand``, ``GCI_YCbCr_CbBand``, and
  1182. ``GCI_YCbCr_CrBand``. ``GCI_YCbCr_CrBand`` also represents ``GCI_Max``
  1183. because both correspond to the integer 16, but only ``GCI_YCbCr_CrBand``
  1184. is returned as a string.
  1185. .. method:: data(data=None, offset=None, size=None, shape=None)
  1186. The accessor to the pixel values of the ``GDALBand``. Returns the complete
  1187. data array if no parameters are provided. A subset of the pixel array can
  1188. be requested by specifying an offset and block size as tuples.
  1189. If NumPy is available, the data is returned as NumPy array. For performance
  1190. reasons, it is highly recommended to use NumPy.
  1191. Data is written to the ``GDALBand`` if the ``data`` parameter is provided.
  1192. The input can be of one of the following types - packed string, buffer, list,
  1193. array, and NumPy array. The number of items in the input should normally
  1194. correspond to the total number of pixels in the band, or to the number
  1195. of pixels for a specific block of pixel values if the ``offset`` and
  1196. ``size`` parameters are provided.
  1197. If the number of items in the input is different from the target pixel
  1198. block, the ``shape`` parameter must be specified. The shape is a tuple
  1199. that specifies the width and height of the input data in pixels. The
  1200. data is then replicated to update the pixel values of the selected
  1201. block. This is useful to fill an entire band with a single value, for
  1202. instance.
  1203. For example:
  1204. .. code-block:: pycon
  1205. >>> rst = GDALRaster(
  1206. ... {"width": 4, "height": 4, "srid": 4326, "datatype": 1, "nr_of_bands": 1}
  1207. ... )
  1208. >>> bnd = rst.bands[0]
  1209. >>> bnd.data(range(16))
  1210. >>> bnd.data()
  1211. array([[ 0, 1, 2, 3],
  1212. [ 4, 5, 6, 7],
  1213. [ 8, 9, 10, 11],
  1214. [12, 13, 14, 15]], dtype=int8)
  1215. >>> bnd.data(offset=(1, 1), size=(2, 2))
  1216. array([[ 5, 6],
  1217. [ 9, 10]], dtype=int8)
  1218. >>> bnd.data(data=[-1, -2, -3, -4], offset=(1, 1), size=(2, 2))
  1219. >>> bnd.data()
  1220. array([[ 0, 1, 2, 3],
  1221. [ 4, -1, -2, 7],
  1222. [ 8, -3, -4, 11],
  1223. [12, 13, 14, 15]], dtype=int8)
  1224. >>> bnd.data(data="\x9d\xa8\xb3\xbe", offset=(1, 1), size=(2, 2))
  1225. >>> bnd.data()
  1226. array([[ 0, 1, 2, 3],
  1227. [ 4, -99, -88, 7],
  1228. [ 8, -77, -66, 11],
  1229. [ 12, 13, 14, 15]], dtype=int8)
  1230. >>> bnd.data([1], shape=(1, 1))
  1231. >>> bnd.data()
  1232. array([[1, 1, 1, 1],
  1233. [1, 1, 1, 1],
  1234. [1, 1, 1, 1],
  1235. [1, 1, 1, 1]], dtype=uint8)
  1236. >>> bnd.data(range(4), shape=(1, 4))
  1237. array([[0, 0, 0, 0],
  1238. [1, 1, 1, 1],
  1239. [2, 2, 2, 2],
  1240. [3, 3, 3, 3]], dtype=uint8)
  1241. .. attribute:: metadata
  1242. The metadata of this band. The functionality is identical to
  1243. :attr:`GDALRaster.metadata`.
  1244. .. _gdal-raster-ds-input:
  1245. Creating rasters from data
  1246. --------------------------
  1247. This section describes how to create rasters from scratch using the
  1248. ``ds_input`` parameter.
  1249. A new raster is created when a ``dict`` is passed to the :class:`GDALRaster`
  1250. constructor. The dictionary contains defining parameters of the new raster,
  1251. such as the origin, size, or spatial reference system. The dictionary can also
  1252. contain pixel data and information about the format of the new raster. The
  1253. resulting raster can therefore be file-based or memory-based, depending on the
  1254. driver specified.
  1255. There's no standard for describing raster data in a dictionary or JSON flavor.
  1256. The definition of the dictionary input to the :class:`GDALRaster` class is
  1257. therefore specific to Django. It's inspired by the `geojson`__ format, but the
  1258. ``geojson`` standard is currently limited to vector formats.
  1259. Examples of using the different keys when creating rasters can be found in the
  1260. documentation of the corresponding attributes and methods of the
  1261. :class:`GDALRaster` and :class:`GDALBand` classes.
  1262. __ https://geojson.org/
  1263. The ``ds_input`` dictionary
  1264. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1265. Only a few keys are required in the ``ds_input`` dictionary to create a raster:
  1266. ``width``, ``height``, and ``srid``. All other parameters have default values
  1267. (see the table below). The list of keys that can be passed in the ``ds_input``
  1268. dictionary is closely related but not identical to the :class:`GDALRaster`
  1269. properties. Many of the parameters are mapped directly to those properties;
  1270. the others are described below.
  1271. The following table describes all keys that can be set in the ``ds_input``
  1272. dictionary.
  1273. ================= ======== ==================================================
  1274. Key Default Usage
  1275. ================= ======== ==================================================
  1276. ``srid`` required Mapped to the :attr:`~GDALRaster.srid` attribute
  1277. ``width`` required Mapped to the :attr:`~GDALRaster.width` attribute
  1278. ``height`` required Mapped to the :attr:`~GDALRaster.height` attribute
  1279. ``driver`` ``MEM`` Mapped to the :attr:`~GDALRaster.driver` attribute
  1280. ``name`` ``''`` See below
  1281. ``origin`` ``0`` Mapped to the :attr:`~GDALRaster.origin` attribute
  1282. ``scale`` ``0`` Mapped to the :attr:`~GDALRaster.scale` attribute
  1283. ``skew`` ``0`` Mapped to the :attr:`~GDALRaster.width` attribute
  1284. ``bands`` ``[]`` See below
  1285. ``nr_of_bands`` ``0`` See below
  1286. ``datatype`` ``6`` See below
  1287. ``papsz_options`` ``{}`` See below
  1288. ================= ======== ==================================================
  1289. .. object:: name
  1290. String representing the name of the raster. When creating a file-based
  1291. raster, this parameter must be the file path for the new raster. If the
  1292. name starts with ``/vsimem/``, the raster is created in GDAL's virtual
  1293. filesystem.
  1294. .. _gdal-raster-datatype:
  1295. .. object:: datatype
  1296. Integer representing the data type for all the bands. Defaults to ``6``
  1297. (Float32). All bands of a new raster are required to have the same datatype.
  1298. The value mapping is:
  1299. ===== =============== ===================================
  1300. Value GDAL Pixel Type Description
  1301. ===== =============== ===================================
  1302. 1 GDT_Byte 8 bit unsigned integer
  1303. 2 GDT_UInt16 16 bit unsigned integer
  1304. 3 GDT_Int16 16 bit signed integer
  1305. 4 GDT_UInt32 32 bit unsigned integer
  1306. 5 GDT_Int32 32 bit signed integer
  1307. 6 GDT_Float32 32 bit floating point
  1308. 7 GDT_Float64 64 bit floating point
  1309. 12 GDT_UInt64 64 bit unsigned integer (GDAL 3.5+)
  1310. 13 GDT_Int64 64 bit signed integer (GDAL 3.5+)
  1311. 14 GDT_Int8 8 bit signed integer (GDAL 3.7+)
  1312. ===== =============== ===================================
  1313. .. object:: nr_of_bands
  1314. Integer representing the number of bands of the raster. A raster can be
  1315. created without passing band data upon creation. If the number of bands
  1316. isn't specified, it's automatically calculated from the length of the
  1317. ``bands`` input. The number of bands can't be changed after creation.
  1318. .. object:: bands
  1319. A list of ``band_input`` dictionaries with band input data. The resulting
  1320. band indices are the same as in the list provided. The definition of the
  1321. band input dictionary is given below. If band data isn't provided, the
  1322. raster bands values are instantiated as an array of zeros and the "no
  1323. data" value is set to ``None``.
  1324. .. object:: papsz_options
  1325. A dictionary with raster creation options. The key-value pairs of the
  1326. input dictionary are passed to the driver on creation of the raster.
  1327. The available options are driver-specific and are described in the
  1328. documentation of each driver.
  1329. The values in the dictionary are not case-sensitive and are automatically
  1330. converted to the correct string format upon creation.
  1331. The following example uses some of the options available for the
  1332. `GTiff driver`__. The result is a compressed raster with an internal tiling
  1333. scheme. The internal tiles have a block size of 23 by 23:
  1334. .. code-block:: pycon
  1335. >>> GDALRaster(
  1336. ... {
  1337. ... "driver": "GTiff",
  1338. ... "name": "/path/to/new/file.tif",
  1339. ... "srid": 4326,
  1340. ... "width": 255,
  1341. ... "height": 255,
  1342. ... "nr_of_bands": 1,
  1343. ... "papsz_options": {
  1344. ... "compress": "packbits",
  1345. ... "tiled": "yes",
  1346. ... "blockxsize": 23,
  1347. ... "blockysize": 23,
  1348. ... },
  1349. ... }
  1350. ... )
  1351. __ https://gdal.org/drivers/raster/gtiff.html
  1352. The ``band_input`` dictionary
  1353. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1354. The ``bands`` key in the ``ds_input`` dictionary is a list of ``band_input``
  1355. dictionaries. Each ``band_input`` dictionary can contain pixel values and the
  1356. "no data" value to be set on the bands of the new raster. The data array can
  1357. have the full size of the new raster or be smaller. For arrays that are smaller
  1358. than the full raster, the ``size``, ``shape``, and ``offset`` keys control the
  1359. pixel values. The corresponding keys are passed to the :meth:`~GDALBand.data`
  1360. method. Their functionality is the same as setting the band data with that
  1361. method. The following table describes the keys that can be used.
  1362. ================ ================================= ======================================================
  1363. Key Default Usage
  1364. ================ ================================= ======================================================
  1365. ``nodata_value`` ``None`` Mapped to the :attr:`~GDALBand.nodata_value` attribute
  1366. ``data`` Same as ``nodata_value`` or ``0`` Passed to the :meth:`~GDALBand.data` method
  1367. ``size`` ``(with, height)`` of raster Passed to the :meth:`~GDALBand.data` method
  1368. ``shape`` Same as size Passed to the :meth:`~GDALBand.data` method
  1369. ``offset`` ``(0, 0)`` Passed to the :meth:`~GDALBand.data` method
  1370. ================ ================================= ======================================================
  1371. .. _gdal-raster-vsimem:
  1372. Using GDAL's Virtual Filesystem
  1373. -------------------------------
  1374. GDAL can access files stored in the filesystem, but also supports virtual
  1375. filesystems to abstract accessing other kind of files, such as compressed,
  1376. encrypted, or remote files.
  1377. Using memory-based Virtual Filesystem
  1378. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1379. GDAL has an internal memory-based filesystem, which allows treating blocks of
  1380. memory as files. It can be used to read and write :class:`GDALRaster` objects
  1381. to and from binary file buffers.
  1382. This is useful in web contexts where rasters might be obtained as a buffer
  1383. from a remote storage or returned from a view without being written to disk.
  1384. :class:`GDALRaster` objects are created in the virtual filesystem when a
  1385. ``bytes`` object is provided as input, or when the file path starts with
  1386. ``/vsimem/``.
  1387. Input provided as ``bytes`` has to be a full binary representation of a file.
  1388. For instance:
  1389. .. code-block:: pycon
  1390. # Read a raster as a file object from a remote source.
  1391. >>> from urllib.request import urlopen
  1392. >>> dat = urlopen("https://example.com/raster.tif").read()
  1393. # Instantiate a raster from the bytes object.
  1394. >>> rst = GDALRaster(dat)
  1395. # The name starts with /vsimem/, indicating that the raster lives in the
  1396. # virtual filesystem.
  1397. >>> rst.name
  1398. '/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'
  1399. To create a new virtual file-based raster from scratch, use the ``ds_input``
  1400. dictionary representation and provide a ``name`` argument that starts with
  1401. ``/vsimem/`` (for detail of the dictionary representation, see
  1402. :ref:`gdal-raster-ds-input`). For virtual file-based rasters, the
  1403. :attr:`~GDALRaster.vsi_buffer` attribute returns the ``bytes`` representation
  1404. of the raster.
  1405. Here's how to create a raster and return it as a file in an
  1406. :class:`~django.http.HttpResponse`:
  1407. .. code-block:: pycon
  1408. >>> from django.http import HttpResponse
  1409. >>> rst = GDALRaster(
  1410. ... {
  1411. ... "name": "/vsimem/temporarymemfile",
  1412. ... "driver": "tif",
  1413. ... "width": 6,
  1414. ... "height": 6,
  1415. ... "srid": 3086,
  1416. ... "origin": [500000, 400000],
  1417. ... "scale": [100, -100],
  1418. ... "bands": [{"data": range(36), "nodata_value": 99}],
  1419. ... }
  1420. ... )
  1421. >>> HttpResponse(rast.vsi_buffer, "image/tiff")
  1422. Using other Virtual Filesystems
  1423. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1424. Depending on the local build of GDAL other virtual filesystems may be
  1425. supported. You can use them by prepending the provided path with the
  1426. appropriate ``/vsi*/`` prefix. See the `GDAL Virtual Filesystems
  1427. documentation`_ for more details.
  1428. .. warning:
  1429. Rasters with names starting with `/vsi*/` will be treated as rasters from
  1430. the GDAL virtual filesystems. Django doesn't perform any extra validation.
  1431. Compressed rasters
  1432. ^^^^^^^^^^^^^^^^^^
  1433. Instead decompressing the file and instantiating the resulting raster, GDAL can
  1434. directly access compressed files using the ``/vsizip/``, ``/vsigzip/``, or
  1435. ``/vsitar/`` virtual filesystems:
  1436. .. code-block:: pycon
  1437. >>> from django.contrib.gis.gdal import GDALRaster
  1438. >>> rst = GDALRaster("/vsizip/path/to/your/file.zip/path/to/raster.tif")
  1439. >>> rst = GDALRaster("/vsigzip/path/to/your/file.gz")
  1440. >>> rst = GDALRaster("/vsitar/path/to/your/file.tar/path/to/raster.tif")
  1441. Network rasters
  1442. ^^^^^^^^^^^^^^^
  1443. GDAL can support online resources and storage providers transparently. As long
  1444. as it's built with such capabilities.
  1445. To access a public raster file with no authentication, you can use
  1446. ``/vsicurl/``:
  1447. .. code-block:: pycon
  1448. >>> from django.contrib.gis.gdal import GDALRaster
  1449. >>> rst = GDALRaster("/vsicurl/https://example.com/raster.tif")
  1450. >>> rst.name
  1451. '/vsicurl/https://example.com/raster.tif'
  1452. For commercial storage providers (e.g. ``/vsis3/``) the system should be
  1453. previously configured for authentication and possibly other settings (see the
  1454. `GDAL Virtual Filesystems documentation`_ for available options).
  1455. .. _`GDAL Virtual Filesystems documentation`: https://gdal.org/user/virtual_file_systems.html
  1456. Settings
  1457. ========
  1458. .. setting:: GDAL_LIBRARY_PATH
  1459. ``GDAL_LIBRARY_PATH``
  1460. ---------------------
  1461. A string specifying the location of the GDAL library. Typically,
  1462. this setting is only used if the GDAL library is in a non-standard
  1463. location (e.g., ``/home/john/lib/libgdal.so``).
  1464. Exceptions
  1465. ==========
  1466. .. exception:: GDALException
  1467. The base GDAL exception, indicating a GDAL-related error.
  1468. .. exception:: SRSException
  1469. An exception raised when an error occurs when constructing or using a
  1470. spatial reference system object.