patch.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. start_row=0, start_col=0):
  35. """Patch raster using a bounding box list to trim the raster."""
  36. # Instantiate the RasterRow input objects
  37. rast = RasterRow(raster, mapset)
  38. rtype = RasterRow(name=raster, mapset=mset_str % (0, 0))
  39. rtype.open('r')
  40. rast.open('w', mtype=rtype.mtype, overwrite=overwrite)
  41. rtype.close()
  42. rasts = []
  43. for row, rbbox in enumerate(bbox_list):
  44. rrasts = []
  45. for col in range(len(rbbox)):
  46. rrasts.append(RasterRow(name=raster,
  47. mapset=mset_str % (start_row + row,
  48. start_col + col)))
  49. rrasts[-1].open('r')
  50. rasts.append(rrasts)
  51. patch_row(rast, rrasts, rbbox)
  52. for rrast in rasts:
  53. for rast_ in rrast:
  54. rast_.close()
  55. rast.close()
  56. #import ipdb; ipdb.set_trace()