netcdf_to_image_bw.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/env python3
  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 = str.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. Ndim = len(f_nc.variables[cv_nc].dimensions)
  28. if Ndim == 4:
  29. xfield = imult*f_nc.variables[cv_nc][0,0,:,:]
  30. elif Ndim == 3:
  31. xfield = imult*f_nc.variables[cv_nc][0,:,:]
  32. elif Ndim == 2:
  33. xfield = imult*f_nc.variables[cv_nc][:,:]
  34. else:
  35. print(' ERROR (mk_zonal_average.py) => weird shape for your mask array!')
  36. sys.exit(0)
  37. #xfield = imult*f_nc.variables[cv_nc][:,:]
  38. f_nc.close()
  39. (ny,nx) = nmp.shape(xfield)
  40. ifield = nmp.zeros((ny,nx), dtype=nmp.int16)
  41. xfield[:,:] = nmp.round(xfield[:,:], 0)
  42. ifield = xfield.astype(nmp.int16)
  43. # Cleaning overshoots:
  44. idx_too_small = nmp.where(ifield < 0)
  45. ifield[idx_too_small] = 0
  46. idx_too_large = nmp.where(ifield > 255)
  47. ifield[idx_too_large] = 255
  48. #print(ifield[:,22])
  49. ifield8 = ifield.astype(nmp.uint8)
  50. image = Image.fromarray(nmp.flipud(ifield8))
  51. # Then save it:
  52. image.save(cf_im)
  53. print(' *** Image '+cf_im+' saved!\n')