def minimalExample(path):
    import cv2
    import matplotlib.pyplot as plt

    img = cv2.imread(path+'Check\\Img_0.jpg',0)
    print(img)
    #plt.imshow(img, cmap='Greys')
#    cv2.imshow('Original', img)
    
    edges = cv2.Canny(img,50,150) 
    cv2.imshow('Canny', edges)
    cv2.imwrite(path+'Check\\Img_0_Cannied_50-150.jpg', edges)
    
    contours, hierarchy = cv2.findContours(edges,cv2.cv.CV_RETR_EXTERNAL,cv2.cv.CV_CHAIN_APPROX_NONE)
    contours = tr.selectContour(contours)
    
    counter=-1
    for cnt in contours:
        counter += 1
        measureCuravture = tr.findMaxCurvatureInContour(img, cnt)
        measureCuravture = tr.smooth(measureCuravture)
        print('%d: max Curvature = %f \t' %(counter, max(measureCuravture)), end="")
        
        M = cv2.moments(cnt) 
        print('Area = %f \t' %M['m00'], end="")
    
        cntHull = cv2.convexHull(cnt, returnPoints=True)
        cntPoly=cv2.approxPolyDP(cnt, epsilon=1, closed=True)
        MHull = cv2.moments(cntHull)
        MPoly = cv2.moments(cntPoly)
        print('Area after Convec Hull = %f \t Area after apporxPoly = %f \t' %(MHull['m00'], MPoly['m00']), end="")
    
    x, y =img.shape
    size = (w, h, channels) = (x, y, 1)
    canvas = np.zeros(size, np.uint8)
    cv2.drawContours(canvas, cnt, -1, 255)
    cv2.imwrite(path+'Check\\Img_0_ContoursCnt.jpg', canvas)
    
    canvas = np.zeros(size, np.uint8)
    cv2.drawContours(canvas, cntHull, -1, 255)
    cv2.imwrite(path+'Check\\Img_0_ContoursCntHull.jpg', canvas)
    canvas = np.zeros(size, np.uint8)
    cv2.drawContours(canvas, cntPoly, -1, 255)
    cv2.imwrite(path+'Check\\Img_0_ContoursCntPoly.jpg', canvas)
def runSym(path, geoTJ, plot=False, show=False):
    SMOOTHING_WINDOW=11
    daugtherChannelMiddel = (geoTJ[0]+ geoTJ[1]+ 0.0)/2.0
    filenames, leng = sortPhotosPCO(path, prefixleng=10)
    
    symmetry = np.zeros(leng, dtype=float)
    symmetry.fill(SYM_ERROR_NR)
    centroid_y = np.zeros(leng, dtype=float)
    
    for ii in range(leng):
        readPath=path+filenames[ii].fn
        symmetry[ii], centroid_y[ii] = symmetryOfOutline(readPath, plot=False)
    
    xarr = range(leng)
    for ii in range(len(symmetry)-1, -1, -1 ):
        if symmetry[ii] == SYM_ERROR_NR:
            del symmetry[ii]
            del xarr[ii]
            
    if plot:
        fig = plt.figure(figsize=(8, 6), dpi=200,); ax = fig.add_subplot(111)
        plt.plot(xarr, np.abs(symmetry), 's', linestyle='None')
        smooth_sym = tr.smooth(np.abs(symmetry),window_len=11,window='hanning')
        plt.plot(xarr, smooth_sym[:-1], 'r', linestyle='--')
        
        fig = plt.figure(figsize=(8, 6), dpi=200,); ax = fig.add_subplot(111)
        plt.plot(xarr, centroid_y - daugtherChannelMiddel, 'or', linestyle='None')
        smooth_cent = tr.smooth((centroid_y - daugtherChannelMiddel),window_len=11,window='hanning')
        plt.plot(xarr, smooth_cent[:-1], 'b', linestyle='--')
        plt.xlabel('Picture #')
        plt.ylabel('Difference Centreline and y-centroid')
        plt.xlim([100, 220])
        
    print('length actual = %d and images %d' %(len(centroid_y), leng))
#    dx1, count = forwardDifferenc(centroid_y - daugtherChannelMiddel)
    dx2, count = centralDifferenc(centroid_y - daugtherChannelMiddel)
    
    
#    smooth_centdx1 = tr.smooth((dx1),window_len=11,window='hanning')
    smooth_centdx2 = tr.smooth((dx2),window_len=SMOOTHING_WINDOW,window='hanning')

    
    #look a differential and define threshold above which it is not in SS
    threshSSLost=0.1 #TODO: adjust this to take into account units?
    endIndex=np.where(smooth_centdx2[:-SMOOTHING_WINDOW] > threshSSLost)
    if not endIndex: #if condition is never satisfied
        endIndex = ERROR_CODE-1
    
    steadyStateReachedOnFrame =endIndex[0][-1] +1
    s = "Steady state reached on frame %d" %steadyStateReachedOnFrame
    
    fig = plt.figure(figsize=(8, 6), dpi=200,); ax = fig.add_subplot(111)
#    plt.plot(xarr, dx1, 'or', linestyle='None', label='Result Forward Difference')
    plt.plot(xarr, dx2, 'sb', linestyle='None', label='Result Central Difference')
#    plt.plot(xarr, smooth_centdx1[:-1], 'r', linestyle='--', label = 'Smoothed Forward Difference')
    plt.plot(xarr, smooth_centdx2[:-1], 'r',linewidth=3, linestyle='--', label = 'Smoothed Central Difference')

    xmin, xmax = plt.xlim()
    dif = xmax - steadyStateReachedOnFrame
#    plt.xlim([int(xmax - 2.5* dif),len(width1) xmax])
    plt.xlim([100, 220])
    
    ymin, ymax = plt.ylim()
#    plt.ylim([-0.2, ymax])
    plt.plot([steadyStateReachedOnFrame, steadyStateReachedOnFrame], [-0.2, ymax], 'y',linewidth=2, linestyle='-', label = 'SS reached (on # %d)' %steadyStateReachedOnFrame)
    
    plt.xlabel('Picture #')
    plt.ylabel('Gradient of Difference Centreline and y-centroid')
    plt.legend(loc='best')
    
    ax.text(0.05, 0.2, s, fontsize=12, horizontalalignment='left', verticalalignment='center', transform = ax.transAxes)
    
    sp1=path.rfind('\\')
    sp2=path[:sp1].rfind('\\')
    sp3=path[:sp2].rfind('\\')
    directory=path[:sp2]
#    print(directory)
    fullpath=directory + "\\%s_GradientCentreline.jpg" %path[sp3+1:sp2]
    
    if not os.path.exists(path[:sp3] + "\\Symmetry"): os.makedirs(path[:sp3] + "\\Symmetry")
    fullpath2=path[:sp3] + "\\Symmetry\\%s_GradientCentreline.jpg" %path[sp3+1:sp2]
    
    plt.title(path[sp3+1:sp2] + ' Difference Centreline')
#    print(fullpath)
    plt.savefig(fullpath, dpi=300)
    plt.savefig(fullpath2, dpi=300)
    
    if show:
        plt.show()
    else:
        plt.close(fig)
    
    return steadyStateReachedOnFrame
def findSymmetryByCentreline(path, geoTJ, plot=False, show=False):
    '''
    Evaluate the point when capsule has reached a steady state from distance of
    centroid from centreline of daugther channel.
    
    The centreline is found from top and bottom of daugther channel, stored in 
    geoTJ. 
    
    -Input-
    path        path to folder with result file from run (folder that stores images)
    geoTJ       4 int values in pixels, related to the geometry: 
                    -top daugther channel
                    -bottom daugther channel
                    -left side of main channel
                    -right side of main channel
    
    plot        plot results
    show        show plots
    
    -Output-
    framesToSS      number of frames from max width to steady state
    distanceToSS    distance (in pixelse) from max width to steady state
    frameMaxWidth   Frame on which max width was reached
    frameSS         Frame on which steady state was reached
    
    
    TODO: This still assumes that there are no gaps in capsules tracking. This
    can be checked using the array "number". 
    
    '''
    #Constants
    SMOOTHING_WINDOW=11
    CUTOFF_LEFT = 0.2
    CUTOFF_RIGHT = 0.8
    #look a differential and define threshold above which capsule is not in Steady state
    THRESH_SS_LOST=0.1 #TODO: adjust this to take into account units?
    
    
    daugtherChannelMiddel = (geoTJ[0]+ geoTJ[1]+ 0.0)/2.0
    
    
    
    centroid_x_fromFile, centroid_y_fromFile, _, _, _, width1, _, _ = rof.readResultsFile(path) 
    
    readCentroidsFromOutlines = True
    #check whether file centroid positions contains only whole numbers
    for ii in range(len(centroid_x_fromFile)):
        if not np.equal(np.mod(centroid_x_fromFile[ii], 1), 0) or not np.equal(np.mod(centroid_y_fromFile[ii], 1), 0):
            readCentroidsFromOutlines=False
            centroid_x, centroid_y = centroid_x_fromFile, centroid_y_fromFile
            break;
            
    if readCentroidsFromOutlines:
        #Older versions of the script analysising the images (track_capsule_TJ)
        #rounded centroid positions to an integer, so need to find centroid position from
        #re-anaylising contour. For new result files, this is unnessecary and centroid 
        #position can be read from the results file
        centroid_x,centroid_y, number = findCentroidFromOutline(path)
            
    #find the point of maximum widht of capsule
    index=np.arange(len(width1))
    widthShort1=width1[int(CUTOFF_LEFT*len(width1)):int(CUTOFF_RIGHT*len(width1))]
    indexShort=index[int(CUTOFF_LEFT*len(width1)):int(CUTOFF_RIGHT*len(width1))]
    #TODO: ensure its that last index where max width is reached!
    maxwidth1=np.max(widthShort1)            
    indS = np.argmax(widthShort1)
    indexMaxWidth = indexShort[indS]    
    
    dx2, count = centralDifferenc(centroid_y - daugtherChannelMiddel)

    smooth_centdx2 = tr.smooth((dx2),window_len=SMOOTHING_WINDOW,window='hanning')

    endIndex=np.where(smooth_centdx2[:-SMOOTHING_WINDOW] > THRESH_SS_LOST)
    if not endIndex: #if condition is never satisfied
        endIndex = ERROR_CODE-1
    
    steadyStateReachedOnFrame =endIndex[0][-1] +1
    s = "Steady state reached on frame %d" %(steadyStateReachedOnFrame)
    
    #distance traveled to reach SS
    distanceToSS = np.sqrt( (centroid_x[steadyStateReachedOnFrame] - centroid_x[indexMaxWidth])**2 + (centroid_y[steadyStateReachedOnFrame] - centroid_y[indexMaxWidth])**2 )
    
    if plot:  #mainly for testing purposes
        xarr = range(len(centroid_y))
        fig = plt.figure(figsize=(8, 6), dpi=200,); ax = fig.add_subplot(111)
        plt.plot(xarr, centroid_y - daugtherChannelMiddel, 'or', linestyle='None')
        smooth_cent = tr.smooth(np.array(centroid_y - daugtherChannelMiddel).flatten(),window_len=11,window='hanning')
        plt.plot(xarr, smooth_cent[:-1], 'b', linestyle='--')
        plt.xlabel('Picture #')
        plt.ylabel('Difference Centreline and y-centroid')
        plt.xlim([0, 220])
        
        fig = plt.figure(figsize=(8, 6), dpi=200,); ax = fig.add_subplot(111)
        plt.plot(xarr, dx2, 'sb', linestyle='None', label='Result Central Difference')
        plt.plot(xarr, smooth_centdx2[:-1], 'r',linewidth=3, linestyle='--', label = 'Smoothed Central Difference')
    
#        xmin, xmax = plt.xlim(); dif = xmax - steadyStateReachedOnFrame; plt.xlim([int(xmax - 2.5* dif), xmax])
        plt.xlim([0, 220])
        
        ymin, ymax = plt.ylim()
    #    plt.ylim([-0.2, ymax])
        plt.plot([steadyStateReachedOnFrame, steadyStateReachedOnFrame], [-0.2, ymax], 'y',linewidth=2, linestyle='-', label = 'SS reached (on # %d)' %steadyStateReachedOnFrame)
        
        plt.xlabel('Picture #')
        plt.ylabel('Gradient of Difference Centreline and y-centroid')
        plt.legend(loc='best')
        
        ax.text(0.05, 0.2, s, fontsize=12, horizontalalignment='left', verticalalignment='center', transform = ax.transAxes)
        
        if show:
            plt.show()
        else:
            plt.close(fig)
    #framesToSS, distanceToSS, frameMaxWidth, frameSS         
    return steadyStateReachedOnFrame - indexMaxWidth +0.0, distanceToSS, indexMaxWidth, steadyStateReachedOnFrame