Guest User

Untitled

a guest
Feb 23rd, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. ## Converts Grayscale 16-bit TIFs to 8-bit TIFs
  2. ## Python 2.7.12
  3. ## James Fleming 10/02/2018
  4.  
  5. from PIL import Image
  6. import numpy
  7. import sys
  8. import os
  9.  
  10. def convert(filepath, scale=True):
  11. ## Loads Image As Array
  12. image = Image.open(filepath)
  13. image_array = numpy.array(image)
  14.  
  15. ## Validate Requirement For Conversion
  16. if image_array.dtype != 'uint16':
  17. return image
  18.  
  19. ## Scale If Required Or Clip
  20. if numpy.amax(image_array) > 255:
  21. if scale:
  22. scale_factor = numpy.amax(image_array)
  23. image_array *= (255 / scale_factor)
  24. print (filepath + ' scaled!')
  25. else:
  26. image_array[image_array > 255] = 255
  27. print (filepath + ' clipped!')
  28.  
  29. ## Convert To Uint8 Image
  30. converted_array = image_array.astype('uint8')
  31. converted_image = Image.fromarray(converted_array)
  32.  
  33. return converted_image
  34.  
  35. ## Command Line Utility
  36. if __name__ == "__main__":
  37.  
  38. ## Check Arguements
  39. if len(sys.argv) == 3:
  40. inpath = sys.argv[1]
  41. outpath = sys.argv[2]
  42. else:
  43. print 'Incorrect Arguments Given!'
  44.  
  45. ## Check If Input Exists
  46. if os.path.exists(inpath):
  47. ## Check If Single File Or Directory
  48. if os.path.isfile(inpath):
  49. convert(inpath).save(outpath)
  50. else:
  51. ## Create Ouput Folder If Required
  52. if not os.path.exists(outpath):
  53. os.mkdir(outpath)
  54.  
  55. ## Find All Valid Files
  56. for root, dirs, files in os.walk(inpath):
  57. for file in files:
  58. if file.endswith(".tif"):
  59. filepath = os.path.join(root, file)
  60. convertedpath = os.path.join(outpath, file)
  61.  
  62. ## Do Indivdual Conversion
  63. convert(filepath).save(convertedpath)
  64. print 'Converted ' + filepath
  65.  
  66. ## Input Non-Existent
  67. else:
  68. print 'Given input does not exist!'
Add Comment
Please, Sign In to add comment