gdal.txt 67 KB

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