Exemple #1
0
def chunk_lcn(chunk, sigma_mean, sigma_std, std_bias=0.0, rescale=1.0):
    """
    based on matlab code by Guanglei Xiong, see http://www.mathworks.com/matlabcentral/fileexchange/8303-local-normalization
    assuming chunk.shape == (num_examples, x, y, channels)

    'rescale' is an additional rescaling constant to get the variance of the result in the 'right' range.
    """
    means = np.zeros(chunk.shape, dtype=chunk.dtype)
    for k in xrange(len(chunk)):
        means[k] = filters.gaussian_filter(chunk[k],
                                           sigma_mean,
                                           multichannel=True)

    chunk = chunk - means  # centering
    del means  # keep memory usage in check

    variances = np.zeros(chunk.shape, dtype=chunk.dtype)
    chunk_squared = chunk**2
    for k in xrange(len(chunk)):
        variances[k] = filters.gaussian_filter(chunk_squared[k],
                                               sigma_std,
                                               multichannel=True)

    chunk = chunk / np.sqrt(variances + std_bias)

    return chunk / rescale
Exemple #2
0
def filter(data, filtType, par):

    if filtType == "sobel":
        filt_data = sobel(data)
    elif filtType == "roberts":
        filt_data = roberts(data)
    elif filtType == "canny":
        filt_data = canny(data)
    elif filtType == "lowpass_avg":
        from scipy import ndimage
        p = int(par)
        kernel = np.ones((p, p), np.float32) / (p * p)
        filt_data = ndimage.convolve(data, kernel)
    elif filtType == "lowpass_gaussian":

        s = float(par)
        filt_data = gaussian_filter(data, sigma=s)

    elif filtType == "highpass_gaussian":

        s = float(par)
        lp_data = gaussian_filter(data, sigma=s)
        filt_data = data - lp_data

    elif filtType == "highpass_avg":
        from scipy import ndimage
        p = int(par)
        kernel = np.ones((p, p), np.float32) / (p * p)
        lp_data = ndimage.convolve(data, kernel)
        filt_data = data - lp_data

    #elif filtType ==  "gradient":

    return filt_data
Exemple #3
0
def hybrid():

    # Read Images
    input_image_1 = skio.imread(INPUT_IMAGES_NAME[0])
    input_image_2 = skio.imread(INPUT_IMAGES_NAME[1])

    #----------------------------------------------------------------------

    # Transform to float
    image_1 = img_as_float(input_image_1)
    image_2 = img_as_float(input_image_2)

    #----------------------------------------------------------------------

    # Align images using provided functiom
    image_aligned_1, image_aligned_2 = align_images(image_1, image_2)

    #----------------------------------------------------------------------

    # Divide image in color channels
    color_channels_1 = np.array([
        image_aligned_1[:, :, 0], image_aligned_1[:, :, 1],
        image_aligned_1[:, :, 2]
    ])
    color_channels_2 = np.array([
        image_aligned_2[:, :, 0], image_aligned_2[:, :, 1],
        image_aligned_2[:, :, 2]
    ])

    # Use color channels to compose an unique gray scale image
    # http://stackoverflow.com/questions/12201577/how-can-i-convert-an-rgb-image-into-grayscale-in-python
    image_1_grayscale = np.clip(
        color_channels_1[0] * 0.299 + color_channels_1[1] * 0.587 +
        color_channels_1[2] * 0.114, 0.0, 1.0)
    image_2_grayscale = np.clip(
        color_channels_2[0] * 0.299 + color_channels_2[1] * 0.587 +
        color_channels_2[2] * 0.114, 0.0, 1.0)

    #----------------------------------------------------------------------

    # Apply the Laplacian Filter (high pass filter) to the first image by subtracting the Gaussian Filtered Image from the original
    low_frequency_image_1 = filter.gaussian_filter(image_1_grayscale,
                                                   HIGH_FREQUENCY_BLUR_RATIO)
    high_frequency_image_1 = image_1_grayscale - low_frequency_image_1

    # Apply the Gaussian Filter (low pass filter) to the second image
    low_frequency_image_2 = filter.gaussian_filter(image_2_grayscale,
                                                   LOW_FREQUENCY_BLUR_RATIO)

    #----------------------------------------------------------------------

    # Add pictures together
    output_image = np.clip(high_frequency_image_1 + low_frequency_image_2, 0.0,
                           1.0)

    #----------------------------------------------------------------------

    # Show final image
    skio.imshow(output_image)
    skio.show()
Exemple #4
0
def test_several_gaussian_filter():
    '''result:these are almost the same'''
    a = np.zeros((5, 5),np.float32)
    a[2, 2] = 1
    import vigra
    from skimage.filter import gaussian_filter

    print gaussian_filter(a,1)
    print vigra.gaussianSmoothing(a, 1)
    print ndimage.gaussian_filter(a, 1)
def smoothing_gauss(data, sigma=1, pseudo_3D='True', sliceId=2):
    if data.ndim == 3 and pseudo_3D:
        if sliceId == 2:
            for idx in range(data.shape[2]):
                temp = skifil.gaussian_filter(data[:, :, idx], sigma=sigma)
                data[:, :, idx] = (255 * temp).astype(np.uint8)
        elif sliceId == 0:
            for idx in range(data.shape[0]):
                temp = skifil.gaussian_filter(data[idx, :, :], sigma=sigma)
                data[idx, :, :] = (255 * temp).astype(np.uint8)
    else:
        data = skifil.gaussian_filter(data, sigma=sigma)
        data = (255 * data).astype(np.uint8)
    return data
    def smoothing(self, sigma_zero):
        """
        :param sigma_zero: initial sigma as a first smoothing
        :return:void (images are saved at disc space in path+ '/npy_arrays_3DGaussianFiltering'
        """
        path_to_save = '/3DGaussianSmoothing/'

        sigmas_x = (self.k ** self.powers) * sigma_zero
        sigmas_y = (self.k ** self.powers) * sigma_zero
        sigmas_z = ((self.k ** self.powers) * sigma_zero) / (self.spacing[2] / self.spacing[0])

        print(sigmas_x, sigmas_z)

        saving = SaveImage(self.path + path_to_save)

        for sigma_x, sigma_y, sigma_z in zip(sigmas_x, sigmas_y, sigmas_z):
            im = self.image.Image3D

            image = normalize(im, [np.min(im), np.max(im)], [-1.0, 1.0])

            print('befor ', np.min(image), np.max(image))
            smoothed_image = gaussian_filter(image, (sigma_x, sigma_y, sigma_z))
            smoothed_image = smoothed_image.astype(dtype=np.float32)

            smoothed_image = normalize(smoothed_image, [-1.0, 1.0], [0.0, 1.0])

            temp_image = deepcopy(self.image)
            temp_image.Image3D = smoothed_image

            temp_image.sigma = sigma_x

            saving.saveImage(temp_image)
    def smoothing(self, sigma_zero):
        """
        :param sigma_zero: initial sigma as a first smoothing
        :return:void (images are saved at disc space in path+ '/npy_arrays_2DGaussianFiltering'
        """

        path_to_save = '/2DGaussianSmoothing/'

        sigmas_x = (self.k ** self.powers) * sigma_zero / self.spacing[0]
        sigmas_y = (self.k ** self.powers) * sigma_zero / self.spacing[1]

        # make directory

        im = self.image.Image3D[:, :, 20]
        saving = SaveImage(self.path + path_to_save)
        for sigma_x, sigma_y in zip(sigmas_x, sigmas_y):
            image = normalize(im, [np.min(im), np.max(im)], [-1.0, 1.0])
            smoothed_image = gaussian_filter(image, (sigma_x, sigma_y))
            print(np.min(smoothed_image), np.max(smoothed_image))
            smoothed_image = normalize(smoothed_image, [-1.0, 1.0], [0.0, 1.0])
            temp_image = deepcopy(self.image)
            temp_image.Image3D = smoothed_image
            temp_image.sigma = sigma_x

            saving.saveImage(temp_image)
Exemple #8
0
def impyramid_next_level(_img, filter='burt_adelson'):
    """
    IMPYRAMID_NEXT_LEVEL: computes the next level in a Gaussian pyramidal
     decomposition.

    :param _img: numpy.ndarray
    A grey-level image (_img.ndim == 2)

    :param filter: string
    Which filter to use in removing high frequencies:
    - burt_adelson: [-0.125, 0.250, 0.375, 0.250, -0.125]
    - custom1: [0.125, 0.275, 0.375, 0.125]  (Gaussian, sigma=0.866)

    :return: numpy.ndarray
    The new level in the pyramid, an image half the size of the original.
    """

    assert (_img.ndim == 2)

    # classical low-pass filter, with the kernel from Burt & Adelson (1983):
    if filter == 'burt_adelson':
        a = 0.375
        krn = [1/4 - a/2, 1/4, a, 1/4, 1/4 - a/2]
        res = (_img - sepfir2d(_img, krn, krn))[::2, ::2]
    elif filter == 'custom1':
        res = gaussian_filter(_img, sigma=0.866)[::2, ::2]

    return res
def gradient_field(im):
    im = skimage_filter.gaussian_filter(im, 1.0)
    gradx = np.hstack([im[:, 1:], im[:, -2:-1]]) - np.hstack(
        [im[:, 0:1], im[:, :-1]])
    grady = np.vstack([im[1:, :], im[-2:-1, :]]) - np.vstack(
        [im[0:1, :], im[:-1, :]])
    return gradx, grady
Exemple #10
0
def label_nuclei(binary, min_size):
    '''Label, watershed and remove small objects'''

    distance = medial_axis(binary, return_distance=True)[1]

    distance_blured = gaussian_filter(distance, 5)

    local_maxi = peak_local_max(distance_blured,
                                indices=False,
                                labels=binary,
                                min_distance=30)

    markers = measure_label(local_maxi)

    #    markers[~binary] = -1

    #    labels_rw = segmentation.random_walker(binary, markers)

    #    labels_rw[labels_rw == -1] = 0

    #    labels_rw = segmentation.relabel_sequential(labels_rw)

    labels_ws = watershed(-distance, markers, mask=binary)

    labels_large = remove_small_objects(labels_ws, min_size)

    labels_clean_border = clear_border(labels_large)

    labels_from_one = relabel_sequential(labels_clean_border)

    #    plt.imshow(ndimage.morphology.binary_dilation(markers))
    #    plt.show()

    return labels_from_one[0]
Exemple #11
0
def label_nuclei(binary, min_size):
    '''Label, watershed and remove small objects'''

    distance = medial_axis(binary, return_distance=True)[1]

    distance_blured = gaussian_filter(distance, 5)

    local_maxi = peak_local_max(distance_blured, indices=False, labels=binary, min_distance = 30)

    markers = measure_label(local_maxi)

#    markers[~binary] = -1

#    labels_rw = segmentation.random_walker(binary, markers)

#    labels_rw[labels_rw == -1] = 0

#    labels_rw = segmentation.relabel_sequential(labels_rw)

    labels_ws = watershed(-distance, markers, mask=binary)

    labels_large = remove_small_objects(labels_ws,min_size)

    labels_clean_border = clear_border(labels_large)

    labels_from_one = relabel_sequential(labels_clean_border)

#    plt.imshow(ndimage.morphology.binary_dilation(markers))
#    plt.show()

    return labels_from_one[0]
Exemple #12
0
def preprocess_image(filename, simple_ds=4., mask_strength=None, nside_out=50):
    from PIL import Image
    from skimage.filter import gaussian_filter
    # open file
    x = np.array(Image.open(filename), dtype=np.float)
    if ((simple_ds > 1) & (simple_ds != None)):
        # Gaussian smooth with FWHM = "simple_ds" pixels.
        for i in range(3):
            x[:, :, i] = gaussian_filter(x[:, :, i], 1. * simple_ds / 2.355)
        # subsample by simple_ds.
        x = x[0::int(simple_ds), 0::int(simple_ds), :]
        # take inner nside_out x nside_out.
        ntmp = x.shape[0] - nside_out
        if (ntmp % 2) == 0:
            nside = ntmp / 2
            x = x[nside:-nside, nside:-nside, :]
        else:
            nside = (ntmp - 1) / 2
            x = x[nside + 1:-nside, nside + 1:-nside, :]
    # If desired, apply mask.
    if (mask_strength == None) | (mask_strength == 'none'):
        return x
    else:
        if (mask_strength == 'weak'): mask_thresh = 15.
        if (mask_strength == 'strong'): mask_thresh = 30.
        avg = np.mean(x, axis=-1)
        mask = get_mask(avg, thresh=mask_thresh)
        x *= mask[:, :, np.newaxis]
        return x
 def train(self, _dataSet):
     '''
     Trains Model for given dataset (ImageDataSet)
     '''
     sys.stderr.write("Got " + str(len(_dataSet.get_inputs())) + " images\n")
     for im in _dataSet.get_inputs():
         self.filtered.append(filter.gaussian_filter(im, self.sigma, multichannel=False))
Exemple #14
0
def impyramid_next_level(_img, filter='burt_adelson'):
    """
    IMPYRAMID_NEXT_LEVEL: computes the next level in a Gaussian pyramidal
     decomposition.

    :param _img: numpy.ndarray
    A grey-level image (_img.ndim == 2)

    :param filter: string
    Which filter to use in removing high frequencies:
    - burt_adelson: [-0.125, 0.250, 0.375, 0.250, -0.125]
    - custom1: [0.125, 0.275, 0.375, 0.125]  (Gaussian, sigma=0.866)

    :return: numpy.ndarray
    The new level in the pyramid, an image half the size of the original.
    """

    assert (_img.ndim == 2)

    # classical low-pass filter, with the kernel from Burt & Adelson (1983):
    if filter == 'burt_adelson':
        a = 0.375
        krn = [1 / 4 - a / 2, 1 / 4, a, 1 / 4, 1 / 4 - a / 2]
        res = (_img - sepfir2d(_img, krn, krn))[::2, ::2]
    elif filter == 'custom1':
        res = gaussian_filter(_img, sigma=0.866)[::2, ::2]

    return res
Exemple #15
0
def FH_Seg(filename,labelMask,minSize,c):
    rgbImg = io.imread(filename)
    width=rgbImg.shape[1]
    height=rgbImg.shape[0]
    labImg = color.rgb2lab(rgbImg)
    smooth_img=filter.gaussian_filter(labImg,sigma=0.8,multichannel=True)
    labelList=unique(labelMask)
    numSeg=len(labelList)
    pixelSet=UnionSet(width*height)
    threshold=[1.0/c]*(width*height)
    for currLabel in labelList:
        edgeList=creatEdgeList(smooth_img,labelMask,currLabel)
        segment_graph(edgeList,pixelSet,threshold,c,minSize)

    """
    现在已经有了pixelSet,接下来把每个labelMask标记成root的index,之后,用uniqueList找到对应的独立
    item,然后再用item的index(0:segNum)代替label中的不规则编号
    """
    segNum=pixelSet.setNum()
    mySegNum=0
    for i in range(width*height):
        if i==pixelSet.find(i):
            pixelSet.setNodeLabel(i,mySegNum)
            mySegNum+=1

    FH_Label=numpy.zeros((height,width))
    for y in range(height):
        for x in range(width):
            index=y*width+x
            FH_Label[y,x]=pixelSet.segLabel(index)

    return FH_Label
Exemple #16
0
    def smoothing(self, sigma_zero):
        """
        :param sigma_zero: initial sigma as a first smoothing
        :return:void (images are saved at disc space in path+ '/npy_arrays_3DGaussianFiltering'
        """
        path_to_save = '/3DGaussianSmoothing/'

        sigmas_x = (self.k**self.powers) * sigma_zero
        sigmas_y = (self.k**self.powers) * sigma_zero
        sigmas_z = ((self.k**self.powers) * sigma_zero) / (self.spacing[2] /
                                                           self.spacing[0])

        print(sigmas_x, sigmas_z)

        saving = SaveImage(self.path + path_to_save)

        for sigma_x, sigma_y, sigma_z in zip(sigmas_x, sigmas_y, sigmas_z):
            im = self.image.Image3D

            image = normalize(im, [np.min(im), np.max(im)], [-1.0, 1.0])

            print('befor ', np.min(image), np.max(image))
            smoothed_image = gaussian_filter(image,
                                             (sigma_x, sigma_y, sigma_z))
            smoothed_image = smoothed_image.astype(dtype=np.float32)

            smoothed_image = normalize(smoothed_image, [-1.0, 1.0], [0.0, 1.0])

            temp_image = deepcopy(self.image)
            temp_image.Image3D = smoothed_image

            temp_image.sigma = sigma_x

            saving.saveImage(temp_image)
Exemple #17
0
    def smoothing(self, sigma_zero):
        """
        :param sigma_zero: initial sigma as a first smoothing
        :return:void (images are saved at disc space in path+ '/npy_arrays_2DGaussianFiltering'
        """

        path_to_save = '/2DGaussianSmoothing/'

        sigmas_x = (self.k**self.powers) * sigma_zero / self.spacing[0]
        sigmas_y = (self.k**self.powers) * sigma_zero / self.spacing[1]

        # make directory

        im = self.image.Image3D[:, :, 20]
        saving = SaveImage(self.path + path_to_save)
        for sigma_x, sigma_y in zip(sigmas_x, sigmas_y):
            image = normalize(im, [np.min(im), np.max(im)], [-1.0, 1.0])
            smoothed_image = gaussian_filter(image, (sigma_x, sigma_y))
            print(np.min(smoothed_image), np.max(smoothed_image))
            smoothed_image = normalize(smoothed_image, [-1.0, 1.0], [0.0, 1.0])
            temp_image = deepcopy(self.image)
            temp_image.Image3D = smoothed_image
            temp_image.sigma = sigma_x

            saving.saveImage(temp_image)
Exemple #18
0
def get_background_markers(image_gray):
    '''
    Finds the pixels that definitely belong in background regions.
    
    Parameters
    -----------
    image_gray : 2-D numpy array
        A grayscale image.
        
    Returns
    -----------
    markers_background : 2-D Boolean numpy array
        An array with the same shape as image_gray, where the seeds of
        the background regions are True. 
    '''
    dark_threshold = threshold_by_blocks(image_gray, 20, background_intensity)
    dark_pixels = image_gray <= dark_threshold
    image_smooth = gaussian_filter(image_gray, 1)
    otsu = image_gray > threshold_otsu(image_gray)
    #minima = local_min(image_smooth) & np.logical_not(otsu)
    #minima = local_min(image_gray) & (~ otsu)
    minima = local_min(image_gray)

    markers_background = dark_pixels | minima
    return markers_background
def applyProgressiveGaussian(im, dof, filterLevel):
  #take the top dof pixels
  top, bottom = np.vsplit(im, [dof])
  #leave top, blur bottom
  newbot = skfilter.gaussian_filter(bottom, filterLevel)
  if (newbot.shape[0] > dof*2):
    newbot = applyProgressiveGaussian(newbot, dof, filterLevel*1.1)
  return np.vstack((top, newbot))
def energyFunctionChannel(channel):
    # The energy function of a single-scaled image (channel)
    # is the absolute and normalized value of the
    # image after an laplacian filter
    # (The energy function will be higher on edges)
    blurred_channel = filter.gaussian_filter(channel, 2)
    high_freq = channel - blurred_channel
    absol = absolutize(high_freq)
    return absol
 def train(self, _dataSet):
     '''
     Trains Model for given dataset (ImageDataSet)
     '''
     sys.stderr.write("Got " + str(len(_dataSet.get_inputs())) +
                      " images\n")
     for im in _dataSet.get_inputs():
         self.filtered.append(
             filter.gaussian_filter(im, self.sigma, multichannel=False))
Exemple #22
0
def create_external_edge_force_gradients_from_img( img, sigma=30. ):
    """
    Given an image, returns 2 functions, fx & fy, that compute
    the gradient of the external edge force in the x and y directions.

    img: ndarray
        The image.
    """
    # Gaussian smoothing.
    smoothed = filt.gaussian_filter( (img-img.min()) / (img.max()-img.min()), sigma )
    # Gradient of the image in x and y directions.
    giy, gix = np.gradient( smoothed )
    # Gradient magnitude of the image.
    gmi = (gix**2 + giy**2)**(0.5)
    # Normalize. This is crucial (empirical observation).
    gmi = (gmi - gmi.min()) / (gmi.max() - gmi.min())

    # Gradient of gradient magnitude of the image in x and y directions.
    ggmiy, ggmix = np.gradient( gmi )

    def fx(x, y):
        """
        Return external edge force in the x direction.

        x: ndarray
            numpy array of floats.
        y: ndarray:
            numpy array of floats.
        """
        # Check bounds.
        x[ x < 0 ] = 0.
        y[ y < 0 ] = 0.

        x[ x > img.shape[1]-1 ] = img.shape[1]-1
        y[ y > img.shape[0]-1 ] = img.shape[0]-1

        return ggmix[ (y.round().astype(int), x.round().astype(int)) ]

    def fy(x, y):
        """
        Return external edge force in the y direction.

        x: ndarray
            numpy array of floats.
        y: ndarray:
            numpy array of floats.
        """
        # Check bounds.
        x[ x < 0 ] = 0.
        y[ y < 0 ] = 0.

        x[ x > img.shape[1]-1 ] = img.shape[1]-1
        y[ y > img.shape[0]-1 ] = img.shape[0]-1

        return ggmiy[ (y.round().astype(int), x.round().astype(int)) ]

    return fx, fy
Exemple #23
0
def CompareExampleToTraining(bwImg, preProcessedModel, getCandidates=False):

    bwImg = filt.gaussian_filter(bwImg, 2.)

    bwImg = bwImg[20:-20, :]
    bwImg = bwImg[:, 20:-20]

    charScores = []
    for ch in preProcessedModel:

        examples = preProcessedModel[ch]
        for example, sourceObjId in examples:
            #Tight crop
            example = filt.gaussian_filter(example, 2.)
            example = example[20:-20, :]
            example = example[:, 20:-20]

            flatExample = example.reshape(example.size)
            flatBwImg = bwImg.reshape(bwImg.size)
            if 0:
                den = np.abs(flatExample - flatBwImg).mean()
                if den > 0.:
                    score = 1. / den
                else:
                    score = 100.
            if 1:
                score = np.corrcoef(flatExample, flatBwImg)[0, 1]

            charScores.append((score, ch, example, sourceObjId))

    charScores.sort(reverse=True)
    #for score, ch, example, sourceObjId in charScores[:5]:
    #	#annot = GetAnnotForObjId(plates, sourceObjId)

    #	print ch, score, sourceObjId#, annot['reg']

    mergeImg = None
    if getCandidates:
        mergeImg = bwImg.copy()
        for score, ch, example, sourceObjId in charScores[:10]:
            mergeImg = np.hstack((mergeImg, example))
        #misc.imshow(mergeImg)

    return charScores, mergeImg
Exemple #24
0
def CompareExampleToTraining(bwImg, preProcessedModel, getCandidates = False):

	bwImg = filt.gaussian_filter(bwImg, 2.)

	bwImg = bwImg[20:-20,:]
	bwImg = bwImg[:,20:-20]

	charScores = []
	for ch in preProcessedModel:
		
		examples = preProcessedModel[ch]
		for example, sourceObjId in examples:
			#Tight crop
			example = filt.gaussian_filter(example, 2.)
			example = example[20:-20,:]
			example = example[:,20:-20]

			flatExample = example.reshape(example.size)
			flatBwImg = bwImg.reshape(bwImg.size)
			if 0:
				den = np.abs(flatExample-flatBwImg).mean()
				if den > 0.:
					score = 1. / den
				else:
					score = 100.
			if 1:
				score = np.corrcoef(flatExample, flatBwImg)[0,1]
			
			charScores.append((score, ch, example, sourceObjId))

	charScores.sort(reverse=True)
	#for score, ch, example, sourceObjId in charScores[:5]:
	#	#annot = GetAnnotForObjId(plates, sourceObjId)

	#	print ch, score, sourceObjId#, annot['reg']

	mergeImg = None
	if getCandidates:
		mergeImg = bwImg.copy()
		for score, ch, example, sourceObjId in charScores[:10]:
			mergeImg = np.hstack((mergeImg, example))
		#misc.imshow(mergeImg)

	return charScores, mergeImg
Exemple #25
0
def highpass(stack, smth_width=100):
    '''
    Simulates a high pass filter in Fourier space by
    substracting a smoothed version of the input image.
    '''
    stack = img_as_float(stack/stack.max())
    lowpass = filter.gaussian_filter(stack, smth_width)
    f_stack = stack - lowpass
    f_stack -= f_stack.min()
    return f_stack
Exemple #26
0
def ssr(img, sig):
	img = img.astype(float)
	limg = gaussian_filter(img, sigma = sig)
	limg = limg + (limg == 0)
	img = img + (img == 0)
	img = (255*(log(img) - log(limg)) + 127)
	tmp = ones((img.shape[0], img.shape[1]), dtype = float)*255
	tmp = (img > 255) * tmp
	img = ((img >= 0)*(img <= 255)*img + tmp).astype(uint8)
	return img
def get_labels(binary):
    '''Return image with labeled cells'''

    distance = distance_transform_edt(binary)
    distance_blured = gaussian_filter(distance, 8)
    local_maxi = peak_local_max(distance_blured, indices=False, labels=binary, min_distance = 10)
    markers = label(local_maxi)
    labels = watershed(-distance, markers, mask=binary)
    labels = remove_small_objects(labels, 4000)
    labels = clear_border(labels)
    return labels
Exemple #28
0
def get_mask(small, thresh=25):
    # add color cut in here?
    from skimage.filter import gaussian_filter
    from scipy import ndimage
    (nx, ny) = small.shape
    sm = gaussian_filter(small, 4.0)
    #sm = gaussian_filter(small, 3.0)
    notdark = sm > thresh
    label_objects, nb_labels = ndimage.label(notdark)
    mask = label_objects == label_objects[np.round(nx / 2.), np.round(ny / 2.)]
    return mask
Exemple #29
0
	def getImage(self,params):
		sigma = float(params['sigma'])
		r = float(params['red'])
		g = float(params['green'])
		b = float(params['blue'])
		image = data.coffee()
		new_image = filter.gaussian_filter(image, sigma=sigma, multichannel=True)
		new_image[:,:,0] = r*new_image[:,:,0]
		new_image[:,:,1] = g*new_image[:,:,1]
		new_image[:,:,2] = b*new_image[:,:,2]
		return new_image
Exemple #30
0
def sim_wire(angle, gaussian_sigma=1, noise_level=0, L=100):
    "Draw a wire with blur and optional noise."
    # Noise level should be from 0 to 1. 0.02 is reasonable.
    shape = (L, L)

    a = np.zeros(shape, dtype=np.uint8)
    a[draw.ellipse(L//2, L//2, L//24, L//4)] = 100  # horizontal ellipse
    a = filter.gaussian_filter(a, gaussian_sigma)
    b = transform.rotate(a, angle)
    b += noise_level*np.random.randn(*shape)
    return b
def apply_gaussian_filter(sigma, prob_map, relative_location_matrix_shape):
    cprime_labels = prob_map.keys()
    c_labels = next(prob_map.itervalues()).keys()
    norm_prob_map = init_prob_map(cprime_labels, c_labels, relative_location_matrix_shape)

    filtered_prob_map = init_prob_map(cprime_labels, c_labels, relative_location_matrix_shape)
    for cprime, prob_map_c_given_cprime in prob_map.iteritems():
        for c,relative_location_mat in prob_map_c_given_cprime.iteritems():
            filtered_relative_location_mat = gaussian_filter(relative_location_mat, sigma=sigma, multichannel=True)
            filtered_prob_map[cprime][c] = filtered_relative_location_mat
    return filtered_prob_map
Exemple #32
0
def generateGaussianPyramids(image, levels):
    color_channels = [image[:, :, 0], image[:, :, 1], image[:, :, 2]]

    gaussian_pyramids = []
    for level in range(levels):
        level_image_channels = []
        for channel in color_channels:
            blurred_channel = filter.gaussian_filter(channel, 2**level)
            level_image_channels.append(blurred_channel)
        gaussian_pyramids.append(level_image_channels)
    return gaussian_pyramids
def apply_gaussian_filter(sigma, prob_map, relative_location_matrix_shape):
    cprime_labels = prob_map.keys()
    c_labels = next(prob_map.itervalues()).keys()
    norm_prob_map = init_prob_map(cprime_labels, c_labels, relative_location_matrix_shape)

    filtered_prob_map = init_prob_map(cprime_labels, c_labels, relative_location_matrix_shape)
    for cprime, prob_map_c_given_cprime in prob_map.iteritems():
        for c,relative_location_mat in prob_map_c_given_cprime.iteritems():
            filtered_relative_location_mat = gaussian_filter(relative_location_mat, sigma=sigma, multichannel=True)
            filtered_prob_map[cprime][c] = filtered_relative_location_mat
    return filtered_prob_map
Exemple #34
0
def structure_reliability(img, gamma=1):
    """ Calculates the flow structure reliability
    Parameters
    ----------
    img: numpy array
    Image to compute the structure

    gamma: float, optional
    Soft threshold

    Return
    ------
    reliability map (0 less reliable, 1 reliable)

    """

    #compute gradient of the image in the three channels

    #kernel for blurring

    st = np.zeros((img.shape[0], img.shape[1]))

    eps = 1e-6

    for k in np.arange(img.shape[-1]):
        grad = np.gradient(img[:, :, k])
        #compute components of the structure tensor
        wxx = filter.gaussian_filter(grad[0] ** 2, 1)
        wxy = filter.gaussian_filter(grad[0] * grad[1], 1)
        wyy = filter.gaussian_filter(grad[1] ** 2, 1)

        #determinant and trace
        wdet = wxx * wyy - wxy ** 2
        wtr = wxx + wyy

        st += wdet / (wtr + eps)

    avg = st.mean()

    return 1 - np.exp(-st / (0.7 * avg * gamma))
Exemple #35
0
def get_markers(foci_pic, nucleus, peak_min_val_perc = 60):
    '''Return foci markers'''

#    foci_pic_blured = img_as_ubyte(gaussian_filter(foci_pic, 1))
    foci_pic_blured = np.floor(gaussian_filter(foci_pic, 1)*255).astype(np.uint8)

    foci_values = np.extract(nucleus, foci_pic)

    min_peak_val = np.percentile(foci_values, (peak_min_val_perc))

    local_maxi = peak_local_max(foci_pic_blured, min_distance=5, threshold_abs=min_peak_val, indices=False, labels=nucleus)

    return measure_label(local_maxi)
    def smooth_data(self, data):
        if data is not None:
            # smoothing data
            print 'smoothing data...'
            if self.params['smoothing'] == 1:
                data = skifil.gaussian_filter(self.data, sigma=self.params['sigma'])
            elif self.params['smoothing'] == 2:
                data = tools.smoothing_bilateral(data, sigma_space=self.params['sigma_spatial'], sigma_color=self.params['sigma_range'], sliceId=0)
            elif self.params['smoothing'] == 3:
                data = tools.smoothing_tv(data, weight=self.params['weight'], sliceId=0)
            else:
                print '\tcurrently switched off'

        return data
Exemple #37
0
    def fit(self, image):
        if image.ndim > 2:
            raise TypeError('only single channel images allowed')

        # smooth image
        im = gaussian_filter(image, self.sigma)

        # gradients and grad. magnitude
        im_x, im_y = self.__gradient(im)
        im_r = np.sqrt(im_x * im_x + im_y * im_y)

        # log gradients
        log_im = np.log(im + self.__eps)
        log_im_x, log_im_y = self.__gradient(log_im)
        log_im_x = log_im_x.ravel()
        log_im_y = log_im_y.ravel()

        # compute weights
        weights = np.exp(-im_r / (self.mu ** 2))
        weights = weights.ravel()

        # (x,y) coordinates
        ny, nx = im.shape
        x, y = np.meshgrid(range(nx), range(ny), indexing='xy')
        x = x.ravel() - 0.5 * nx
        y = y.ravel() - 0.5 * ny

        # model (gradient) matrix
        M = self.__M(x, y)

        # observed (smoothed) gradient
        g = np.row_stack((log_im_x, log_im_y))
        g.shape = (g.size, 1)

        # diag(weights) * M
        weights.shape = (weights.size, 1)
        WM = M * np.vstack((weights, weights))

        # solve for gamma
        _g = np.asmatrix(g)
        _M = np.asmatrix(M)
        _WM = np.asmatrix(WM)
        gamma = np.linalg.inv(_WM.T * _M) * _WM.T * _g

        # compute illumination profile
        S = self.__S(x, y)
        I = np.asarray(np.asmatrix(S) * gamma)

        self.profile = np.exp(I - I.max())
        self.profile = self.profile.reshape(im.shape)
def createHSVColourValues(imageRGB):
    totalPixels = np.shape(imageRGB)[0] * np.shape(imageRGB)[1]
    
    hsvSourceImage = color.rgb2hsv(imageRGB)
    # Rather than just taking the pixel value, which might be noisy, average locally.
    hsvSourceImage = filter.gaussian_filter( hsvSourceImage, sigma=1.0, multichannel=True )

    allHuePixels = np.reshape(hsvSourceImage[:,:,0] , (totalPixels, 1) )
    allSaturationPixels = np.reshape(hsvSourceImage[:,:,1] , (totalPixels, 1) )
    allValueBrightPixels = np.reshape(hsvSourceImage[:,:,2] , (totalPixels, 1) ) 
    
    hsvColourValueFeature = np.hstack( ( allHuePixels, allSaturationPixels, allValueBrightPixels ) )
    
    return hsvColourValueFeature
Exemple #39
0
def filter(data, filtType, par):

    if filtType == "sobel":
        filt_data = sobel(data)
    elif filtType == "roberts":
        filt_data = roberts(data)
    elif filtType == "canny":
        filt_data = canny(data)
    elif filtType == "lowpass_avg":
        from scipy import ndimage

        p = int(par)
        kernel = np.ones((p, p), np.float32) / (p * p)
        filt_data = ndimage.convolve(data, kernel)
    elif filtType == "lowpass_gaussian":

        s = float(par)
        filt_data = gaussian_filter(data, sigma=s)

    elif filtType == "highpass_gaussian":

        s = float(par)
        lp_data = gaussian_filter(data, sigma=s)
        filt_data = data - lp_data

    elif filtType == "highpass_avg":
        from scipy import ndimage

        p = int(par)
        kernel = np.ones((p, p), np.float32) / (p * p)
        lp_data = ndimage.convolve(data, kernel)
        filt_data = data - lp_data

    # elif filtType ==  "gradient":

    return filt_data
Exemple #40
0
def impyramid_next_level_rgb(_img):
    """
    IMPYRAMID_NEXT_LEVEL_RGB: computes the next level in a Gaussian
    pyramidal decomposition, for color images (RGB, or any 3-channel
    image).

    :param _img: numpy.ndarray
    A grey-level image (_img.ndim == 2)

    :return: numpy.ndarray
    The new level in the pyramid, an image half the size of the original.
    """

    res = gaussian_filter(_img, sigma=0.866, multichannel=True)

    return res[::2, ::2, :]
Exemple #41
0
def impyramid_next_level_rgb(_img):
    """
    IMPYRAMID_NEXT_LEVEL_RGB: computes the next level in a Gaussian
    pyramidal decomposition, for color images (RGB, or any 3-channel
    image).

    :param _img: numpy.ndarray
    A grey-level image (_img.ndim == 2)

    :return: numpy.ndarray
    The new level in the pyramid, an image half the size of the original.
    """

    res = gaussian_filter(_img, sigma=0.866, multichannel=True)

    return res[::2, ::2, :]
Exemple #42
0
def main():
    plt.figure(figsize=(15, 14))
    planes = ['samolot01.jpg', 'samolot09.jpg', 'samolot05.jpg', 'samolot00.jpg', 'samolot07.jpg', 'samolot13.jpg']
    i = 0
    for file in planes:
        img = data.imread(file, as_grey=True)
        ax = plt.subplot(3, 2, i)
        ax.axis('off')
        #img = filter.sobel(img)
        img **= 0.4
        img = filter.canny(img, sigma=3.0)
        img = morphology.dilation(img, morphology.disk(2))
        img = filter.gaussian_filter(img, sigma=1.0)
        ax.imshow(img, cmap=plt.cm.gray, aspect='auto')
        i += 1

    plt.savefig('zad1.pdf')
Exemple #43
0
def get_markers(foci_pic, nucleus, peak_min_val_perc=60):
    '''Return foci markers'''

    #    foci_pic_blured = img_as_ubyte(gaussian_filter(foci_pic, 1))
    foci_pic_blured = np.floor(gaussian_filter(foci_pic, 1) * 255).astype(
        np.uint8)

    foci_values = np.extract(nucleus, foci_pic)

    min_peak_val = np.percentile(foci_values, (peak_min_val_perc))

    local_maxi = peak_local_max(foci_pic_blured,
                                min_distance=5,
                                threshold_abs=min_peak_val,
                                indices=False,
                                labels=nucleus)

    return measure_label(local_maxi)
def createHSVColourValues(imageRGB):
    totalPixels = np.shape(imageRGB)[0] * np.shape(imageRGB)[1]

    hsvSourceImage = color.rgb2hsv(imageRGB)
    # Rather than just taking the pixel value, which might be noisy, average locally.
    hsvSourceImage = filter.gaussian_filter(hsvSourceImage,
                                            sigma=1.0,
                                            multichannel=True)

    allHuePixels = np.reshape(hsvSourceImage[:, :, 0], (totalPixels, 1))
    allSaturationPixels = np.reshape(hsvSourceImage[:, :, 1], (totalPixels, 1))
    allValueBrightPixels = np.reshape(hsvSourceImage[:, :, 2],
                                      (totalPixels, 1))

    hsvColourValueFeature = np.hstack(
        (allHuePixels, allSaturationPixels, allValueBrightPixels))

    return hsvColourValueFeature
def showAttMap(
    img,
    attMaps,
    tagName,
    overlap=True,
    cmap='autumn',
    blur=False,
    save=False,
):
    pylab.rcParams['figure.figsize'] = (12.0, 12.0)
    f, ax = plt.subplots(int(len(tagName) / 2 + 1), 2)
    ax[0, 0].imshow(img)
    if len(img.shape) == 2 or img.shape[2] == 1:
        img = color.gray2rgb(img)

    for i in range(len(tagName)):
        attMap = attMaps[i].copy()
        attMap -= attMap.min()
        if attMap.max() > 0:
            attMap /= attMap.max()
        attMap = transform.resize(attMap, (img.shape[:2]),
                                  order=3,
                                  mode='nearest')
        if blur:
            attMap = filter.gaussian_filter(attMap, 0.02 * max(img.shape[:2]))
            attMap -= attMap.min()
            attMap /= attMap.max()

        cmap = plt.get_cmap(cmap)
        attMapV = cmap(attMap)
        attMapV = np.delete(attMapV, 3, 2)
        if overlap:
            attMap = 1 * (1 - attMap**0.8).reshape(attMap.shape + (
                1, )) * img + (attMap**0.8).reshape(attMap.shape +
                                                    (1, )) * attMapV

        current_subplot_axes = ax[int((i + 1) / 2), int((i + 1) % 2)]
        attention_map_subplot = current_subplot_axes.imshow(
            attMap, interpolation='bicubic', cmap=cmap)
        plt.colorbar(attention_map_subplot, ax=current_subplot_axes)
        current_subplot_axes.set_title(tagName[i])

    if save:
        f.savefig("attentionmaps.jpg")
def get_binary(cells):
    '''Returns binary image with cells'''

    if (len(cells.shape) == 3):
        cells = np.max(cells, 2)

    blured = gaussian_filter(cells,8)
    highpass = cells - 0.8*blured
    sharp = highpass + cells
    sharp = np.floor(sharp).astype(np.uint8)

    diamond = np.array([0,1,0,1,1,1,0,1,0], dtype=bool).reshape((3,3))

    edges = canny(sharp, sigma = 1, high_threshold = 35., low_threshold = 14.)
    edges = double_dilation(edges, diamond)
    binary = fill_holes(edges)
    binary = double_erosion(binary, diamond)

    return binary
Exemple #47
0
def compute_features(filtered, frequencies,
                     proportion=0.5,
                     alpha=0.25):
    """Compute features for each filtered image.

    ``frequencies[i]`` is the center frequency of the Gabor filter
    that generated ``filtered[i]``.

    """
    # TODO: is this really what the paper means in formula 6?
    nonlinear = np.tanh(alpha * filtered)
    ncols = filtered.shape[1]

    # paper says proportion * n_cols / frequency, but remember that
    # their frequency is in cycles per image width. our frequency is
    # in cycles per pixel, so we just need to take the inverse.
    sigmas = proportion * (1.0 / np.array(frequencies))
    features = np.dstack(gaussian_filter(nonlinear[:, :, i], sigmas[i])
                         for i in range(len(sigmas)))
    return features
def record_mouse(event):
    """
    Save a mouse action
    """
    global counter
    global session

    if event.buttons != 1:
        return

    h, w, _, _, _ = session.console.display.get_screen_resolution(0)
    png = session.console.display.take_screen_shot_png_to_array(0, h, w)

    with open('screenshot.png', 'wb') as f:
        f.write(png)

    IMAGE_FILE_PATH = "screenshot.png"
    FILE_TO_SAVE = "%s%s.png" % (SAVE_FOLDER, counter)

    # load image
    image = data.imread(IMAGE_FILE_PATH)
    image = rgb2gray(image)

    # edges
    image = sobel(image)

    # blur
    image = gaussian_filter(image, sigma=10)

    mpimg.imsave("output.png", image)

    img = Image("output.png")
    img_original = Image(IMAGE_FILE_PATH)
    image = Image(IMAGE_FILE_PATH)
    blobs = img.findBlobs(threshval = -1, minsize=10, maxsize=0, threshblocksize=0, threshconstant=5, appx_level=3)
    if blobs:
        blobs.draw(width=10)
    img.save(FILE_TO_SAVE)
    img_original.save(FILE_TO_SAVE+"_original.png")

    counter += 1
def test():
    '''
    test function classifyIm with given tree and parameter vector A and B
    '''    
    import sys
    from skimage import io, color, filter
    sys.path.append('/home/jo/Dropbox/FaceRegion') # navigate to the folder that contains 
                                                       # A, B and tree
    A = np.genfromtxt('A.csv', dtype = float, delimiter = ',')
    B = np.genfromtxt('B.csv', dtype = float, delimiter = ',')
    A = np.array(A, dtype = int8)
    B = np.array(B, dtype = int8)
    
    m = 9
    pathData = '/host/Research Project/Data/Rdata' + str(m) + '.jpg';
    tree = grabTree('myTree1.txt')
    image = io.imread(pathData)
    image = color.rgb2gray(image)
    image = filter.gaussian_filter(image, sigma = 0.8)
    
    classifyIm(tree, image)
def segment_texture(image, n_clusters=15, init=None):
    # blur and take local maxima
    blur_image = gaussian_filter(image, sigma=8)
    blur_image = ndi.maximum_filter(blur_image, size=3)

    # get texture features
    feats = lbp(blur_image, n=5, method="uniform")
    feats_r = feats.reshape(-1, 1)

    # cluster the texture features, reusing initialised centres if already calculated
    params = {"n_clusters": n_clusters, "batch_size": 500}
    if init is not None:
        params.update({"init": init})
    km = k_means(**params)
    clus = km.fit(feats_r)

    # copy relevant attributes
    labels = clus.labels_
    clusters = clus.cluster_centers_

    # reshape label arrays
    labels = labels.reshape(blur_image.shape[0], blur_image.shape[1])

    return (image, blur_image, labels, clusters)
Exemple #51
0
    ext_s_min[out_min_min] = 0
    ext_s_max[out_max_min] = 0
    # clamp the max to image bounds across each dimension
    for i in xrange(image.n_dims):
        ext_s_max[out_max_max[:, i], i] = image_size[i] - 1
        ext_s_min[out_min_max[:, i], i] = image_size[i] - 1

    # 3. Build the insertion slices
    ins_s_min = ext_s_min - c_min
    ins_s_max = np.maximum(ext_s_max - c_max + parts_shape, (0, 0))

    for i, (e_a, e_b, i_a, i_b) in enumerate(zip(ext_s_min, ext_s_max,
                                                 ins_s_min, ins_s_max)):
        # build a list of insertion slices and extraction slices
        i_slices = [slice(a, b) for a, b in zip(i_a, i_b)]
        e_slices = [slice(a, b) for a, b in zip(e_a, e_b)]
        # get a view onto the parts we are on
        part = parts[..., i, :]
        # apply the slices to map
        part[i_slices] = image.pixels[e_slices]

    # build and return parts image
    return Image(parts)


def flatten_out(list_of_lists):
    return [i for l in list_of_lists for i in l]


fsmooth = lambda x, sigma: gaussian_filter(x, sigma, mode='constant')
################################################################################
from skimage.exposure import rescale_intensity
rescaled_nuclei = rescale_intensity(nuclei, in_range=(np.min(nuclei),np.max(nuclei)))
plt.imshow(rescaled_nuclei)

new_range = tuple(np.percentile(nuclei,(2,98)))
rescaled_nuclei = rescale_intensity(nuclei, in_range=new_range)
plt.imshow(rescaled_nuclei)
################################################################################


################################################################################
#### Применение фильтров, создание рисунка с повышенной чёткостью границ    ####
################################################################################
from skimage.filter import gaussian_filter
blured = gaussian_filter(nuclei,8)
plt.imshow(blured)

highpass = nuclei - 0.8*blured
sharp = highpass + nuclei
sharp = np.floor(sharp).astype(np.uint8)

fig, ax = plt.subplots(1,2)
plt.gray()
ax[0].imshow(nuclei)
ax[1].imshow(sharp)
################################################################################


################################################################################
#### Бинаризация изображений (белые клетки, чёрный фон)                     ####
import skimage.io as io
from skimage.filter import gaussian_filter
import matplotlib.pyplot as plt
import numpy as np
img = io.imread('sobel.png')


def show_images(images, titles=None):
    """Display a list of images"""
    n_ims = len(images)
    if titles is None: titles = ['(%d)' % i for i in range(1, n_ims + 1)]
    fig = plt.figure()
    n = 1
    for image, title in zip(images, titles):
        a = fig.add_subplot(1, n_ims, n)  # Make subplot
        if image.ndim == 2:  # Is image grayscale?
            plt.gray(
            )  # Only place in this blog you can't replace 'gray' with 'grey'
        plt.imshow(image)
        a.set_title(title)
        n += 1
    fig.set_size_inches(np.array(fig.get_size_inches()) * n_ims)
    plt.show()


blurred_image = gaussian_filter(img, sigma=3)
really_blurred_image = gaussian_filter(img, sigma=6)

show_images(images=[img, blurred_image, really_blurred_image],
            titles=["Equalized", "3 Sigma Blur", "6 Sigma Blur"])
from skimage import measure, filter
from scipy import ndimage
from matplotlib import animation
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from glob import glob

reload(trackblobs)

files = glob('/Users/ethan/insight/nexrad/data/kmlb_grid/firstn/*.png')
frames = []
storm_list = []
for f in files:
    im = Image.open(f)
    z = np.flipud(np.array(im)) * 75.0 / 255.0
    z1 = filter.gaussian_filter(1 * z, sigma=1.1)
    im.close()
    frames.append(z1)
    storms = trackblobs.find_storms(z1)
    storm_list.append(storms)

fig = plt.figure(figsize=(5, 5))
ax = fig.add_axes([0, 0, 1, 1])
axim = ax.imshow(z1, origin='lower')


def init():
    pass


def animate(i):
Exemple #55
0
def segment_image(prefix, filename, min_area, blur):
    #import resource ; r = resource.getrusage(resource.RUSAGE_SELF)
    #print 'maxrss start', r.ru_maxrss

    image = images.load(filename)
    height = image.shape[0]
    width = image.shape[1]

    print prefix, 'FG/BG'

    blurred = filter.gaussian_filter(image, blur, multichannel=True)
    image_raveled = numpy.reshape(blurred, (height * width, 3))
    del blurred

    # Allow for non-uniform lighting over image using a linear model

    #pred = [ ]
    #order = 2
    #for i in xrange(order):
    #    for j in xrange(order):
    #        pred.append((
    #            numpy.cos(numpy.linspace(0,numpy.pi*i, width)).astype('float32')[None,:] *
    #            numpy.cos(numpy.linspace(0,numpy.pi*j, height)).astype('float32')[:,None]  ).ravel())
    #pred = numpy.transpose(pred)

    #one = numpy.ones((height,width), dtype='float32').ravel()
    #x = numpy.empty((height,width), dtype='float32')
    #x[:,:] = numpy.linspace(0.0, 1.0, width)[None,:]
    #x = x.ravel()
    #y = numpy.empty((height,width), dtype='float32')
    #y[:,:] = numpy.linspace(0.0, 1.0, height)[:,None]
    #y = y.ravel()
    #pred = numpy.array((
    #    one,
    #    #x,
    #    #y,
    #    #x*x,
    #    #y*y,
    #    #x*y,
    #    #x*x*x,
    #    #y*y*y,
    #    #x*x*y,
    #    #y*y*x,
    #    )).transpose()
    #del one,x,y
    #
    #def fit(mask):
    #    result = numpy.zeros((height*width,3), dtype='float32')
    #    for i in xrange(3):
    #        model = linalg.lstsq(pred[mask],image_raveled[mask,i])[0]
    #        for j in xrange(pred.shape[1]):
    #            result[:,i] += pred[:,j] * model[j]
    #    return result

    average = numpy.mean(image_raveled, axis=0)
    # Initial guess
    color_bg = (average * 1.5)  #[None,:]
    color_fg = (average * 0.5)  #[None,:]

    #offsets = image_raveled - average
    #icovar_fg = icovar_bg = stats.inverse_covariance(offsets)
    #mv_fg = mv_bg = stats.estimate_multivar(offsets)
    #mv = stats.estimate_indivar(offsets)
    #del offsets
    #p_fg = 0.5

    i = 0
    while True:
        #d_bg = a_raveled-color_bg[None,:]
        #d_bg *= d_bg
        #d_bg = numpy.sum(d_bg,1)
        #d_fg = a_raveled-color_fg[None,:]
        #d_fg *= d_fg
        #d_fg = numpy.sum(d_fg,1)
        #fg = d_fg*Background_weight < d_bg
        #color_fg = numpy.median(a_raveled[fg,:],axis=0)
        #color_bg = numpy.median(a_raveled[~fg,:],axis=0)

        #d_bg = stats.length2s(icovar_bg, image_raveled - color_bg[None,:])
        #d_fg = stats.length2s(icovar_fg, image_raveled - color_fg[None,:])
        #fg = d_fg < d_bg

        #logp_bg = mv.logps(image_raveled - color_bg) #+ numpy.log(1.0-p_fg)
        #logp_fg = mv.logps(image_raveled - color_fg) #+ numpy.log(p_fg)
        #fg = logp_fg > logp_bg
        #del logp_bg, logp_fg

        mid = (color_bg + color_fg) * 0.5
        proj = (color_fg - color_bg)
        fg = numpy.sum(image_raveled * proj[None, :], axis=1) > numpy.sum(
            mid * proj)

        #p_fg = numpy.mean(fg)
        #p_fg = max(0.05,min(0.95,p_fg))

        #print logp_bg[:10]
        #print logp_fg[:10]
        #print p_fg

        if i >= 5: break

        color_fg = numpy.mean(image_raveled[fg, :], axis=0)
        color_bg = numpy.mean(image_raveled[~fg, :], axis=0)

        #color_fg = fit(fg)
        #color_bg = fit(~fg)

        #offsets = image_raveled.copy()
        #offsets[fg,:] -= color_fg #[fg,:]
        #offsets[~fg,:] -= color_bg #[~fg,:]
        #mv = stats.estimate_indivar(offsets)
        #del offsets

        #mv_fg = mv_bg = stats.estimate_multivar(offsets)
        #icovar = stats.inverse_covariance(offsets)
        #icovar_fg = stats.inverse_covariance(image_raveled[fg,:] - color_fg[None,:])
        #icovar_bg = stats.inverse_covariance(image_raveled[~fg,:] - color_bg[None,:])
        # mv_fg = stats.estimate_multivar(image_raveled[fg,:] - color_fg[fg,:])
        # mv_bg = stats.estimate_multivar(image_raveled[~fg,:] - color_bg[~fg,:])

        i += 1

    fg = numpy.reshape(fg, (height, width))

    pred = None
    del color_fg, color_bg

    print prefix, 'Detect size'

    sizer = 1.0
    n1 = numpy.sum(fg)
    while True:
        n2 = numpy.sum(images.erode(fg, sizer))
        if n2 < n1 * 0.3: break
        sizer += 0.1
    print prefix, 'Size', sizer

    print prefix, 'Cleave'

    cores = images.cleave(fg, sizer)

    print prefix, 'Segment'

    core_labels, num_features = ndimage.label(cores)

    #dist = ndimage.distance_transform_edt(~cores)
    #dist = -ndimage.distance_transform_edt(fg)
    dist = images.hessian(ndimage.gaussian_filter(fg.astype('float64'),
                                                  sizer)).i1

    labels = morphology.watershed(dist, core_labels, mask=fg)

    #===
    #Remap labels to eliminate border cells and small cells

    bad_labels = set()
    for x in xrange(width):
        bad_labels.add(labels[0, x])
        bad_labels.add(labels[height - 1, x])
    for y in xrange(height):
        bad_labels.add(labels[y, 0])
        bad_labels.add(labels[y, width - 1])

    threshold = sizer * sizer * min_area
    print prefix, 'Min cell area', threshold
    areas = numpy.zeros(num_features + 1, 'int32')
    for i in numpy.ravel(labels):
        areas[i] += 1
    for i in xrange(1, num_features + 1):
        if areas[i] < threshold:
            bad_labels.add(i)

    mapping = numpy.zeros(num_features + 1, 'int32')
    j = 1
    for i in xrange(1, num_features + 1):
        if i not in bad_labels:
            mapping[i] = j
            j += 1
    labels = mapping[labels]

    bounds = [
        images.Rect(item[1].start, item[0].start, item[1].stop - item[1].start,
                    item[0].stop - item[0].start)
        for item in ndimage.find_objects(labels)
    ]
    labels -= 1  #Labels start from zero, index into bounds

    print prefix, 'Saving'

    #test = color.label2rgb(labels-1, image)

    border = ndimage.maximum_filter(
        labels, size=(3, 3)) != ndimage.minimum_filter(labels, size=(3, 3))

    test = image.copy()
    test[border, :] = 0.0
    test[cores, :] *= 0.5
    test[cores, :] += 0.5
    #test[~fg,1] = 1.0
    #test[cores,2] = 1.0
    #test[:,:,1] = hatmax * 10.0
    #test[good,1] = hatmax

    #test[bounds[0]][:,:,1] = 1.0
    #test[labels == 0,2] = 1.0

    images.save(prefix + '-debug.png', test)

    #test2 = image.copy()
    #test2 /= numpy.reshape(color_fg, (height,width,3))
    #images.save(prefix+'-corrected.png', test2)

    images.save(prefix + '.png', image)

    result = Segmentation()
    result.n_cells = len(bounds)
    result.sizer = sizer
    result.labels = labels
    result.bounds = bounds
    util.save(prefix + '-segmentation.pgz', result)
    util.clear(prefix + '-measure.pgz')
    util.clear(prefix + '-classification.pgz')
    util.save(prefix + '-labels.pgz', [None] * result.n_cells)

    print prefix, 'Done'
def gradient_field(im):
    im = skimage_filter.gaussian_filter(im, 1.0)
    gradx = np.hstack([im[:, 1:], im[:, -2:-1]]) - np.hstack([im[:, 0:1], im[:, :-1]]) 
    grady = np.vstack([im[1:, :], im[-2:-1, :]]) - np.vstack([im[0:1, :], im[:-1, :]]) 
    return gradx, grady