def findNearestNeighbourPixel(img, seg, i, j, segSize, fourConnected):
    """
    For the (i, j) pixel, choose which of the neighbouring
    pixels is the most similar, spectrally. 
    
    Returns tuple (ii, jj) of the row and column of the most
    spectrally similar neighbour, which is also in a 
    clump of size > 1. If none is found, return (-1, -1)
    """
    (nBands, nRows, nCols) = img.shape
    
    minDsqr = -1
    ii = jj = -1
    # Cope with image edges
    (iiiStrt, iiiEnd) = (max(i-1, 0), min(i+1, nRows-1))
    (jjjStrt, jjjEnd) = (max(j-1, 0), min(j+1, nCols-1))
    
    for iii in range(iiiStrt, iiiEnd+1):
        for jjj in range(jjjStrt, jjjEnd+1):
            connected = ((not fourConnected) or ((iii == i) or (jjj == j)))
            if connected:
                segNbr = seg[iii, jjj]
                if segSize[segNbr] > 1:
                    # Euclidean distance in spectral space. Note that because 
                    # we are only interested in the order, we don't actually 
                    # need to do the sqrt (which is expensive)
                    dSqr = ((img[:, i, j] - img[:, iii, jjj]) ** 2).sum()
                    if minDsqr < 0 or dSqr < minDsqr:
                        minDsqr = dSqr
                        ii = iii
                        jj = jjj
    
    return (ii, jj)