patch.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Apr 2 18:57:42 2013
  4. @author: pietro
  5. """
  6. from grass.pygrass.gis.region import Region
  7. from grass.pygrass.raster import RasterRow
  8. from grass.pygrass.functions import coor2pixel
  9. def get_start_end_index(bbox_list):
  10. """Convert a Bounding Box to a list of the index of
  11. column start, end, row start and end
  12. """
  13. ss_list = []
  14. reg = Region()
  15. for bbox in bbox_list:
  16. r_start, c_start = coor2pixel((bbox.west, bbox.north), reg)
  17. r_end, c_end = coor2pixel((bbox.east, bbox.south), reg)
  18. ss_list.append((int(r_start), int(r_end), int(c_start), int(c_end)))
  19. return ss_list
  20. def patch_row(rast, rasts, bboxes):
  21. """Patch a row of bound boxes."""
  22. sei = get_start_end_index(bboxes)
  23. # instantiate two buffer
  24. buff = rasts[0][0]
  25. rbuff = rasts[0][0]
  26. r_start, r_end, c_start, c_end = sei[0]
  27. for row in xrange(r_start, r_end):
  28. for col, ras in enumerate(rasts):
  29. r_start, r_end, c_start, c_end = sei[col]
  30. buff = ras.get_row(row, buff)
  31. rbuff[c_start:c_end] = buff[c_start:c_end]
  32. rast.put_row(rbuff)
  33. def patch_map(raster, mapset, mset_str, bbox_list, overwrite=False):
  34. """Patch raster using a bounding box list to trim the raster."""
  35. # Instantiate the RasterRow input objects
  36. rast = RasterRow(raster, mapset)
  37. rtype = RasterRow(name=raster, mapset=mset_str % (0, 0))
  38. rtype.open('r')
  39. rast.open('w', mtype=rtype.mtype, overwrite=overwrite)
  40. rtype.close()
  41. rasts = []
  42. for row, rbbox in enumerate(bbox_list):
  43. rrasts = []
  44. for col in range(len(rbbox)):
  45. rrasts.append(RasterRow(name=raster, mapset=mset_str % (row, col)))
  46. rrasts[-1].open('r')
  47. rasts.append(rrasts)
  48. patch_row(rast, rrasts, rbbox)
  49. for rrast in rasts:
  50. for rast_ in rrast:
  51. rast_.close()
  52. rast.close()