__init__.py 26 KB

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