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 steepestDescentImagesAffineDisplay(SDImages, IMGSize):
	
	IMG = list()

	for z in range(SDImages.shape[1]):
		IMG.append(numpy.reshape(numpy.take(SDImages, [z], axis = 1), IMGSize))
	
	IMG = numpy.concatenate(IMG, axis = 1)

	CCSegUtils.showIMG(IMG);
def jacobianAffineDisplay(jacobian, IMGSize):

	#% Displays the jacobian as an image in the current plot using imshow

	#IMG = cell(2, 6);
	# list of two empty lists
	IMG = list()
	IMG.append([])
	IMG.append([])

	for z in range(len(jacobian)):
	#for CurParameter = 1:6
		IMG[0].append(numpy.reshape(jacobian[z][0, :], IMGSize))
		IMG[1].append(numpy.reshape(jacobian[z][1, :], IMGSize))

	IMG = numpy.concatenate((numpy.concatenate(IMG[0], axis = 1), numpy.concatenate(IMG[1], axis = 1)), axis = 0)
	#IMG = cell2mat(IMG);
	CCSegUtils.showIMG(IMG)
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 weightedAffineInvComp(targetIMG, templateIMG, templateWeight, initialParameters, numIterations, targetIMGMask = None):

# Python port of lk_run_affine_for_comp
#% [varargout] = lk_run_affine_for_comp(targetIMG, templateIMG, InitialParameters, NumIterations)
#%
#% LUCAS-KANADE algorithm Inverse Compositional method, affine
#% transformation
#% Registers the image to the template, using composition to update the
#% parameters
#%
#% PARAMETERS
#%   targetIMG [M, N]: the input image
#%   templateIMG [TM, TN]: the target image
#%   InitialParameters [6, 1]: the initial transformation
#%   NumIterations [1]: the number of iterations to perform
#%
#% Copyright 2013, Chris Adamson, Murdoch Childrens Research Institute
#% See LICENSE for full license information.
#%

	displayStuff = False

	if displayStuff == True:
		pylab.clf()
		pylab.subplot(4, 3, 1); CCSegUtils.showIMG(targetIMG); pylab.title("Image");
		pylab.subplot(4, 3, 2); CCSegUtils.showIMG(templateIMG); pylab.title("Template");

	FY, FX = numpy.gradient(templateIMG)

	templateJacobian = jacobianAffine(templateIMG.shape)

	if displayStuff == True:
		pylab.subplot(4, 3, 3); CCSegUtils.showIMG(numpy.concatenate((FX, FY), axis = 1)); pylab.title('Template gradients');
		pylab.subplot(4, 3, 4); jacobianAffineDisplay(templateJacobian, templateIMG.shape); pylab.title('Template Jacobian');
	
#	% compute steepest descent images
	#[SDImages] = lk_sd_images_affine(FX, FY, Jacobian);
	SDImages = steepestDescentImagesAffine(FX, FY, templateJacobian)

#	TemplateWMatrix = spdiags(TemplateW(:), 0, numel(TemplateW), numel(TemplateW));
	templateWeightMatrix = scipy.sparse.spdiags(numpy.ravel(templateWeight), numpy.array([0]), numpy.size(templateWeight), numpy.size(templateWeight))

#	H = full(SDImages' * TemplateWMatrix * SDImages);
	Hessian = numpy.matrix(SDImages).T * templateWeightMatrix * numpy.matrix(SDImages)
	#print Hessian	
#	SDImages = full(TemplateWMatrix * SDImages);
	SDImages = templateWeightMatrix * numpy.matrix(SDImages)

	#rint templateWeightMatrix

	if displayStuff == True:
		pylab.subplot(4, 3, 8); steepestDescentImagesAffineDisplay(SDImages, templateIMG.shape); pylab.title('Steepest descent images');
		pylab.subplot(4, 3, 10); CCSegUtils.showIMG(Hessian); pylab.title('Hessian');

	curParameters = initialParameters
	(targetIMGToTemplate, TX, TY, errorIMG, LKCost) = weightedAffineInvCompWarpCost(targetIMG, templateIMG, templateWeight, curParameters, displayStuff, targetIMGMask = targetIMGMask)
	
	if numpy.isinf(LKCost):
		return (curParameters, LKCost)

	del targetIMGToTemplate; del TX; del TY;
	#[~, ~, ~, ErrorIMG, CostValue] = lk_weighted_run_affine_inv_comp_warpcost(targetIMG, templateIMG, TemplateW, CurParameters, displayStuf    f);
	
#	for CurIter = 1:NumIterations
	for curIter in range(numIterations):

		if(displayStuff == True):
			pylab.subplot(4, 3, 7);
			CCSegUtils.showIMG(errorIMG); pylab.title('Error Image');
		
		SDUpdate = scipy.linalg.solve(Hessian, numpy.matrix(SDImages).T * numpy.matrix(numpy.atleast_2d(numpy.ravel(errorIMG))).T)
		
		if(displayStuff == True):
			pylab.subplot(4, 3, 11);
			pylab.cla()
			pylab.bar(numpy.arange(0, numpy.size(SDUpdate)), SDUpdate); pylab.title('SD Updates');

#		compose the new warp
#		make the transformation matrix used to transform the coordinates
		
		curParametersMatrix = numpy.concatenate((numpy.reshape(curParameters, (2, 3), order='F'), numpy.matrix([0, 0, 1])), axis = 0)
		curParametersMatrix[0, 0] = curParametersMatrix[0, 0] + 1.0
		curParametersMatrix[1, 1] = curParametersMatrix[1, 1] + 1.0

#		CurParametersMatrix = [reshape(CurParameters, 2, 3); 0 0 1];
#		CurParametersMatrix(1, 1) = CurParametersMatrix(1, 1) + 1;
#		CurParametersMatrix(2, 2) = CurParametersMatrix(2, 2) + 1;

		SDUpdateMatrix = numpy.concatenate((numpy.reshape(SDUpdate, (2, 3), order = 'F'), numpy.matrix([0, 0, 1])), axis = 0)
		SDUpdateMatrix[0, 0] = SDUpdateMatrix[0, 0] + 1.0
		SDUpdateMatrix[1, 1] = SDUpdateMatrix[1, 1] + 1.0
		#print curParameters
		#print curParametersMatrix
		#print "SDUpdateMatrix"
		#print SDUpdateMatrix
		
		# matrix division, solve composedMatrix * SDUpdateMatrix = curParametersMatrix for composedMatrix
		# numpy has no equivalent, so solve for
		# SDUpdateMatrix^T * composedMatrix^T = curParametersMatrix
		# then traspose the result

		composedMatrix = scipy.linalg.solve(SDUpdateMatrix.T, curParametersMatrix.T).T
		
		composedMatrix[0, 0] = composedMatrix[0, 0] - 1.0
		composedMatrix[1, 1] = composedMatrix[1, 1] - 1.0
		#print "Composed Matrix"
		#print composedMatrix	
		
		composedMatrix = numpy.take(composedMatrix, [0, 1], axis = 0)
		curParameters = numpy.ravel(composedMatrix, order = 'F')
		#print curParameters

		if(displayStuff == True):
			pylab.subplot(4, 3, 12)
			pylab.cla()
			pylab.bar(numpy.arange(0, numpy.size(curParameters)), curParameters); pylab.title('Parameters');
			F = pylab.gcf()
			F.set_size_inches((20, 10), forward = True)
		
		(targetIMGToTemplate, TX, TY, errorIMG, LKCost) = weightedAffineInvCompWarpCost(targetIMG, templateIMG, templateWeight, curParameters, displayStuff, targetIMGMask = targetIMGMask)
		if numpy.isinf(LKCost):
			#print "InfCost"
			return (curParameters, LKCost)
		if displayStuff == True:
			pylab.draw()
			pylab.show(block = False)
		#quit()

		#composedMatrix = curParametersMatrix
#		SDUpdateMatrix = [reshape(SDUpdate, 2, 3); 0 0 1];
#		SDUpdateMatrix(1, 1) = SDUpdateMatrix(1, 1) + 1;
#		SDUpdateMatrix(2, 2) = SDUpdateMatrix(2, 2) + 1;
#		%SDUpdateMatrix = inv(SDUpdateMatrix);
#		
#		%ComposedMatrix = CurParametersMatrix * SDUpdateMatrix;
#		ComposedMatrix = CurParametersMatrix / SDUpdateMatrix;
#		ComposedMatrix = ComposedMatrix(1:2, :);
#		CurParameters = ComposedMatrix(:);
#		CurParameters(1) = CurParameters(1) - 1;
#		CurParameters(4) = CurParameters(4) - 1;
#		%CurParameters = CurParameters + SDUpdate;
#		
#		ParameterHistory(:, CurIter) = CurParameters;
#
#		if(displayStuff == true)
#			subplot(4, 3, 12);
#			bar(CurParameters); title('Parameters');
#			drawnow;
#		end
#		%disp([num2str(CurIter) ': ' num2str(ObjectiveFunction(CurIter))]);
#		%urParameters
#		%keyboard;
#		[~, ~, ~, ErrorIMG, CostValue] = lk_weighted_run_affine_inv_comp_warpcost(targetIMG, templateIMG, TemplateW, CurParameters, displayStuff);
#	end
#
	#pylab.show()
	return (curParameters, LKCost)