thumbnails.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. #!/usr/bin/env python
  2. #
  3. # thumbnails.py: Create thumbnail sample images of the various GRASS color rules
  4. #
  5. # AUTHOR: Python version by Glynn Clements
  6. # Earlier Bourne script version by Hamish Bowman,
  7. # http://grasswiki.osgeo.org/wiki/Talk:Color_tables
  8. #
  9. # (C) 2009-2013 by the GRASS Development Team
  10. # This program is free software under the GNU General Public
  11. # License (>=v2). Read the file COPYING that comes with GRASS
  12. # for details.
  13. #
  14. import sys
  15. import os
  16. import atexit
  17. import string
  18. import array
  19. import grass.script as grass
  20. tmp_img = None
  21. tmp_grad_abs = None
  22. tmp_grad_rel = None
  23. height = 85
  24. width = 15
  25. def cleanup():
  26. if tmp_img:
  27. grass.try_remove(tmp_img)
  28. if tmp_grad_rel:
  29. grass.run_command('g.remove', rast = tmp_grad_rel, quiet = True)
  30. if tmp_grad_abs:
  31. grass.run_command('g.remove', rast = tmp_grad_abs, quiet = True)
  32. # def rotate(src, dst):
  33. # grass.call(["convert", "-rotate", "90", src, dst])
  34. def read_ppm(src):
  35. fh = open(src, "rb")
  36. text = fh.read()
  37. fh.close()
  38. i = 0
  39. j = text.find('\n', i)
  40. if text[i:j] != 'P6':
  41. raise IOError
  42. i = j + 1
  43. j = text.find('\n', i)
  44. w, h = text[i:j].split()
  45. if int(w) != width or int(h) != height:
  46. raise IOError
  47. i = j + 1
  48. j = text.find('\n', i)
  49. maxval = text[i:j]
  50. if int(maxval) != 255:
  51. raise IOError
  52. i = j + 1
  53. return array.array('B', text[i:])
  54. def write_ppm(dst, data):
  55. w = height
  56. h = width
  57. fh = open(dst, "wb")
  58. fh.write("P6\n%d %d\n%d\n" % (w, h, 255))
  59. data.tofile(fh)
  60. fh.close()
  61. def rotate_ppm(srcd):
  62. dstd = array.array('B', len(srcd) * '\0')
  63. for y in xrange(height):
  64. for x in xrange(width):
  65. for c in xrange(3):
  66. dstd[(x * height + (height - 1 - y)) * 3 + c] = srcd[(y * width + x) * 3 + c]
  67. return dstd
  68. def flip_ppm(srcd):
  69. dstd = array.array('B', len(srcd) * '\0')
  70. stride = width * 3
  71. for y in xrange(height):
  72. dy = (height - 1 - y)
  73. dstd[dy * stride:(dy + 1) * stride] = srcd[y * stride:(y + 1) * stride]
  74. return dstd
  75. def ppmtopng(dst, src):
  76. if grass.find_program("g.ppmtopng", '--help'):
  77. grass.run_command('g.ppmtopng', input = src, output = dst, quiet = True)
  78. elif grass.find_program("pnmtopng"):
  79. fh = open(dst, 'wb')
  80. grass.call(["pnmtopng", src], stdout = fh)
  81. fh.close()
  82. elif grass.find_program("convert"):
  83. grass.call(["convert", src, dst])
  84. else:
  85. grass.fatal(_("Cannot find g.ppmtopng, pnmtopng or convert"))
  86. def convert_and_rotate(src, dst, flip = False):
  87. ppm = read_ppm(src)
  88. if flip:
  89. ppm = flip_ppm(ppm)
  90. ppm = rotate_ppm(ppm)
  91. write_ppm(tmp_img, ppm)
  92. ppmtopng(dst, tmp_img)
  93. def make_gradient(path):
  94. fh = open(path)
  95. text = fh.read()
  96. fh.close()
  97. lines = text.splitlines()
  98. records = list()
  99. for line in lines:
  100. if line.startswith("#"):
  101. # skip comments
  102. continue
  103. if len(line) == 0:
  104. # skip empty lines
  105. continue
  106. records.append(line.split())
  107. records = [record for record in records if record[0] != 'nv' and record[0] != 'default']
  108. relative = False
  109. absolute = False
  110. for record in records:
  111. if record[0].endswith("%"):
  112. relative = True
  113. record[0] = record[0].rstrip("%")
  114. else:
  115. absolute = True
  116. if absolute:
  117. if relative:
  118. minval = -0.04
  119. maxval = 0.04
  120. else:
  121. minval = float(records[0][0])
  122. maxval = float(records[-1][0])
  123. maxval = min(maxval, 2500000)
  124. grad = tmp_grad_abs
  125. grass.mapcalc("$grad = if(row()==1, float($min), float($max))",
  126. grad = tmp_grad_abs, min = minval, max = maxval, quiet = True)
  127. else:
  128. grad = tmp_grad_rel
  129. return grad
  130. def make_image(output_dir, table, grad, discrete = False):
  131. if discrete:
  132. lines, cols = height, 1
  133. else:
  134. lines, cols = None, None
  135. grass.run_command("r.colors", map = grad, color = table, quiet = True)
  136. grass.run_command("d.colortable", flags = 'n', map = grad,
  137. lines = lines, cols = cols, quiet = True)
  138. outfile = os.path.join(output_dir, "colortables", "%s.png" % table)
  139. convert_and_rotate(tmp_img, outfile, discrete)
  140. def main():
  141. global tmp_img, tmp_grad_abs, tmp_grad_rel
  142. os.environ['GRASS_OVERWRITE'] = '1'
  143. color_dir = os.path.join(os.environ['GISBASE'], "etc", "colors")
  144. output_dir = os.path.join(os.environ['GISBASE'], "docs", "html")
  145. if not os.path.exists(output_dir):
  146. os.makedirs(output_dir)
  147. pid = os.getpid()
  148. tmp_grad_abs = "tmp_grad_abs_%d" % pid
  149. tmp_grad_rel = "tmp_grad_rel_%d" % pid
  150. tmp_img = grass.tempfile() + ".ppm"
  151. os.environ['GRASS_WIDTH'] = '%d' % width
  152. os.environ['GRASS_HEIGHT'] = '%d' % height
  153. os.environ['GRASS_FRAME'] = '%f,%f,%f,%f' % (0,height,0,width)
  154. os.environ['GRASS_PNGFILE'] = tmp_img
  155. os.environ['GRASS_TRUECOLOR'] = 'TRUE'
  156. os.environ['GRASS_PNG_READ'] = 'FALSE'
  157. os.environ['GRASS_PNG_MAPPED'] = 'FALSE'
  158. os.environ['GRASS_TRANSPARENT'] = 'FALSE'
  159. os.environ['GRASS_BACKGROUNDCOLOR'] = 'ffffff'
  160. os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'
  161. for var in ['GRASS_LINE_WIDTH', 'GRASS_ANTIALIAS']:
  162. if var in os.environ:
  163. del os.environ[var]
  164. grass.use_temp_region()
  165. grass.run_command('g.region', rows = 100, cols = 100)
  166. grass.mapcalc("$grad = row()/1.0", grad = tmp_grad_rel, quiet = True)
  167. for table in os.listdir(color_dir):
  168. path = os.path.join(color_dir, table)
  169. grad = make_gradient(path)
  170. make_image(output_dir, table, grad)
  171. grass.mapcalc("$grad = row()", grad = tmp_grad_abs, quiet = True)
  172. for table in ['grey.eq', 'grey.log', 'random']:
  173. make_image(output_dir, table, tmp_grad_abs, True)
  174. if __name__ == "__main__":
  175. atexit.register(cleanup)
  176. main()