gdal.txt 67 KB

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