Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Converts Grayscale 16-bit TIFs to 8-bit TIFs
- ## Python 2.7.12
- ## James Fleming 10/02/2018
- from PIL import Image
- import numpy
- import sys
- import os
- def convert(filepath, scale=True):
- ## Loads Image As Array
- image = Image.open(filepath)
- image_array = numpy.array(image)
- ## Validate Requirement For Conversion
- if image_array.dtype != 'uint16':
- return image
- ## Scale If Required Or Clip
- if numpy.amax(image_array) > 255:
- if scale:
- scale_factor = numpy.amax(image_array)
- image_array *= (255 / scale_factor)
- print (filepath + ' scaled!')
- else:
- image_array[image_array > 255] = 255
- print (filepath + ' clipped!')
- ## Convert To Uint8 Image
- converted_array = image_array.astype('uint8')
- converted_image = Image.fromarray(converted_array)
- return converted_image
- ## Command Line Utility
- if __name__ == "__main__":
- ## Check Arguements
- if len(sys.argv) == 3:
- inpath = sys.argv[1]
- outpath = sys.argv[2]
- else:
- print 'Incorrect Arguments Given!'
- ## Check If Input Exists
- if os.path.exists(inpath):
- ## Check If Single File Or Directory
- if os.path.isfile(inpath):
- convert(inpath).save(outpath)
- else:
- ## Create Ouput Folder If Required
- if not os.path.exists(outpath):
- os.mkdir(outpath)
- ## Find All Valid Files
- for root, dirs, files in os.walk(inpath):
- for file in files:
- if file.endswith(".tif"):
- filepath = os.path.join(root, file)
- convertedpath = os.path.join(outpath, file)
- ## Do Indivdual Conversion
- convert(filepath).save(convertedpath)
- print 'Converted ' + filepath
- ## Input Non-Existent
- else:
- print 'Given input does not exist!'
Add Comment
Please, Sign In to add comment