netcdf_to_image_clr.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/env python
  2. # B a r a K u d a
  3. #
  4. # L. Brodeau, 2017]
  5. import sys
  6. import numpy as nmp
  7. from PIL import Image
  8. import string
  9. import os
  10. from netCDF4 import Dataset
  11. l_fake_coor = True
  12. #l_fake_coor = False
  13. narg = len(sys.argv)
  14. if narg not in [4, 5]:
  15. print 'Usage: '+sys.argv[0]+' <netcdf_file.nc> <netcdf_variable> <image_extension (jpg,png,bmp,...)> (mutiple to field)'; sys.exit(0)
  16. cf_nc = sys.argv[1]
  17. cv_nc = sys.argv[2]
  18. ciext = sys.argv[3]
  19. imult = 1
  20. if narg == 5: imult = int(sys.argv[4])
  21. print imult
  22. cfname, cncext = os.path.splitext(cf_nc)
  23. cf_im = string.replace(os.path.basename(cf_nc), cncext, '.'+ciext)
  24. print ' *** Will create image '+cf_im
  25. # Reading data array:
  26. f_nc = Dataset(cf_nc)
  27. xfield = imult*f_nc.variables[cv_nc][:,:]
  28. f_nc.close()
  29. (ny,nx) = nmp.shape(xfield)
  30. #ifield = nmp.zeros((ny,nx), dtype=nmp.int16)
  31. ifield = np.zeros((ny,nx,3), dtype=np.uint8)
  32. print 'To be written!'
  33. sys.exit(0)
  34. xfield[:,:] = nmp.round(xfield[:,:], 0)
  35. ia = xfield.astype(nmp.int16)
  36. ifield[:,:,0] = ia*0.3
  37. # Cleaning overshoots:
  38. idx_too_small = nmp.where(ifield < 0)
  39. ifield[idx_too_small] = 0
  40. idx_too_large = nmp.where(ifield > 255)
  41. ifield[idx_too_large] = 255
  42. #print ifield[:,22]
  43. ifield8 = ifield.astype(nmp.uint8)
  44. image = Image.fromarray(nmp.flipud(ifield8))
  45. # Then save it:
  46. image.save(cf_im)
  47. print ' *** Image '+cf_im+' saved!\n'