##################################
# Lupin Image Parsing Pipeline
# Eli Ramthun 4/14/2018
#
#
# A program used to convert aerial images into black and white,
# ideally with lupin showing as black and everything else as white.
# Also used to analyze B/W ratios in an image.
#
# Usage: to convert, run `python lupin_pipeline.py -T -t 30 ./path_to_your_image.png'
# To analyze B/W, run `python lupin_pipeline.py -a /path_to_your_file.png'

import subprocess
import argparse
import sys
import os

def convert_VARI(image_name):
	# VARI (very[vari] bad)
	output_string = image_name[0:-4] + '_VARI.tif'
	command_string = 'convert ' + image_name + ' -fx \'(u.g-u.r)/(u.r+u.g-u.b+0.001)\' -normalize -compress lzw ' + output_string
	os.system(command_string)
	return output_string

def convert_TGI(image_name):
	# TGI (maybe better)
	output_string = image_name[0:-4] + '_TGI.tif'
	command_string = 'convert ' + image_name + ' -fx \'(u.g-(0.39*u.r)-(0.61*u.b))\' -negate -normalize -compress lzw ' + output_string
	os.system(command_string)
	return output_string

def convert_threshold(image_name,threshold=30):
	# converts image to black & white based on a threshold
	output_string = image_name[0:-4] + '_' + threshold + '.tif'
	command_string = 'convert ' + image_name + ' -threshold ' + threshold + '% ' + output_string
	os.system(command_string)
	# make thresholded image pure B&W
	command_string = 'convert ' + output_string + ' -monochrome ' + output_string
	os.system(command_string)
	return output_string

def black_white_breakdown(image_name):
	#returns a tuple of black and white pixel counts from an image
	command_string = 'convert ' + image_name + ' -define histogram:unique-colors=true -format %c histogram:info:-'
	output = subprocess.check_output(command_string, shell=True)
	output = output.splitlines()
	new_output = []
	for i in range(len(output)):
		output[i] = output[i].decode('UTF-8')
		new_output.append(output[i].split(':'))
	new_output = (new_output[0][0].strip(), new_output[1][0].strip())
	return new_output

def driver(args):
	input_image = args.filepath

	print(args)

	if args.TGI:
		print('attempting TGI conversion of ' + input_image)
		output_image = convert_TGI(input_image)
		print('initial conversion output as ' + output_image)
		if args.t:
			print('thresholding image at ' + args.t + '%.')
			threshold_output = convert_threshold(output_image, args.t)
			print('final image output as ' + threshold_output)
	elif args.VARI:
		print('attempting VARI conversion of ' + input_image)
		output_image = convert_VARI(input_image)
		print('initial conversion output as ' + output_image)
		if args.t:
			print('thresholding image at ' + args.t + '%.')
			threshold_output = convert_threshold(output_image, args.t)
			print('final image output as ' + threshold_output)

#	if (args.TGI or args.VARI) and args.t:
#		print('thresholding image at ' + args.t + '%.')
#		threshold_output = convert_threshold(output_image, args.t)
#		print('final image output as ' + threshold_output)
	elif args.t:
		print('thresholding image at ' + args.t + '%.')
		threshold_output = convert_threshold(input_image, args.t)
		print('final image output as ' + threshold_output)

	if args.analyze:
		print(black_white_breakdown(input_image))

	print('maybe it worked!')


if __name__ == '__main__':

	parser = argparse.ArgumentParser(description='Tool to convert RGB images to approximations of lupin converage.',prog='python ./lupin_pipeline.py')
	parser.add_argument("filepath", help='path to your file',type=str)
	parser.add_argument("-t",metavar="threshold",help='the threshold for the black & white image conversion process; higher numbers will have more noise. 0.1 - 100, recommended value 30',type=str)#,default='30')
	parser.add_argument("-a","--analyze",help='analyze black/white pixel breakdown of output image',action='store_true')
	conversion_method = parser.add_mutually_exclusive_group()
	conversion_method.add_argument("-T","--TGI",help='use the TGI algorithm to sense vegetation. default.', action="store_true")
	conversion_method.add_argument("-V","--VARI",help='use the VARI algorithm to sense vegetation. not advised.', action="store_true")


	args = parser.parse_args()
	driver(args)


