__init__.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. # -*- coding: utf-8 -*-
  2. from __future__ import (nested_scopes, generators, division, absolute_import,
  3. with_statement, print_function, unicode_literals)
  4. import os
  5. import ctypes
  6. import numpy as np
  7. #
  8. # import GRASS modules
  9. #
  10. from grass.script import fatal, warning
  11. from grass.script import core as grasscore
  12. import grass.lib.gis as libgis
  13. import grass.lib.raster as libraster
  14. import grass.lib.rowio as librowio
  15. libgis.G_gisinit('')
  16. #
  17. # import pygrass modules
  18. #
  19. from grass.pygrass.errors import OpenError, must_be_open
  20. from grass.pygrass.gis.region import Region
  21. from grass.pygrass import utils
  22. #
  23. # import raster classes
  24. #
  25. from grass.pygrass.raster.abstract import RasterAbstractBase
  26. from grass.pygrass.raster.raster_type import TYPE as RTYPE, RTYPE_STR
  27. from grass.pygrass.raster.buffer import Buffer
  28. from grass.pygrass.raster.segment import Segment
  29. from grass.pygrass.raster.rowio import RowIO
  30. WARN_OVERWRITE = "Raster map <{0}> already exists and will be overwritten"
  31. test_raster_name="Raster_test_map"
  32. class RasterRow(RasterAbstractBase):
  33. """Raster_row_access": Inherits: "Raster_abstract_base" and implements
  34. the default row access of the Rast library.
  35. * Implements row access using row id
  36. * The get_row() method must accept a Row object as argument that will
  37. be used for value storage, so no new buffer will be allocated
  38. * Implements sequential writing of rows
  39. * Implements indexed value read only access using the [row][col]
  40. operator
  41. * Implements the [row] read method that returns a new Row object
  42. * Writing is limited using the put_row() method which accepts a
  43. Row as argument
  44. * No mathematical operation like __add__ and stuff for the Raster
  45. object (only for rows), since r.mapcalc is more sophisticated and
  46. faster
  47. * Rises IndexError if [row] is out of range
  48. Examples:
  49. >>> elev = RasterRow(test_raster_name)
  50. >>> elev.exist()
  51. True
  52. >>> elev.is_open()
  53. False
  54. >>> elev.open()
  55. >>> elev.is_open()
  56. True
  57. >>> elev.has_cats()
  58. True
  59. >>> elev.mode
  60. u'r'
  61. >>> elev.mtype
  62. 'CELL'
  63. >>> elev.num_cats()
  64. 16
  65. >>> elev.info.range
  66. (11, 44)
  67. >>> elev.info.cols
  68. 4
  69. >>> elev.info.rows
  70. 4
  71. Editing the history
  72. >>> elev.hist.read()
  73. >>> elev.hist.title = "A test map"
  74. >>> elev.hist.write()
  75. >>> elev.hist.title
  76. 'A test map'
  77. >>> elev.hist.keyword
  78. 'This is a test map'
  79. >>> attrs = list(elev.hist)
  80. >>> attrs[0]
  81. ('name', u'Raster_test_map')
  82. >>> attrs[2]
  83. ('mtype', '')
  84. Each Raster map have an attribute call ``cats`` that allow user
  85. to interact with the raster categories.
  86. >>> elev.cats # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  87. [('A', 11, None),
  88. ('B', 12, None),
  89. ...
  90. ('P', 44, None)]
  91. >>> elev.cats.labels() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
  92. ['A', 'B', 'C', 'D', 'E',
  93. 'F', 'G', 'H', 'I', 'J',
  94. 'K', 'L', 'M', 'n', 'O', 'P']
  95. >>> elev.cats[0]
  96. ('A', 11, None)
  97. >>> elev.cats[2]
  98. ('C', 13, None)
  99. >>> elev.cats[0] = ('AA', 11)
  100. >>> elev.cats[1] = ('BB', 12)
  101. >>> elev.cats.write()
  102. >>> elev.cats.read()
  103. >>> elev.cats[0]
  104. ('AA', 11, None)
  105. >>> elev.cats[1]
  106. ('BB', 12, None)
  107. Open a raster map using the *with statement*:
  108. >>> with RasterRow(test_raster_name) as elev:
  109. ... for row in elev:
  110. ... row
  111. Buffer([11, 21, 31, 41], dtype=int32)
  112. Buffer([12, 22, 32, 42], dtype=int32)
  113. Buffer([13, 23, 33, 43], dtype=int32)
  114. Buffer([14, 24, 34, 44], dtype=int32)
  115. >>> elev.is_open()
  116. False
  117. """
  118. def __init__(self, name, mapset='', *args, **kargs):
  119. super(RasterRow, self).__init__(name, mapset, *args, **kargs)
  120. # mode = "r", method = "row",
  121. @must_be_open
  122. def get_row(self, row, row_buffer=None):
  123. """Private method that return the row using the read mode
  124. call the `Rast_get_row` C function.
  125. :param row: the number of row to obtain
  126. :type row: int
  127. :param row_buffer: Buffer object instance with the right dim and type
  128. :type row_buffer: Buffer
  129. >>> elev = RasterRow(test_raster_name)
  130. >>> elev.open()
  131. >>> elev[0]
  132. Buffer([11, 21, 31, 41], dtype=int32)
  133. >>> elev.get_row(0)
  134. Buffer([11, 21, 31, 41], dtype=int32)
  135. """
  136. if row_buffer is None:
  137. row_buffer = Buffer((self._cols,), self.mtype)
  138. libraster.Rast_get_row(self._fd, row_buffer.p, row, self._gtype)
  139. return row_buffer
  140. @must_be_open
  141. def put_row(self, row):
  142. """Private method to write the row sequentially.
  143. :param row: a Row object to insert into raster
  144. :type row: Buffer object
  145. """
  146. libraster.Rast_put_row(self._fd, row.p, self._gtype)
  147. def open(self, mode=None, mtype=None, overwrite=None):
  148. """Open the raster if exist or created a new one.
  149. :param str mode: Specify if the map will be open with read or write mode
  150. ('r', 'w')
  151. :param str type: If a new map is open, specify the type of the map(`CELL`,
  152. `FCELL`, `DCELL`)
  153. :param bool overwrite: Use this flag to set the overwrite mode of existing
  154. raster maps
  155. if the map already exist, automatically check the type and set:
  156. * self.mtype
  157. Set all the privite, attributes:
  158. * self._fd;
  159. * self._gtype
  160. * self._rows and self._cols
  161. """
  162. self.mode = mode if mode else self.mode
  163. self.mtype = mtype if mtype else self.mtype
  164. self.overwrite = overwrite if overwrite is not None else self.overwrite
  165. if self.mode == 'r':
  166. if self.exist():
  167. self.info.read()
  168. self.cats.mtype = self.mtype
  169. self.cats.read()
  170. self.hist.read()
  171. self._fd = libraster.Rast_open_old(self.name, self.mapset)
  172. self._gtype = libraster.Rast_get_map_type(self._fd)
  173. self.mtype = RTYPE_STR[self._gtype]
  174. else:
  175. str_err = _("The map does not exist, I can't open in 'r' mode")
  176. raise OpenError(str_err)
  177. elif self.mode == 'w':
  178. if self.exist():
  179. if not self.overwrite:
  180. str_err = _("Raster map <{0}> already exists"
  181. " and will be not overwritten")
  182. raise OpenError(str_err.format(self))
  183. if self._gtype is None:
  184. raise OpenError(_("Raster type not defined"))
  185. self._fd = libraster.Rast_open_new(self.name, self._gtype)
  186. else:
  187. raise OpenError("Open mode: %r not supported,"
  188. " valid mode are: r, w")
  189. # read rows and cols from the active region
  190. self._rows = libraster.Rast_window_rows()
  191. self._cols = libraster.Rast_window_cols()
  192. class RasterRowIO(RasterRow):
  193. """Raster_row_cache_access": The same as "Raster_row_access" but uses
  194. the ROWIO library for cached row access
  195. """
  196. def __init__(self, name, *args, **kargs):
  197. self.rowio = RowIO()
  198. super(RasterRowIO, self).__init__(name, *args, **kargs)
  199. def open(self, mode=None, mtype=None, overwrite=False):
  200. """Open the raster if exist or created a new one.
  201. :param mode: specify if the map will be open with read or write mode
  202. ('r', 'w')
  203. :type mode: str
  204. :param type: if a new map is open, specify the type of the map(`CELL`,
  205. `FCELL`, `DCELL`)
  206. :type type: str
  207. :param overwrite: use this flag to set the overwrite mode of existing
  208. raster maps
  209. :type overwrite: bool
  210. """
  211. super(RasterRowIO, self).open(mode, mtype, overwrite)
  212. self.rowio.open(self._fd, self._rows, self._cols, self.mtype)
  213. @must_be_open
  214. def close(self):
  215. """Function to close the raster"""
  216. self.rowio.release()
  217. libraster.Rast_close(self._fd)
  218. # update rows and cols attributes
  219. self._rows = None
  220. self._cols = None
  221. self._fd = None
  222. @must_be_open
  223. def get_row(self, row, row_buffer=None):
  224. """This method returns the row using:
  225. * the read mode and
  226. * `rowcache` method
  227. :param row: the number of row to obtain
  228. :type row: int
  229. :param row_buffer: Specify the Buffer object that will be instantiate
  230. :type row_buffer: Buffer object
  231. >>> elev = RasterRowIO(test_raster_name)
  232. >>> elev.open('r')
  233. >>> for row in elev:
  234. ... row
  235. Buffer([11, 21, 31, 41], dtype=int32)
  236. Buffer([12, 22, 32, 42], dtype=int32)
  237. Buffer([13, 23, 33, 43], dtype=int32)
  238. Buffer([14, 24, 34, 44], dtype=int32)
  239. >>> elev.close()
  240. """
  241. if row_buffer is None:
  242. row_buffer = Buffer((self._cols,), self.mtype)
  243. rowio_buf = librowio.Rowio_get(ctypes.byref(self.rowio.c_rowio), row)
  244. ctypes.memmove(row_buffer.p, rowio_buf, self.rowio.row_size)
  245. return row_buffer
  246. class RasterSegment(RasterAbstractBase):
  247. """Raster_segment_access": Inherits "Raster_abstract_base" and uses the
  248. segment library for cached randomly reading and writing access.
  249. * Implements the [row][col] operator for read and write access using
  250. Segment_get() and Segment_put() functions internally
  251. * Implements row read and write access with the [row] operator using
  252. Segment_get_row() Segment_put_row() internally
  253. * Implements the get_row() and put_row() method using
  254. Segment_get_row() Segment_put_row() internally
  255. * Implements the flush_segment() method
  256. * Implements the copying of raster maps to segments and vice verse
  257. * Overwrites the open and close methods
  258. * No mathematical operation like __add__ and stuff for the Raster
  259. object (only for rows), since r.mapcalc is more sophisticated and
  260. faster
  261. """
  262. def __init__(self, name, srows=64, scols=64, maxmem=100,
  263. *args, **kargs):
  264. self.segment = Segment(srows, scols, maxmem)
  265. super(RasterSegment, self).__init__(name, *args, **kargs)
  266. def _get_mode(self):
  267. return self._mode
  268. def _set_mode(self, mode):
  269. if mode and mode.lower() not in ('r', 'w', 'rw'):
  270. str_err = _("Mode type: {0} not supported ('r', 'w','rw')")
  271. raise ValueError(str_err.format(mode))
  272. self._mode = mode
  273. mode = property(fget=_get_mode, fset=_set_mode,
  274. doc="Set or obtain the opening mode of raster")
  275. def __setitem__(self, key, row):
  276. """Return the row of Raster object, slice allowed."""
  277. if isinstance(key, slice):
  278. #Get the start, stop, and step from the slice
  279. return [self.put_row(ii, row)
  280. for ii in range(*key.indices(len(self)))]
  281. elif isinstance(key, tuple):
  282. x, y = key
  283. return self.put(x, y, row)
  284. elif isinstance(key, int):
  285. if key < 0: # Handle negative indices
  286. key += self._rows
  287. if key >= self._rows:
  288. raise IndexError(_("Index out of range: %r.") % key)
  289. return self.put_row(key, row)
  290. else:
  291. raise TypeError("Invalid argument type.")
  292. @must_be_open
  293. def map2segment(self):
  294. """Transform an existing map to segment file.
  295. """
  296. row_buffer = Buffer((self._cols), self.mtype)
  297. for row in range(self._rows):
  298. libraster.Rast_get_row(
  299. self._fd, row_buffer.p, row, self._gtype)
  300. self.segment.put_row(row, row_buffer)
  301. @must_be_open
  302. def segment2map(self):
  303. """Transform the segment file to a map.
  304. """
  305. row_buffer = Buffer((self._cols), self.mtype)
  306. for row in range(self._rows):
  307. row_buffer = self.segment.get_row(row, row_buffer)
  308. libraster.Rast_put_row(self._fd, row_buffer.p, self._gtype)
  309. @must_be_open
  310. def get_row(self, row, row_buffer=None):
  311. """Return the row using the `segment.get_row` method
  312. :param row: specify the row number
  313. :type row: int
  314. :param row_buffer: specify the Buffer object that will be instantiate
  315. :type row_buffer: Buffer object
  316. >>> elev = RasterRowIO(test_raster_name)
  317. >>> elev.open('r')
  318. >>> for row in elev:
  319. ... row
  320. Buffer([11, 21, 31, 41], dtype=int32)
  321. Buffer([12, 22, 32, 42], dtype=int32)
  322. Buffer([13, 23, 33, 43], dtype=int32)
  323. Buffer([14, 24, 34, 44], dtype=int32)
  324. >>> elev.close()
  325. >>> with RasterSegment(test_raster_name) as elev:
  326. ... for row in elev:
  327. ... row
  328. Buffer([11, 21, 31, 41], dtype=int32)
  329. Buffer([12, 22, 32, 42], dtype=int32)
  330. Buffer([13, 23, 33, 43], dtype=int32)
  331. Buffer([14, 24, 34, 44], dtype=int32)
  332. """
  333. if row_buffer is None:
  334. row_buffer = Buffer((self._cols), self.mtype)
  335. return self.segment.get_row(row, row_buffer)
  336. @must_be_open
  337. def put_row(self, row, row_buffer):
  338. """Write the row using the `segment.put_row` method
  339. :param row: a Row object to insert into raster
  340. :type row: Buffer object
  341. Input and output must have the same type in case of row copy
  342. >>> map_a = RasterSegment(test_raster_name)
  343. >>> map_b = RasterSegment(test_raster_name + "_segment")
  344. >>> map_a.open('r')
  345. >>> map_b.open('w', mtype="CELL", overwrite=True)
  346. >>> for row in xrange(map_a.info.rows):
  347. ... map_b[row] = map_a[row] + 1000
  348. >>> map_a.close()
  349. >>> map_b.close()
  350. >>> map_b = RasterSegment(test_raster_name + "_segment")
  351. >>> map_b.open("r")
  352. >>> for row in map_b:
  353. ... row
  354. Buffer([1011, 1021, 1031, 1041], dtype=int32)
  355. Buffer([1012, 1022, 1032, 1042], dtype=int32)
  356. Buffer([1013, 1023, 1033, 1043], dtype=int32)
  357. Buffer([1014, 1024, 1034, 1044], dtype=int32)
  358. >>> map_b.close()
  359. """
  360. self.segment.put_row(row, row_buffer)
  361. @must_be_open
  362. def get(self, row, col):
  363. """Return the map value using the `segment.get` method
  364. :param row: Specify the row number
  365. :type row: int
  366. :param col: Specify the column number
  367. :type col: int
  368. >>> elev = RasterSegment(test_raster_name)
  369. >>> elev.open('r')
  370. >>> for i in xrange(4):
  371. ... elev.get(i,i)
  372. 11
  373. 22
  374. 33
  375. 44
  376. >>> elev.close()
  377. >>> with RasterSegment(test_raster_name) as elev:
  378. ... elev.get(0,0)
  379. ... elev.get(1,1)
  380. ... elev.get(2,2)
  381. ... elev.get(3,3)
  382. 11
  383. 22
  384. 33
  385. 44
  386. """
  387. return self.segment.get(row, col)
  388. @must_be_open
  389. def put(self, row, col, val):
  390. """Write the value to the map using the `segment.put` method
  391. :param row: Specify the row number
  392. :type row: int
  393. :param col: Specify the column number
  394. :type col: int
  395. :param val: Specify the value that will be write to the map cell
  396. :type val: value
  397. >>> map_a = RasterSegment(test_raster_name)
  398. >>> map_b = RasterSegment(test_raster_name + "_segment")
  399. >>> map_a.open('r')
  400. >>> map_b.open('w', mtype="FCELL", overwrite=True)
  401. >>> for row in xrange(map_a.info.rows):
  402. ... for col in xrange(map_a.info.cols):
  403. ... value = map_a.get(row,col)
  404. ... map_b.put(row,col,value + 100)
  405. >>> map_a.close()
  406. >>> map_b.close()
  407. >>> map_b = RasterSegment(test_raster_name + "_segment")
  408. >>> map_b.open("r")
  409. >>> for row in map_b:
  410. ... row
  411. Buffer([ 111., 121., 131., 141.], dtype=float32)
  412. Buffer([ 112., 122., 132., 142.], dtype=float32)
  413. Buffer([ 113., 123., 133., 143.], dtype=float32)
  414. Buffer([ 114., 124., 134., 144.], dtype=float32)
  415. >>> map_b.close()
  416. """
  417. self.segment.val.value = val
  418. self.segment.put(row, col)
  419. def open(self, mode=None, mtype=None, overwrite=None):
  420. """Open the map, if the map already exist: determine the map type
  421. and copy the map to the segment files;
  422. else, open a new segment map.
  423. :param mode: specify if the map will be open with read, write or
  424. read/write mode ('r', 'w', 'rw')
  425. :type mode: str
  426. :param mtype: specify the map type, valid only for new maps: CELL,
  427. FCELL, DCELL
  428. :type mtype: str
  429. :param overwrite: use this flag to set the overwrite mode of existing
  430. raster maps
  431. :type overwrite: bool
  432. """
  433. # read rows and cols from the active region
  434. self._rows = libraster.Rast_window_rows()
  435. self._cols = libraster.Rast_window_cols()
  436. self.mode = mode if mode else self.mode
  437. self.mtype = mtype if mtype else self.mtype
  438. self.overwrite = overwrite if overwrite is not None else self.overwrite
  439. if self.exist():
  440. self.info.read()
  441. self.cats.mtype = self.mtype
  442. self.cats.read()
  443. self.hist.read()
  444. if ((self.mode == "w" or self.mode == "rw") and
  445. self.overwrite is False):
  446. str_err = _("Raster map <{0}> already exists. Use overwrite.")
  447. fatal(str_err.format(self))
  448. # We copy the raster map content into the segments
  449. if self.mode == "rw" or self.mode == "r":
  450. self._fd = libraster.Rast_open_old(self.name, self.mapset)
  451. self._gtype = libraster.Rast_get_map_type(self._fd)
  452. self.mtype = RTYPE_STR[self._gtype]
  453. # initialize the segment, I need to determine the mtype of the
  454. # map
  455. # before to open the segment
  456. self.segment.open(self)
  457. self.map2segment()
  458. self.segment.flush()
  459. self.cats.read()
  460. self.hist.read()
  461. if self.mode == "rw":
  462. #warning(_(WARN_OVERWRITE.format(self)))
  463. # Close the file descriptor and open it as new again
  464. libraster.Rast_close(self._fd)
  465. self._fd = libraster.Rast_open_new(
  466. self.name, self._gtype)
  467. # Here we simply overwrite the existing map without content copying
  468. elif self.mode == "w":
  469. #warning(_(WARN_OVERWRITE.format(self)))
  470. self._gtype = RTYPE[self.mtype]['grass type']
  471. self.segment.open(self)
  472. self._fd = libraster.Rast_open_new(self.name, self._gtype)
  473. else:
  474. if self.mode == "r":
  475. str_err = _("Raster map <{0}> does not exist")
  476. raise OpenError(str_err.format(self.name))
  477. self._gtype = RTYPE[self.mtype]['grass type']
  478. self.segment.open(self)
  479. self._fd = libraster.Rast_open_new(self.name, self._gtype)
  480. @must_be_open
  481. def close(self, rm_temp_files=True):
  482. """Close the map, copy the segment files to the map.
  483. :param rm_temp_files: if True all the segments file will be removed
  484. :type rm_temp_files: bool
  485. """
  486. if self.mode == "w" or self.mode == "rw":
  487. self.segment.flush()
  488. self.segment2map()
  489. if rm_temp_files:
  490. self.segment.close()
  491. else:
  492. self.segment.release()
  493. libraster.Rast_close(self._fd)
  494. # update rows and cols attributes
  495. self._rows = None
  496. self._cols = None
  497. self._fd = None
  498. def random_map_only_columns(mapname, mtype, overwrite=True, factor=100):
  499. region = Region()
  500. random_map = RasterRow(mapname)
  501. row_buf = Buffer((region.cols, ), mtype,
  502. buffer=(np.random.random(region.cols,) * factor).data)
  503. random_map.open('w', mtype, overwrite)
  504. for _ in range(region.rows):
  505. random_map.put_row(row_buf)
  506. random_map.close()
  507. return random_map
  508. def random_map(mapname, mtype, overwrite=True, factor=100):
  509. region = Region()
  510. random_map = RasterRow(mapname)
  511. random_map.open('w', mtype, overwrite)
  512. for _ in range(region.rows):
  513. row_buf = Buffer((region.cols, ), mtype,
  514. buffer=(np.random.random(region.cols,) * factor).data)
  515. random_map.put_row(row_buf)
  516. random_map.close()
  517. return random_map
  518. def raster2numpy(rastname, mapset=''):
  519. """Return a numpy array from a raster map
  520. :param str rastname: the name of raster map
  521. :parar str mapset: the name of mapset containig raster map
  522. """
  523. with RasterRow(rastname, mapset=mapset, mode='r') as rast:
  524. return np.array(rast)
  525. def raster2numpy_img(rastname, region, color="ARGB", array=None):
  526. """Convert a raster map layer into a string with
  527. 32Bit ARGB, 24Bit RGB or 8Bit Gray little endian encoding.
  528. Return a numpy array from a raster map of type uint8
  529. that contains the colored map data as 32 bit ARGB, 32Bit RGB
  530. or 8 bit image
  531. :param rastname: The name of raster map
  532. :type rastname: string
  533. :param region: The region to be used for raster map reading
  534. :type region: grass.pygrass.gis.region.Region
  535. :param color: "ARGB", "RGB", "GRAY1", "GRAY2"
  536. ARGB -> 32Bit RGB with alpha channel (0xAARRGGBB)
  537. RGB -> 32Bit RGB (0xffRRGGBB)
  538. GRAY1 -> grey scale formular: .33R+ .5G+ .17B
  539. GRAY2 -> grey scale formular: .30R+ .59G+ .11B
  540. :type color: String
  541. :param array: A numpy array (optional) to store the image,
  542. the array needs to setup as follows:
  543. array = np.ndarray((region.rows*region.cols*scale), np.uint8)
  544. scale = 4 in case of ARGB and RGB or scale = 1
  545. in case of Gray scale
  546. :type array: numpy.ndarray
  547. :return: A numpy array of size rows*cols*4 in case of ARGB, RGB and
  548. rows*cols*1 in case of gray scale
  549. Attention: This function will change the computational raster region
  550. of the current process while running.
  551. """
  552. from copy import deepcopy
  553. region_orig = deepcopy(region)
  554. # Set the raster region
  555. region.set_raster_region()
  556. scale = 1
  557. color_mode = 1
  558. if color.upper() == "ARGB":
  559. scale = 4
  560. color_mode = 1
  561. elif color.upper() == "RGB":
  562. scale = 4
  563. color_mode = 2
  564. elif color.upper() == "GRAY1":
  565. scale = 1
  566. color_mode = 3
  567. elif color.upper() == "GRAY2":
  568. scale = 1
  569. color_mode = 4
  570. if array is None:
  571. array = np.ndarray((region.rows*region.cols*scale), np.uint8)
  572. libraster.Rast_map_to_img_str(rastname, color_mode,
  573. array.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)))
  574. # Restore the raster region
  575. region_orig.set_raster_region()
  576. return array
  577. def numpy2raster(array, mtype, rastname, overwrite=False):
  578. """Save a numpy array to a raster map
  579. :param obj array: a numpy array
  580. :param obj mtype: the datatype of array
  581. :param str rastername: the name of output map
  582. :param bool overwrite: True to overwrite existing map
  583. """
  584. reg = Region()
  585. if (reg.rows, reg.cols) != array.shape:
  586. msg = "Region and array are different: %r != %r"
  587. raise TypeError(msg % ((reg.rows, reg.cols), array.shape))
  588. with RasterRow(rastname, mode='w', mtype=mtype, overwrite=overwrite) as new:
  589. newrow = Buffer((array.shape[1],), mtype=mtype)
  590. for row in array:
  591. newrow[:] = row[:]
  592. new.put_row(newrow)
  593. if __name__ == "__main__":
  594. import doctest
  595. from grass.pygrass import utils
  596. from grass.pygrass.modules import Module
  597. Module("g.region", n=40, s=0, e=40, w=0, res=10)
  598. Module("r.mapcalc", expression="%s = row() + (10 * col())"%(test_raster_name),
  599. overwrite=True)
  600. Module("r.support", map=test_raster_name,
  601. title="A test map",
  602. history="Generated by r.mapcalc",
  603. description="This is a test map")
  604. cats="""11:A
  605. 12:B
  606. 13:C
  607. 14:D
  608. 21:E
  609. 22:F
  610. 23:G
  611. 24:H
  612. 31:I
  613. 32:J
  614. 33:K
  615. 34:L
  616. 41:M
  617. 42:n
  618. 43:O
  619. 44:P"""
  620. Module("r.category", rules="-", map=test_raster_name,
  621. stdin_=cats, separator=":")
  622. doctest.testmod()
  623. """Remove the generated vector map, if exist"""
  624. mset = utils.get_mapset_raster(test_raster_name, mapset='')
  625. if mset:
  626. Module("g.remove", flags='f', type='raster', name=test_raster_name)
  627. mset = utils.get_mapset_raster(test_raster_name + "_segment",
  628. mapset='')
  629. if mset:
  630. Module("g.remove", flags='f', type='raster',
  631. name=test_raster_name + "_segment")