'''
calc_area.py
compute the muscle cross-section area on the scan plane
input:
A pre-processed image with cross-section roughly cropped
The scale where the image was taken from CATMAID data in um/pixel
The pennation angle to project the cross-section area

output: 
A thresholded plot with muscle area segmented
The PCSA of muscle (if given plane angle of muscle)
The ACSA of muscle (if given pennation angle between muscle-tendon)

usage: 

preprocessed images stored in analysis/results/catmaid results

naming convention: z{cropping plane}_zoom{zoom level in CATMAID at cropping}_{muscle name}_t.png

python calc_area.py -i "z4798_zoom1.5_tibia_flexor_t.png" -s 50/240 -a 41.72
python calc_area.py -i "z4798_zoom1.5_tibia_extensor_t.png" -s 50/240 -a 46
python calc_area.py -i "z6783_zoom1.5_trochanter_extensor_t.png" -s 50/240 -a 37.72
python calc_area.py -i "z5488_zoom1.5_trochanter_flexor_t.png" -s 50/240 -a 50.96
python calc_area.py -i "z4688_zoom1.5_sterno-tergo-trochanter_extensor_t.png" -s 50/240 -a 35.54
python calc_area.py -i "z6293_zoom1.5_accesory_trochanter_flexor_t.png" -s 50/240 -a 36.52
python calc_area.py -i "z2484_zoom1.5_pleural_promotor_t.png" -s 50/240 -a 49.75
python calc_area.py -i "z2753_zoom1.5_pleural_remotor_and_abductor_t.png" -s 50/240 -a 24.62
python calc_area.py -i "z3424_zoom1.5_sternal_abductor_t.png" -s 50/240 -a 81.14
python calc_area.py -i "z3113_zoom1.5_sternal_anterior_rotator_t.png" -s 50/240 -a 78.56
python calc_area.py -i "z2753_zoom1.5_sternal_posterior_rotator_t.png" -s 50/240 -a 35.52
python calc_area.py -i "z2484_zoom1.5_tergo_pleural_promotor_t.png" -s 50/240 -a 49.75

'''

import cv2
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='Compute the muscle cross-section area across z-plane')
parser.add_argument('-i', '--input', required=True) 
parser.add_argument('-s', '--scale', type=str, required=True, help='Scaling factor 1D in form of fraction um/Pix') 
parser.add_argument('-a', '--angle', type=float, required=True, help='plane angle to project the cross-section to physiological cross-section') 
args = parser.parse_args()

fileName = args.input
num, denom = args.scale.split('/')
umPerPix = float(num) / float(denom)
cosAlpha = np.cos(args.angle/180*np.pi)
image1 = cv2.imread(fileName,-1)
ColorImage1 = cv2.cvtColor(image1,cv2.COLOR_RGB2GRAY)
ThresholdImage1 = cv2.bitwise_not(ColorImage1)
blur = cv2.GaussianBlur(ThresholdImage1,(5,5),0)
ret,ThresholdImage1 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
area = np.count_nonzero(ThresholdImage1)
realArea = area * cosAlpha * (umPerPix**2)
print('area_total is {:.4f},realArea is {:.4f}'.format(area,realArea))

  
# Using cv2.imwrite() method
# Saving the image
cv2.imwrite(fileName[:-4] + '_processed.png', ThresholdImage1)
cv2.imshow("threshold",ThresholdImage1)
cv2.waitKey(0)
cv2.destroyAllWindows()
