def weightedAffineInvCompWarpCost(targetIMG, templateIMG, templateWeight, curParameters, displayStuff, targetIMGMask = None):
	#function [ImageWarpedToTemplate, TX, TY, ErrorIMG, CostValue] = lk_weighted_run_affine_inv_comp_warpcost(targetIMG, templateIMG, TemplateW, CurParameters, displayStuff)
#	[ImageWarpedToTemplate, TX, TY] = lk_warp_image_affine(targetIMG, size(templateIMG), CurParameters);
	targetIMGToTemplate, TX, TY = warpImageAffine(targetIMG, templateIMG.shape, curParameters)
	if displayStuff == True:
		pylab.subplot(4, 3, 5);	CCSegUtils.showIMG(targetIMGToTemplate); pylab.title('template coordinates warped to image');
		pylab.subplot2grid((4, 3), (1, 2), rowspan = 2, colspan = 1); pylab.cla(); CCSegUtils.showIMG(targetIMG);
			
		pylab.plot(TX[:, 0], TY[:, 0], 'b-')
		pylab.plot(TX[0, :], TY[0, :], 'b-')
		pylab.plot(TX[:, -1], TY[:, -1], 'b-')
		pylab.plot(TX[-1, :], TY[-1, :], 'b-')
		pylab.title('Coordinates on target')
	#print "oiajfdoijadsf"

	errorIMG = targetIMGToTemplate - templateIMG

	
	LKCost = numpy.sum(errorIMG * templateWeight * errorIMG)
	
	# find out if any coordinates are not in the mask
	if targetIMGMask != None:
		T = CCSegUtils.interp2q(numpy.arange(1, targetIMG.shape[1] + 1), numpy.arange(1, targetIMG.shape[0] + 1), targetIMGMask, TX, TY, extrapval = 0)
		if numpy.any(T == 0):
			LKCost = numpy.inf
	
	return (targetIMGToTemplate, TX, TY, errorIMG, LKCost)
def warpImageAffine(targetIMG, templateIMGSize, affineParameters):
#
#function [WarpedIMG, TX, TY] = lk_warp_image_affine(targetIMG, TemplateIMGSize, Parameters)
#
#% [WarpedImage] = lk_warp_image_affine(targetIMG, TemplateIMGSize, Parameters)
#% 
#% DESCRIPTION
#%   Warps an image onto a template using the affine parameters
#%   Parameters = [p1, p2, p3, p4, p5, p6];
#%   Assumes that the template coordinates are [1:size(TemplateIMGSize(2)), 1:size(TemplateIMGSize(1))]
#%
#% PARAMETERS
#%   targetIMG [InputM, InputN]: the input image
#%   TemplateIMGSize [2]: [M, N] the size of the template
#%
#% RETURNS
#%   WarpedImage [M, N]: the portion of the warped image that was in the boundary of the template
#%
#% In the algorithm, the template is the input and the TemplateIMGSize comes
#% from the I dont know
#%
#% Copyright 2013, Chris Adamson, Murdoch Childrens Research Institute
#% See LICENSE for full license information.
#%

#
#if(numel(Parameters) ~= 6)
#    error('Parameters should have 6 elements');
#end
	assert(numpy.size(affineParameters) == 6),"Affine parameters should have 6 elements"

#[TemplateX, TemplateY] = meshgrid(1:TemplateIMGSize(2), 1:TemplateIMGSize(1));
	templateX, templateY = numpy.meshgrid(numpy.arange(1, templateIMGSize[1] + 1), numpy.arange(1, templateIMGSize[0] + 1))

#XY = cat(1, TemplateX(:)', TemplateY(:)', ones(1, prod(TemplateIMGSize)));
	XY = numpy.concatenate((numpy.atleast_2d(numpy.ravel(templateX)), numpy.atleast_2d(numpy.ravel(templateY)), numpy.ones([1, numpy.prod(templateIMGSize)])), axis = 0)
	
	transformMatrix = numpy.matrix([[1 + affineParameters[0], affineParameters[2], affineParameters[4]], [affineParameters[1], 1 + affineParameters[3], affineParameters[5]], [0, 0, 1]])

	TXY = transformMatrix * XY
	#TXY = numpy.take(TXY, [0, 1], axis = 0)

	TX = numpy.array(numpy.reshape(numpy.take(TXY, [0], axis = 0), templateIMGSize))
	TY = numpy.array(numpy.reshape(numpy.take(TXY, [1], axis = 0), templateIMGSize))

	warpedIMG = CCSegUtils.interp2q(numpy.arange(1, targetIMG.shape[1] + 1), numpy.arange(1, targetIMG.shape[0] + 1), targetIMG, TX, TY, extrapval = 0)
	
	return (warpedIMG, TX, TY)
def thicknessCC(outputBase, groundTruthFile = None, numThicknessNodes = 100, doGraphics = False):
	
	assert(isinstance(numThicknessNodes, int) and numThicknessNodes > 0),"number of thickness nodes must be non-zero, positive and of type int"

	segMATFile = outputBase + "_seg.hdf5"
	segManeditMATFile = outputBase + "_seg_manedit.hdf5"
	
	assert(os.path.isfile(segMATFile)),"Seg mat file not found: " + segMATFile
	
	(outputDir, tail) = os.path.split(outputBase)
	subjectID = tail

	FID = h5py.File(segMATFile, 'r')
	
	seg = dict()

	seg['IMG'] = numpy.array(FID['IMG']);
	#seg['initialSeg'] = numpy.array(FID['initialSeg']) > 0
	seg['finalSeg'] = numpy.array(FID['finalSeg']) > 0
	seg['finalSegNoArtefacts'] = numpy.array(FID['finalSegNoArtefacts']) > 0 # the greater than 0 is to convert it to a boolean array
	seg['templatePixdims'] = numpy.array(FID['templatePixdims']) 
	#print seg['templatePixdims']
	FID.close()
	#print seg['IMG'].dtype

	#pylab.subplot(1, 4, 1); CCSegUtils.showIMG(seg['initialSeg'])
	#pylab.subplot(1, 4, 2); CCSegUtils.showIMG(seg['finalSeg'])
	#pylab.subplot(1, 4, 3); CCSegUtils.showIMG(seg['finalSegNoArtefacts'])
	#pylab.subplot(1, 4, 4); CCSegUtils.showIMG(seg['IMG'])
	
	
	#pylab.gcf().set_size_inches((20, 10), forward = True)
	#pylab.show()
	#quit()	
	if os.path.isfile(segManeditMATFile):
		print "using man edit seg"
		FID = h5py.File(segManeditMATFile, 'r')
		finalSeg = numpy.array(FID['finalSegManEdit']) > 0
		FID.close()	
	else:
		finalSeg = numpy.array(seg['finalSeg'])
	
	if doGraphics:
		outputPNG = os.path.join(outputDir, 'endpoint', subjectID + "_endpoints.png")
	else:
		outputPNG = None
	try:
		finalContours = LaplaceThicknessMethod.endpointsFind(finalSeg, outputPNG = outputPNG)
	except Exception as e:
		raise(e)
	
	#return

	xx, yy, scaledContours, streamlines, validStreamlines, solvedImage = LaplaceThicknessMethod.laplaceEquation2DContours(finalContours['xi'], finalContours['yi'], finalContours['xo'][::-1], finalContours['yo'][::-1], seg['templatePixdims'][0], seg['templatePixdims'][1], 1.0 / numpy.min(seg['templatePixdims']), 100, redoFactorisation = True)
	
	startV = numpy.zeros((2, numThicknessNodes))

	# make start points for each streamline
	for z in range(numThicknessNodes):
		D = numpy.diff(streamlines[z], axis = 1)
		cumArcLength = numpy.cumsum(numpy.sqrt(numpy.sum(D * D, axis = 0)))
		cumArcLength = cumArcLength / cumArcLength[-1]
		cumArcLength = numpy.concatenate((numpy.array([0]), cumArcLength))

		startV[0, z] = numpy.interp(0.5, cumArcLength, streamlines[z][0])
		startV[1, z] = numpy.interp(0.5, cumArcLength, streamlines[z][1])

	thicknessProfile = numpy.zeros((numThicknessNodes))
	for z in range(numThicknessNodes):
		D = numpy.diff(streamlines[z], axis = 1)

		thicknessProfile[z] = numpy.sum(numpy.sqrt(numpy.sum(D * D, axis = 0)))
	
	# here, we need to scale if we are using the longitudinal method
	FID = h5py.File(outputBase + "_midsag.hdf5", 'r')
	
	MSPMethod = FID['MSPMethod'].value
	if MSPMethod == 'long':
		flirtMAT = numpy.matrix(numpy.array(FID['flirtMAT']))
		(rotmat, skew, scales, transl, angles) = FLIRT.fsl_decomp_aff(flirtMAT)
		scales = numpy.diag(scales)
		
		D = numpy.abs(scales[0] - scales)
		if numpy.any(D > 1e-5):
			print "Scaling constants are not equal, this should not happen, using mean anyway"
		globalScale = numpy.mean(scales)
		print "global scale: " + str(globalScale)
		thicknessProfile = thicknessProfile / globalScale

	FID.close()
	thicknessProfile[numpy.logical_not(validStreamlines)] = 0

	registeredThicknessProfile = registerProfile(thicknessProfile)

	if doGraphics:
		PNGDirectory = os.path.join(outputDir, "thickness")
		try:
			os.makedirs(PNGDirectory)
		except OSError as exc: # Python >2.5
			if exc.errno == errno.EEXIST and os.path.isdir(PNGDirectory):
				pass
			else:
				raise Exception
		
			outputPNG = os.path.join(PNGDirectory, subjectID + "_thickness.png")

		pylab.clf()
		
		pylab.subplot(2, 1, 1)
		for z in range(len(streamlines)):
			if validStreamlines[z] == True:
				lineProps = {'color': 'b', 'linewidth': 2}
			else:
				lineProps = {'color': 'm', 'linewidth': 2}
			CCSegUtils.plotContour(streamlines[z], closed = False, lineProps = lineProps)
			
			if numpy.mod(z, 5) == 0:
				#pylab.text(streamlines[z][0, 0], streamlines[z][1, 0], str(z))startV[0, z], startV[1, z]
				pylab.text(startV[0, z], startV[1, z], str(z), horizontalalignment='center', verticalalignment='center', backgroundcolor='w')
			#CCSegUtils.plotContour(streamlinesOuter[z], closed = False)
			#CCSegUtils.plotContour(streamlinesInner[z], closed = False)
		lineProps = {'color': 'g', 'linewidth': 2}
		pylab.plot(scaledContours['inner'][0], scaledContours['inner'][1], **lineProps)
		lineProps = {'color': 'r', 'linewidth': 2}
		pylab.plot(scaledContours['outer'][0], scaledContours['outer'][1], **lineProps)
		
		pylab.gca().invert_yaxis()
		pylab.gca().get_xaxis().set_ticks([])
		pylab.gca().get_yaxis().set_ticks([])
		pylab.title('Streamlines')

		pylab.subplot(2, 1, 2)
		thicknessProfilePlot, = pylab.plot(thicknessProfile)
		registeredThicknessProfilePlot, = pylab.plot(registeredThicknessProfile)
		pylab.legend([thicknessProfilePlot, registeredThicknessProfilePlot], ['Original thickness profile', 'Registered thickness profile'], loc = 9)
		pylab.title('Thickness profile')
		pylab.xlabel('Node')
		pylab.ylabel('Thickness (mm)')

		#pylab.subplot(1, 2, 2); CCSegUtils.showIMG(FY, extent = [xx[0], xx[-1], yy[0], yy[-1]], ticks = True);
		#for z in range(numpy.size(sxi)):
		#	CCSegUtils.plotContour(streamlinesOuter[z], closed = False)
		#	CCSegUtils.plotContour(streamlinesInner[z], closed = False)
		#pylab.plot(scaledxi[0], scaledyi[0])
		#pylab.plot(scaledxo[0], scaledyo[0])
		
		#print scaledxi
		#print scaledyi
#	CCSegUtils.showIMG(FX)
		
		#print outputPNG
		pylab.savefig(outputPNG)
		CCSegUtils.cropAutoWhitePNG(outputPNG)
		
	#pylab.gcf().set_size_inches((20, 10), forward = True)
	#pylab.show()
	#quit()
	
	# perform Witelson and "Hofer and Frahm" parcellations on the CCs, output parcellations of the streamlines
	#../witelson_hoferfrahm_parcellation_schemes.png

	# first, get the leftmost and rightmost pixels

	maskClosed = numpy.isfinite(solvedImage)
	I = numpy.where(maskClosed)

	minCol = numpy.min(I[1])
	maxCol = numpy.max(I[1])

	minColRow = numpy.mean(I[0][numpy.where(I[1] == minCol)])  
	maxColRow = numpy.mean(I[0][numpy.where(I[1] == maxCol)])  
	pylab.clf()

	minColX = xx[minCol]
	minColY = yy[minColRow]
	maxColX = xx[maxCol]
	maxColY = yy[maxColRow]
	
	# get the slope of the line, rise over run
	cropLineM = (maxColY - minColY) / (maxColX - minColX)
	# get the Y intercept
	cropLineC = minColY - (minColX * cropLineM)

	#print str(cropLineM) + " * X + " + str(cropLineC)

	X, Y = numpy.meshgrid(xx, yy)
	
	midLineCross = Y - (cropLineM * X + cropLineC)
	#midLineCross = numpy.sign(midLineCross)
	
	witelsonLabels = numpy.zeros(maskClosed.shape, dtype = numpy.uint8)
	hoferFrahmLabels = numpy.zeros(maskClosed.shape, dtype = numpy.uint8)
	emsellLabels = numpy.zeros(maskClosed.shape, dtype = numpy.uint8)
	
	I = numpy.where(maskClosed)
	midLineCrossInMask = midLineCross[I]
	
	midLineCrossInMaskIMG = numpy.array(midLineCross)
	midLineCrossInMaskIMG[numpy.logical_not(maskClosed)] = numpy.nan

	validX = X[I]
	validY = Y[I]
	
	# according to the witelson and HoferFrahm parcellations, the lines of division are perpendicular to the line that cuts the CC
	# find the scalar projection of the vector go)ing from (minColX, minColY) to (validX, validY) on (minColX, minColY) -> (maxColX, maxColY)
	# construct vectors A and B, the scalar projection is A . B / |B|^2
	AX = validX - minColX
	AY = validY - minColY
	
	BX = maxColX - minColX
	BY = maxColY - minColY
	
	antPostProportion = (AX * BX + AY * BY) / (BX * BX + BY * BY)
	del AX
	del AY
	del BX
	del BY
	
	# because our images are posterior to anterior, we need to invert the direction, i.e.:
	antPostProportion = 1.0 - antPostProportion

	witelsonI = numpy.zeros(validX.shape, dtype = numpy.uint8)
	
	witelsonI[numpy.where(antPostProportion < (1.0 / 3.0))] = 1	
	witelsonI[numpy.where(numpy.logical_and(antPostProportion < (1.0 / 2.0), witelsonI == 0))] = 2	
	witelsonI[numpy.where(numpy.logical_and(antPostProportion < (2.0 / 3.0), witelsonI == 0))] = 3	
	witelsonI[numpy.where(numpy.logical_and(antPostProportion < (4.0 / 5.0), witelsonI == 0))] = 4	
	witelsonI[numpy.where(witelsonI == 0)] = 5	
	
	witelsonI[midLineCrossInMask > 0] = 0
	
	#SIMG = numpy.zeros(maskClosed.shape)
	#SIMG[I] = witelsonI
	witelsonLabels[I] = witelsonI
	
	hoferFrahmI = numpy.zeros(validX.shape, dtype = numpy.uint8)
	
	hoferFrahmI[numpy.where(antPostProportion < (1.0 / 6.0))] = 1	
	hoferFrahmI[numpy.where(numpy.logical_and(antPostProportion < (1.0 / 2.0), hoferFrahmI == 0))] = 2	
	hoferFrahmI[numpy.where(numpy.logical_and(antPostProportion < (2.0 / 3.0), hoferFrahmI == 0))] = 3	
	hoferFrahmI[numpy.where(numpy.logical_and(antPostProportion < (3.0 / 4.0), hoferFrahmI == 0))] = 4	
	hoferFrahmI[numpy.where(hoferFrahmI == 0)] = 5
	hoferFrahmI[midLineCrossInMask > 0] = 0
	
	hoferFrahmLabels[I] = hoferFrahmI

	emsellI = numpy.zeros(validX.shape, dtype = numpy.uint8)
	
	emsellI[numpy.where(antPostProportion < (1.0 / 6.0))] = 2
	emsellI[numpy.where(numpy.logical_and(antPostProportion < (1.0 / 3.0), numpy.logical_and(emsellI == 0, midLineCrossInMask <= 0)))] = 3
	emsellI[numpy.where(numpy.logical_and(antPostProportion < (1.0 / 2.0), numpy.logical_and(emsellI == 0, midLineCrossInMask <= 0)))] = 4
	emsellI[numpy.where(numpy.logical_and(antPostProportion < (2.0 / 3.0), numpy.logical_and(emsellI == 0, midLineCrossInMask <= 0)))] = 5
	emsellI[numpy.where(numpy.logical_and(antPostProportion < (4.0 / 5.0), numpy.logical_and(emsellI == 0, midLineCrossInMask <= 0)))] = 6
	emsellI[numpy.where(numpy.logical_and(emsellI == 0, midLineCrossInMask <= 0))] = 7
	emsellI[numpy.where(numpy.logical_and(emsellI == 0, antPostProportion > (1.0 / 2.0)))] = 8
	
	
	# we need to find the apex of the genu
	
	# it is the pixel closest to the rightmost element of the inferior boundary
	# firstly find out which contour is the inferior contour
	# it is the contour whose minimum y coordinate is greatest
	if numpy.min(scaledContours['inner'][1]) > numpy.min(scaledContours['outer'][1]):
		inferiorContourXY = numpy.array(scaledContours['inner'])
	else:
		inferiorContourXY = numpy.array(scaledContours['outer'])
	
	#print scaledContours
	# find the rightmost point
	rightMostInnerXY = numpy.take(inferiorContourXY, [numpy.argmax(inferiorContourXY[0])], axis = 1)
	
	# get the anterior-posterior proportion that is closest to this point
	
	rightMostInnerXYClosestIDX = numpy.argmin(numpy.abs(rightMostInnerXY[0] - validX) + numpy.abs(rightMostInnerXY[1] - validY))
	
	antPostProportionClosest = antPostProportion[rightMostInnerXYClosestIDX]
	midLineCrossInMaskClosest = midLineCrossInMask[rightMostInnerXYClosestIDX]

	emsellI[numpy.where(numpy.logical_and(numpy.logical_and(antPostProportion > antPostProportionClosest, antPostProportion < (1.0 / 2.0)), midLineCrossInMask > midLineCrossInMaskClosest))] = 1


	################### THIS DOESNT ALWAYS WORK ######################## NEW METHOD ABOVE
	# it is the pixel with the highest S value in the right half on the 0 contour of midLineCrossInMask
	
	# if pixels on 0 contour of midLineCrossInMask
	# make midLineCrossInMask image
	#midLineCrossInMaskIMG = numpy.zeros(maskClosed.shape)
	#midLineCrossInMaskIMG.fill(numpy.inf)
	# make SIMG
	#IMG = numpy.zeros(maskClosed.shape)
	#IMG.fill(numpy.nan)

	#midLineCrossInMaskIMG[I] = midLineCrossInMask
	#IMG[I] = S
	
	# the roll shifts elements down one row, so this says pixelsAtSignChangeIMG[I, J] = midLineCrossInMaskIMG[I, J] == 1 && midLineCrossInMaskIMG[I - 1, J] == -1

	#pixelsAtSignChangeIMG = numpy.logical_and(midLineCrossInMaskIMG == 1, numpy.roll(midLineCrossInMaskIMG, 1, axis = 0) < 1)
	
	#pixelsAtSignChange = pixelsAtSignChangeIMG[I]

	# find highest S in the right half 
	#SAtPixelsAtSignChange = S[pixelsAtSignChange]

	#R = 1
	#SC = 1
	#pylab.subplot(SR, SC, 1)
	#CCSegUtils.showIMG(FY, extent = [xx[0], xx[-1], yy[0], yy[-1]], ticks = True);
	#CCSegUtils.showIMG(midLineCrossInMaskIMG, extent = [xx[0], xx[-1], yy[0], yy[-1]], ticks = True)
	#pylab.plot(inferiorContourXY[0, rightMostIDX], inferiorContourXY[1, rightMostIDX], 'r*')
#	pylab.colorbar()
#	pylab.subplot(SR, SC, 2)
#	CCSegUtils.showIMG(midLineCrossInMaskIMG == 1)
#	
#	pylab.subplot(SR, SC, 3)
#	CCSegUtils.showIMG(pixelsAtSignChangeIMG)
#	
	#pylab.gcf().set_size_inches((20, 10), forward = True)
	#pylab.show()
	#quit()
#	
	
#	try:
#		SAtApex = numpy.max(SAtPixelsAtSignChange[SAtPixelsAtSignChange < (1.0 / 2.0)])
#		print "Proportion at rostrum apex: " + str(SAtApex)
#		emsellI[numpy.where(numpy.logical_and(numpy.logical_and(S > SAtApex, S < (1.0 / 2.0)), midLineCrossInMask > 0))] = 1
#	except Exception:
#		print "Rostrum apex not found, region 1 will be empty"
#
	emsellLabels[I] = emsellI
	
	# make RGB images
	witelsonRGB = numpy.tile(numpy.atleast_3d(numpy.double(maskClosed)), (1, 1, 3))
	hoferFrahmRGB = numpy.tile(numpy.atleast_3d(numpy.double(maskClosed)), (1, 1, 3))
	emsellRGB = numpy.tile(numpy.atleast_3d(numpy.double(maskClosed)), (1, 1, 3))
	
	#witelsonIMG = numpy.zeros(maskClosed.shape, dtype = numpy.uint8)
	#hoferFrahmIMG = numpy.zeros(maskClosed.shape, dtype = numpy.uint8)
	#emsellIMG = numpy.zeros(maskClosed.shape, dtype = numpy.uint8)

	#witelsonIMG[I] = witelsonLabels
	#hoferFrahmIMG[I] = hoferFrahmLabels
	#emsellIMG[I] = emsellLabels

	CMAP = numpy.array([[1, 1, 1], [1, 0, 0], [0, 0.5, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1], [0.5, 0, 0], [0, 1, 1], [1, 0, 0.5]])
	
	#emsellLabels = numpy.mod(emsellLabels, CMAP.shape[0])
	

	for z in range(3):
		T = witelsonRGB[:, :, z]
		T[I] = CMAP[witelsonLabels[I], z]
		witelsonRGB[:, :, z] = T
		T = hoferFrahmRGB[:, :, z]
		T[I] = CMAP[hoferFrahmLabels[I], z]
		hoferFrahmRGB[:, :, z] = T
		T = emsellRGB[:, :, z]
		T[I] = CMAP[emsellLabels[I], z]
		emsellRGB[:, :, z] = T
		del T
	
	del I
	del witelsonI
	del hoferFrahmI
	del emsellI

	#CCSegUtils.showIMG(maskClosed, extent = [xx[0], xx[-1], yy[0], yy[-1]])
	#pylab.subplot(2, 1, 1)
	#CCSegUtils.showIMG(witelsonRGB, extent = [xx[0], xx[-1], yy[0], yy[-1]])
	#pylab.title('Witelson parcellation')
	
	#pylab.subplot(2, 1, 2)
	#CCSegUtils.showIMG(hoferFrahmRGB, extent = [xx[0], xx[-1], yy[0], yy[-1]])
	#pylab.title('Hofer and Frahm parcellation')
	#pylab.plot(xx, cropLineM * xx + cropLineC, 'b-')

	#pylab.plot(minColX, minColY, 'g*')
	#pylab.plot(maxColX, maxColY, 'r*')

	#pylab.gcf().set_size_inches((20, 10), forward = True)
	#pylab.show()
	#pylab.savefig(outputPNG)
		

		
	witelsonNodeLabels = CCSegUtils.interp2q(xx, yy, numpy.double(witelsonLabels), startV[0], startV[1], interpmethod = 'nearest')
	witelsonNodeLabels = numpy.uint8(witelsonNodeLabels)
	
	hoferFrahmNodeLabels = CCSegUtils.interp2q(xx, yy, numpy.double(hoferFrahmLabels), startV[0], startV[1], interpmethod = 'nearest')
	hoferFrahmNodeLabels = numpy.uint8(hoferFrahmNodeLabels)
	
	emsellNodeLabels = CCSegUtils.interp2q(xx, yy, numpy.double(emsellLabels), startV[0], startV[1], interpmethod = 'nearest')
	emsellNodeLabels = numpy.uint8(emsellNodeLabels)
	
	if doGraphics:
		pylab.clf()
		
		lineProps = {'color': 'y', 'linewidth': 2}
		
		SR = 3
		SC = 1
		pylab.subplot(SR, SC, 1)
		CCSegUtils.showIMG(witelsonRGB, extent = [xx[0], xx[-1], yy[0], yy[-1]])
		for z in range(numThicknessNodes):
			pylab.text(startV[0, z], startV[1, z], str(witelsonNodeLabels[z]), horizontalalignment='center', verticalalignment='center')
		CCSegUtils.plotStreamlines(streamlines, lineProps = lineProps)
		pylab.title('Witelson parcellation')
		
		pylab.subplot(SR, SC, 2)
		CCSegUtils.showIMG(hoferFrahmRGB, extent = [xx[0], xx[-1], yy[0], yy[-1]])
		for z in range(numThicknessNodes):
			pylab.text(startV[0, z], startV[1, z], str(hoferFrahmNodeLabels[z]), horizontalalignment='center', verticalalignment='center')
		CCSegUtils.plotStreamlines(streamlines, lineProps = lineProps)
		pylab.title('Hofer and Frahm parcellation')

		pylab.subplot(SR, SC, 3)
		CCSegUtils.showIMG(emsellRGB, extent = [xx[0], xx[-1], yy[0], yy[-1]])
		for z in range(numThicknessNodes):
			pylab.text(startV[0, z], startV[1, z], str(emsellNodeLabels[z]), horizontalalignment='center', verticalalignment='center')
		CCSegUtils.plotStreamlines(streamlines, lineProps = lineProps)
		pylab.title('Emsell parcellation')

		parcellationPNGDirectory = os.path.join(outputDir, "parcellations")
		try:
			os.makedirs(parcellationPNGDirectory)
		except OSError as exc: # Python >2.5
			if exc.errno == errno.EEXIST and os.path.isdir(parcellationPNGDirectory):
				pass
			else:
				raise Exception

		outputPNG = os.path.join(parcellationPNGDirectory, subjectID + "_parcellations.png")
		
		pylab.gcf().set_size_inches((20, 10), forward = True)
		#pylab.show()
		#quit()

		pylab.savefig(outputPNG)
		CCSegUtils.cropAutoWhitePNG(outputPNG)
		
	pixelArea = (xx[1] - xx[0]) * (yy[1] - yy[0])
	# now do the stats
	witelsonStats = CCSegUtils.parcellationStats(witelsonLabels, pixelArea, thicknessProfile, witelsonNodeLabels)
	hoferFrahmStats = CCSegUtils.parcellationStats(hoferFrahmLabels, pixelArea, thicknessProfile, hoferFrahmNodeLabels)
	emsellStats = CCSegUtils.parcellationStats(emsellLabels, pixelArea, thicknessProfile, emsellNodeLabels)
	
	#print witelsonStats
	#print hoferFrahmStats

	#quit()
	outputMAT = outputBase + "_thickness.hdf5"

	FID = h5py.File(outputMAT, 'w')
	
	FID.create_dataset("xx", data = xx, compression = 'gzip')
	FID.create_dataset("yy", data = yy, compression = 'gzip')
	finalContoursGroup = FID.create_group("finalContours")
	finalContoursGroup.create_dataset("inner", data = scaledContours['inner'], compression = 'gzip')
	finalContoursGroup.create_dataset("outer", data = scaledContours['outer'], compression = 'gzip')
	
	#FID.create_dataset("startV", data = startV, compression = 'gzip')
	FID.create_dataset("validStreamlines", data = numpy.uint8(validStreamlines), compression = 'gzip')
	FID.create_dataset("thicknessProfile", data = thicknessProfile, compression = 'gzip')
	FID.create_dataset("registeredThicknessProfile", data = registeredThicknessProfile, compression = 'gzip')
	
	streamlinesGroup = FID.create_group("streamlines")
	for z in range(numThicknessNodes):
		streamlinesGroup.create_dataset(str(z), data = streamlines[z], compression = 'gzip')

	FID.create_dataset("solvedImage", data = solvedImage, compression = 'gzip')
	
	FID.create_dataset("witelsonLabels", data = witelsonLabels, compression = 'gzip')
	FID.create_dataset("witelsonNodeLabels", data = witelsonNodeLabels, compression = 'gzip')
	
	witelsonGroup = FID.create_group("witelsonStats")
	for curKey in witelsonStats.iterkeys():
		witelsonGroup.create_dataset(curKey, data = witelsonStats[curKey], compression = 'gzip')
	
	FID.create_dataset("hoferFrahmLabels", data = hoferFrahmLabels, compression = 'gzip')
	FID.create_dataset("hoferFrahmNodeLabels", data = hoferFrahmNodeLabels, compression = 'gzip')
	
	hoferFrahmGroup = FID.create_group("hoferFrahmStats")
	for curKey in hoferFrahmStats.iterkeys():
		hoferFrahmGroup.create_dataset(curKey, data = hoferFrahmStats[curKey], compression = 'gzip')
	
	FID.create_dataset("emsellLabels", data = emsellLabels, compression = 'gzip')
	FID.create_dataset("emsellNodeLabels", data = emsellNodeLabels, compression = 'gzip')
	
	emsellGroup = FID.create_group("emsellStats")
	for curKey in emsellStats.iterkeys():
		emsellGroup.create_dataset(curKey, data = emsellStats[curKey], compression = 'gzip')
	
	FID.create_dataset("startV", data = startV, compression = 'gzip')

	#FID.create_dataset("maskClosed", data = maskClosed, compression = 'gzip')

	FID.close()
def segCCToNativeOneFile(segIMG, outputBase, midSagMATFile, segMATFile, dilateToParaSag = False, flirtInterpType = 'trilinear'):
	
	FID = h5py.File(segMATFile, 'r')
	
	resampledAVWShape = numpy.array(FID['resampledAVWShape'])
	LKCropRows = numpy.array(FID['LKCropRows'])
	LKCropCols = numpy.array(FID['LKCropCols'])
	midSagAVWxx = numpy.array(FID['midSagAVWxx'])
	midSagAVWyy = numpy.array(FID['midSagAVWyy'])
	resamplexx = numpy.array(FID['resamplexx'])
	resampleyy = numpy.array(FID['resampleyy'])

	#print seg['templatePixdims']
	FID.close()
	#print seg['IMG'].dtype
	
	FID = h5py.File(midSagMATFile, 'r')
	
	MSPMethod = str(numpy.array(FID['MSPMethod']))
	
	FID.close()

	midSagAVW = numpy.array(FID['midSagAVW'])
	
	skullCrop = numpy.array(FID["skullCrop"]) # the initial cropping indices of the background
	originalOrientationString = str(numpy.array(FID['originalOrientationString']))
	originalNativeFile = str(numpy.array(FID['originalNativeFile']))
	originalNativeCroppedFile = str(numpy.array(FID['originalNativeCroppedFile']))
	flirtTemplateFile = str(numpy.array(FID['flirtTemplateFile']))
	
	if flirtTemplateFile == "***":
		flirtTemplateFile = CCSegUtils.MNI152FLIRTTemplate()
	
	flirtMAT = numpy.array(FID["flirtMAT"]) # the transformation between  originalNativeCroppedFile -> flirtTemplateFile
	flirtCropZerosRows = numpy.array(FID["flirtCropZerosRows"])
	flirtCropZerosCols = numpy.array(FID["flirtCropZerosCols"])

	
	#midSagAVW = midSagAVW[:, ::-1]
	#midSagAVW = numpy.rot90(midSagAVW, -1)
	FID.close()
	
	if not numpy.array_equal(flirtMAT.shape, (4, 4)):
		print "the flirt matrix should be a 4x4 array, it is not"
		return

	del FID


	#pylab.subplot(1, 4, 1); CCSegUtils.showIMG(seg['initialSeg'])
	#pylab.subplot(1, 4, 2); CCSegUtils.showIMG(seg['finalSeg'])
	#pylab.subplot(1, 4, 3); CCSegUtils.showIMG(seg['finalSegNoArtefacts'])
	#pylab.subplot(1, 4, 4); CCSegUtils.showIMG(seg['IMG'])
	
	finalSegResampledAVWSpace = numpy.zeros(resampledAVWShape, dtype = numpy.uint8)

	#finalSegResampledAVWSpace[LKOutput['cropRows'], LKOutput['cropCols']] = finalSeg
	finalSegResampledAVWSpace[LKCropRows[0]:(LKCropRows[1] + 1), LKCropCols[0]:(LKCropCols[1] + 1)] = segIMG
	midSagAVWX, midSagAVWY = numpy.meshgrid(midSagAVWxx, midSagAVWyy)
	
	finalSegMidSagAVWSpace = CCSegUtils.interp2q(resamplexx, resampleyy, numpy.double(finalSegResampledAVWSpace), midSagAVWX, midSagAVWY, interpmethod = 'nearest', extrapval = 0)
	
	flirtTemplateNII = nibabel.load(flirtTemplateFile)
	
	#print finalSegMidSagAVWSpace.shape
	finalSegTemplateSpace = numpy.zeros((flirtTemplateNII.shape[2], flirtTemplateNII.shape[1]), dtype = numpy.uint8)
	#print finalSegTemplateSpace.shape
	finalSegTemplateSpace[flirtCropZerosRows[0]:(flirtCropZerosRows[-1] + 1), flirtCropZerosCols[0]:(flirtCropZerosCols[-1] + 1)] = finalSegMidSagAVWSpace
	
	finalSegTemplateSpaceNIIData = numpy.zeros((flirtTemplateNII.shape[1], flirtTemplateNII.shape[0], flirtTemplateNII.shape[2]), dtype = numpy.uint8)

	#NIIData = flirtTemplateNII.get_data()
	#NIIData = numpy.rot90(NIIData, 1)
	
	#print "flirt template: " + flirtTemplateFile

	T = math.floor(flirtTemplateNII.shape[0] / 2)
	
	#print flirtTemplateNII
	#print finalSegTemplateSpaceNIIData.shape
	#print finalSegTemplateSpace.shape
	finalSegTemplateSpaceNIIData[:, T] = numpy.rot90(finalSegTemplateSpace[:, ::-1], -1)
	if dilateToParaSag == True:
		finalSegTemplateSpaceNIIData[:, T - 1] = numpy.rot90(finalSegTemplateSpace[:, ::-1], -1)
		finalSegTemplateSpaceNIIData[:, T + 1] = numpy.rot90(finalSegTemplateSpace[:, ::-1], -1)

	finalSegTemplateSpaceNIIData = numpy.uint8(numpy.rot90(finalSegTemplateSpaceNIIData, -1))
	
	newNII = nibabel.Nifti1Image(finalSegTemplateSpaceNIIData, flirtTemplateNII.get_affine())
	
	NIITempDir = tempfile.mkdtemp()
	nibabel.save(newNII, os.path.join(NIITempDir, 'test.nii.gz'))
	
	invFlirtMAT = numpy.linalg.inv(flirtMAT)
	numpy.savetxt(os.path.join(NIITempDir, 'test.mat'), invFlirtMAT, fmt = '%.18f')

	# run flirt to project the segmentation to native space
	CommandString = os.environ['FSLDIR'] + '/bin/flirt -in ' + os.path.join(NIITempDir, 'test') + ' -ref ' + originalNativeCroppedFile + ' -applyxfm -init ' + os.path.join(NIITempDir, 'test.mat') + ' -interp ' + flirtInterpType + ' -out ' + (outputBase + "_native_axial_cropped.nii.gz")
	#print CommandString
	os.system(CommandString)
	
	segNativeCroppedNII = nibabel.load((outputBase + "_native_axial_cropped.nii.gz"))

	originalNativeNII = nibabel.load(originalNativeFile)
	finalSegNativeNIIData = numpy.zeros(originalNativeNII.shape, dtype = segNativeCroppedNII.get_data().dtype)
	finalSegNativeNIIData = numpy.rot90(finalSegNativeNIIData, 1)
	finalSegNativeNIIData[skullCrop[0, 0]:(skullCrop[0, 1] + 1), skullCrop[1, 0]:(skullCrop[1, 1] + 1), skullCrop[2, 0]:(skullCrop[2, 1] + 1)] = numpy.rot90(segNativeCroppedNII.get_data(), 1)
	finalSegNativeNIIData = numpy.rot90(finalSegNativeNIIData, -1)
	
	#print skullCrop
	finalSegNativeSpaceNII = nibabel.Nifti1Image(finalSegNativeNIIData, originalNativeNII.get_affine())
	
	nibabel.save(finalSegNativeSpaceNII, (outputBase + "_native_axial.nii.gz"))
		
	os.system(os.environ['FSLDIR'] + '/bin/fslswapdim ' + (outputBase + "_native_axial.nii.gz") + ' ' + originalOrientationString + ' ' + (outputBase + "_native.nii.gz"))

	shutil.rmtree(NIITempDir)

	del newNII
	del T
def segCCToNative(outputBase, doGraphics = False, dilateToParaSag = False):
	midSagMATFile = outputBase + "_midsag.hdf5"
	
	assert(os.path.isfile(midSagMATFile)),"midsag hdf5 file not found"

	segMATFile = outputBase + "_seg.hdf5"
	segManeditMATFile = outputBase + "_seg_manedit.hdf5"
	
	#finalSeg = numpy.array(seg['finalSeg'])
	
	assert(os.path.isfile(segMATFile)),"Seg mat file not found: " + segMATFile
	
	FID = h5py.File(segMATFile, 'r')
	
	autoFinalSeg = numpy.array(FID['finalSegNoArtefacts'])	
	templatePixdims = numpy.array(FID['templatePixdims'])
	#print seg['templatePixdims']
	FID.close()
	#print seg['IMG'].dtype
	

	#pylab.subplot(1, 4, 1); CCSegUtils.showIMG(seg['initialSeg'])
	#pylab.subplot(1, 4, 2); CCSegUtils.showIMG(seg['finalSeg'])
	#pylab.subplot(1, 4, 3); CCSegUtils.showIMG(seg['finalSegNoArtefacts'])
	#pylab.subplot(1, 4, 4); CCSegUtils.showIMG(seg['IMG'])
	
	
	#pylab.gcf().set_size_inches((20, 10), forward = True)
	#pylab.show()
	#quit()	
	if os.path.isfile(segManeditMATFile):
		FID = h5py.File(segManeditMATFile, 'r')
		finalSeg = numpy.array(FID['finalSegManEdit']) > 0
		FID.close()	
	else:
		finalSeg = numpy.array(autoFinalSeg)
	
	segCCToNativeOneFile(numpy.uint8(finalSeg), outputBase + "_seg", midSagMATFile, segMATFile, dilateToParaSag = dilateToParaSag)
	#print finalSeg.shape
	thicknessMATFile = outputBase + "_thickness.hdf5"
	
	if os.path.isfile(thicknessMATFile):
		
		finalSegxx = numpy.arange(finalSeg.shape[1])
		finalSegyy = numpy.arange(finalSeg.shape[0])
		
		finalSegX, finalSegY = numpy.meshgrid(finalSegxx, finalSegyy)

		FID = h5py.File(thicknessMATFile, 'r')

		labelNames = ['witelson', 'hoferFrahm', 'emsell']

		for curLabels in labelNames:
			curLabelIMG = numpy.array(FID[curLabels + 'Labels'])
			# for the parcellations, we need to get the parcellation images in the same space as the segmentation images
			# so we resample the parcellation image using the grid of the segmentation image, we need to reverse a scaling that was performed in the thickness part:
			curLabelIMG = CCSegUtils.interp2q(numpy.array(FID['xx']) / templatePixdims[0], numpy.array(FID['yy']) / templatePixdims[1], numpy.double(curLabelIMG), finalSegX, finalSegY, interpmethod = 'nearest', extrapval = 0)
			
			#SR = 1
			#SC = 3
			#pylab.subplot(SR, SC, 1); CCSegUtils.showIMG(finalSeg)
			#pylab.subplot(SR, SC, 2); CCSegUtils.showIMG(curLabelIMG)
			#pylab.subplot(SR, SC, 3); CCSegUtils.showIMG(T)
			#pylab.gcf().set_size_inches((20, 10), forward = True)
			#pylab.show()
			#quit()	
			segCCToNativeOneFile(numpy.uint8(curLabelIMG), outputBase + "_parcellation_" + curLabels.lower(), midSagMATFile, segMATFile, flirtInterpType = 'nearestneighbour', dilateToParaSag = dilateToParaSag)
			
		FID.close()