Ejemplo n.º 1
0
def test_fullhistogram_random():
    np.random.seed(122)
    A = np.random.rand(12,3,44,33)*1000
    A = A.astype(np.uint16)
    hist = fullhistogram(A)
    for i in range(len(hist)):
        assert hist[i] == (A == i).sum()
    assert len(hist.shape) == 1

    A = A[::2,:,2::3,1:-2:2]
    hist = fullhistogram(A)
    for i in range(len(hist)):
        assert hist[i] == (A == i).sum()
    assert hist.sum() == A.size
    assert len(hist.shape) == 1
Ejemplo n.º 2
0
def test_fullhistogram_random():
    np.random.seed(122)
    A = np.random.rand(12, 3, 44, 33) * 1000
    A = A.astype(np.uint16)
    hist = fullhistogram(A)
    for i in xrange(len(hist)):
        assert hist[i] == (A == i).sum()
    assert len(hist.shape) == 1

    A = A[::2, :, 2::3, 1:-2:2]
    hist = fullhistogram(A)
    for i in xrange(len(hist)):
        assert hist[i] == (A == i).sum()
    assert hist.sum() == A.size
    assert len(hist.shape) == 1
Ejemplo n.º 3
0
def bgsub(img,options = {}):
    '''
    bgsub(img,options = None)

    Background subtract img (which must be a numpy-type array).

    Changes are done inplace and the img is returned. Use the following idiom for operating on a copy:

    B = bgsub(A.copy(),options)
    '''
    type = options.get('bgsub.type','lowcommon')
    if type == 'nobgsub':
        return img
    elif type == 'lowcommon':
        M = np.round(img.mean())-1
        if M <= 0:
            T = 0
        else:
            hist = fullhistogram(img)
            T = np.argmax(hist[:M])
        if T > 0:
            img -= np.minimum(img,T)
        return img
    else:
        raise KeyError('Background subtraction option not recognised (%s).' % type)
Ejemplo n.º 4
0
def slow_otsu(img, ignore_zeros=False):
    hist = fullhistogram(img)
    hist = hist.astype(np.double)
    Hsum = img.size - hist[0]
    if ignore_zeros:
        hist[0] = 0
    if Hsum == 0:
        return 0
    Ng = len(hist)

    nB = np.cumsum(hist)
    nO = nB[-1]-nB
    mu_B = 0
    mu_O = np.dot(np.arange(Ng), hist)/ Hsum
    best = nB[0]*nO[0]*(mu_B-mu_O)*(mu_B-mu_O)
    bestT = 0

    for T in range(1, Ng):
        if nB[T] == 0: continue
        if nO[T] == 0: break
        mu_B = (mu_B*nB[T-1] + T*hist[T]) / nB[T]
        mu_O = (mu_O*nO[T-1] - T*hist[T]) / nO[T]
        sigma_between = nB[T]*nO[T]*(mu_B-mu_O)*(mu_B-mu_O)
        if sigma_between > best:
            best = sigma_between
            bestT = T
    return bestT
Ejemplo n.º 5
0
def slow_otsu(img, ignore_zeros=False):
    hist = fullhistogram(img)
    hist = hist.astype(np.double)
    Hsum = img.size - hist[0]
    if ignore_zeros:
        hist[0] = 0
    if Hsum == 0:
        return 0
    Ng = len(hist)

    nB = np.cumsum(hist)
    nO = nB[-1] - nB
    mu_B = 0
    mu_O = np.dot(np.arange(Ng), hist) / Hsum
    best = nB[0] * nO[0] * (mu_B - mu_O) * (mu_B - mu_O)
    bestT = 0

    for T in range(1, Ng):
        if nB[T] == 0: continue
        if nO[T] == 0: break
        mu_B = (mu_B * nB[T - 1] + T * hist[T]) / nB[T]
        mu_O = (mu_O * nO[T - 1] - T * hist[T]) / nO[T]
        sigma_between = nB[T] * nO[T] * (mu_B - mu_O) * (mu_B - mu_O)
        if sigma_between > best:
            best = sigma_between
            bestT = T
    return bestT
Ejemplo n.º 6
0
def test_fullhistogram():
    A100 = np.arange(100).reshape((10,10)).astype(np.uint32)
    assert fullhistogram(A100).shape == (100,)
    assert np.all(fullhistogram(A100) == np.ones(100))

    A1s = np.ones((12,12), np.uint8)
    assert fullhistogram(A1s).shape == (2,)
    assert np.all(fullhistogram(A1s) == np.array([0,144]))

    A1s[0] = 0
    A1s[1] = 2
    assert fullhistogram(A1s).shape == (3,)
    assert np.all(fullhistogram(A1s) == np.array([12,120,12]))
Ejemplo n.º 7
0
def test_fullhistogram():
    A100 = np.arange(100).reshape((10, 10)).astype(np.uint32)
    assert fullhistogram(A100).shape == (100, )
    assert np.all(fullhistogram(A100) == np.ones(100))

    A1s = np.ones((12, 12), np.uint8)
    assert fullhistogram(A1s).shape == (2, )
    assert np.all(fullhistogram(A1s) == np.array([0, 144]))

    A1s[0] = 0
    A1s[1] = 2
    assert fullhistogram(A1s).shape == (3, )
    assert np.all(fullhistogram(A1s) == np.array([12, 120, 12]))
Ejemplo n.º 8
0
def test_float():
    fullhistogram(np.arange(16.*4., dtype=float).reshape((16,4)))
Ejemplo n.º 9
0
def test_types():
    A100 = np.arange(100).reshape((10,10)).astype(np.uint32)
    assert np.all(fullhistogram(A100.astype(np.uint8)) == fullhistogram(A100))
    assert np.all(fullhistogram(A100.astype(np.uint16)) == fullhistogram(A100))
    assert np.all(fullhistogram(A100.astype(np.uint32)) == fullhistogram(A100))
    assert np.all(fullhistogram(A100.astype(np.uint64)) == fullhistogram(A100))
Ejemplo n.º 10
0
def test_fullhistogram_boolean():
    np.random.seed(123)
    A = (np.random.rand(128,128) > .5)
    H = fullhistogram(A)
    assert H[0] == (~A).sum()
    assert H[1] == A.sum()
Ejemplo n.º 11
0
def test_float():
    fullhistogram(np.arange(16. * 4., dtype=float).reshape((16, 4)))
Ejemplo n.º 12
0
def test_types():
    A100 = np.arange(100).reshape((10, 10)).astype(np.uint32)
    assert np.all(fullhistogram(A100.astype(np.uint8)) == fullhistogram(A100))
    assert np.all(fullhistogram(A100.astype(np.uint16)) == fullhistogram(A100))
    assert np.all(fullhistogram(A100.astype(np.uint32)) == fullhistogram(A100))
    assert np.all(fullhistogram(A100.astype(np.uint64)) == fullhistogram(A100))
Ejemplo n.º 13
0
def test_fullhistogram_boolean():
    np.random.seed(123)
    A = (np.random.rand(128, 128) > .5)
    H = fullhistogram(A)
    assert H[0] == (~A).sum()
    assert H[1] == A.sum()
def test_float():
    with pytest.raises(TypeError):
        fullhistogram(np.arange(16.*4., dtype=float).reshape((16,4)))
Ejemplo n.º 15
0
def imgfeaturesdna(imageproc, dnaproc, isfield=False):
    """
    values = imgfeaturesdna(imageproc, dnaproc, isfield=False)

    calculates object features for imageproc
    where imageproc contains the pre-processed fluorescence image,
    and dnaproc the pre-processed dna fluorescence image.
    Pre-processed means that the image has been cropped and had
    pixels of interest selected (via a threshold, for instance).
    use dnaproc=None to exclude features based on the dna image.

    Parameters
    ----------
        * imageproc: pre-processed image
        * dnaproc: pre-processed DNA image
        * isfield: whether to calculate only field level features
                (default: False)

    Features calculated include:
      - Number of objects
      - Euler number of the image (# of objects - # of holes)
      - Average of the object sizes
      - Variance of the object sizes
      - Ratio of the largest object to the smallest
      - Average of the object distances from the COF [unless isfield]
      - Variance of the object distances from the COF [unless isfield]
      - Ratio of the largest object distance to the smallest
      - DNA: average of the object distances to the DNA COF [unless isfield]
      - DNA: variance of the object distances to the DNA COF [unless isfield]
      - DNA: ratio of the largest object distance to the smallest
      - DNA/Image: distance of the DNA COF to the image COF [unless isfield]
      - DNA/Image: ratio of the DNA image area to the image area
      - DNA/Image: fraction of image that overlaps with DNA
    """
    bwimage = (imageproc > 0)
    imagelabeled,nr_objs = ndimage.label(bwimage)
    if not nr_objs:
        nfeatures = 5
        if not isfield:
            nfeatures += 3
        if dnaproc is not None:
            nfeatures += 2
        if (not isfield and (dnaproc is not None)):
            nfeatures  += 1
        return np.zeros(nfeatures)

    values = [nr_objs]
    dnacof = None
    euler_nr = euler(bwimage)
    values.append(euler_nr)

    cof = None
    if not isfield:
        cof = center_of_mass(imageproc.astype(np.uint32))

    obj_sizes = fullhistogram(imagelabeled.view(np.uint32))[1:]

    obj_size_avg = obj_sizes.mean()
    obj_size_var = obj_sizes.var()
    obj_size_ratio = obj_sizes.max()/obj_sizes.min()

    values.append(obj_size_avg)
    values.append(obj_size_var)
    values.append(obj_size_ratio)


    if not isfield:
        obj_cms = center_of_mass(imageproc.astype(np.uint32), imagelabeled)
        obj_cms = obj_cms[1:]
        obj_distances = []
        obj_dnadistances = []
        if dnaproc is not None:
            dnacof = center_of_mass(dnaproc.astype(np.uint32))
        for obj_center in obj_cms:
            obj_distance = _norm2(obj_center - cof)
            obj_distances.append(obj_distance)

            if dnaproc is not None:
                obj_dnadistance = _norm2(obj_center - dnacof)
                obj_dnadistances.append(obj_dnadistance)
        obj_distances = np.array(obj_distances)
        obj_dist_avg = obj_distances.mean()
        obj_dist_var = obj_distances.var()
        mindist = obj_distances.min()
        if mindist != 0:
            obj_dist_ratio = obj_distances.max()/mindist
        else:
            obj_dist_ratio = 0

        values.append(obj_dist_avg)
        values.append(obj_dist_var)
        values.append(obj_dist_ratio)

        if dnaproc is not None:
            obj_dnadistances = np.array(obj_dnadistances)
            obj_dnadist_avg = obj_dnadistances.mean()
            obj_dnadist_var = obj_dnadistances.var()
            obj_dnamindist=obj_dnadistances.min()
            if obj_dnamindist != 0:
                obj_dnadist_ratio = obj_dnadistances.max()/obj_dnamindist
            else:
                obj_dnadist_ratio = 0 ;
            values.append(obj_dnadist_avg)
            values.append(obj_dnadist_var)
            values.append(obj_dnadist_ratio)



    if dnaproc is not None:
        dna_area = (dnaproc > 0).sum()
        image_area = (imageproc > 0).sum()

        # what fraction of the image fluorescence area overlaps the dna image?
        image_overlap = ( (imageproc > 0) & (dnaproc > 0) ).sum()

        if image_area == 0:
            dna_image_area_ratio = 0
            image_dna_overlap = 0
        else:
            dna_image_area_ratio = dna_area/image_area
            image_dna_overlap = image_overlap/image_area

        if dnacof is not None:
            dna_image_distance = _norm2(cof-dnacof)
            values.append(dna_image_distance)
        values.append(dna_image_area_ratio)
        values.append(image_dna_overlap)
    return values
Ejemplo n.º 16
0
def lddp(image,
         radius1,
         radius2,
         points,
         ignore_zeros=False,
         preserve_shape=True):
    """
    Custom implementation of 2nd order local directional derivative pattern
    Originally obtained from mahotas.features.lbp_transform function.

    An inner and an outer radius with respect to a point, which is each image pixel are selected.
    Then, a set of points are obtained by interpolation on these radii, according to the number defined by *points*
    argument. Note that if, for example, 8 points are given, there are 8 points that are considered on the inner radius
    defined by equal angles starting from the central point and each one of them. If these two points (the origin, or the
    centre) and each point define a straight line, also 8 points on the same lines are considered for the outer radius.

    For reference see :

    Guo, Zhenhua, et al. "Local directional derivative pattern for rotation invariant texture classification."
    Neural Computing and Applications 21.8 (2012): 1893-1904.

    :param np.array image: numpy array input image
    :param int radius1: inner radius (in pixels)
    :param int radius2: outer radius (in pixels)
    :param int points: number of points to consider. It should be given regarding the inner radius, as the second set of points will be aligned to the ones lying in the inner circle.

    :return: lddp histogram
    """
    from mahotas import interpolate
    from mahotas.features import _lbp
    from mahotas import histogram

    if ignore_zeros and preserve_shape:
        raise ValueError(
            'mahotas.features.lbp_transform: *ignore_zeros* and *preserve_shape* cannot both be used together'
        )

    image = np.asanyarray(image, dtype=np.float64)
    if image.ndim != 2:
        raise ValueError(
            'mahotas.features.lbp_transform: This function is only defined for two dimensional images'
        )

    if ignore_zeros:
        Y, X = np.nonzero(image)

        def select(im):
            return im[Y, X].ravel()
    else:
        select = np.ravel

    pixels = select(image)
    angles = np.linspace(0, 2 * np.pi, points + 1)[:-1]
    data1 = []
    for dy, dx in zip(np.sin(angles), np.cos(angles)):
        data1.append(
            select(
                interpolate.shift(image, [radius1 * dy, radius1 * dx],
                                  order=1)))
    data1 = np.array(data1)

    data2 = []
    for dy, dx in zip(np.sin(angles), np.cos(angles)):
        data2.append(
            select(
                interpolate.shift(image, [radius2 * dy, radius2 * dx],
                                  order=1)))
    data2 = np.array(data2)
    data = np.array(data2 + pixels - 2 * data1)
    codes = (data >= 0).astype(np.int32)
    codes *= (2**np.arange(points)[:, np.newaxis])
    codes = codes.sum(0)

    codes = _lbp.map(codes.astype(np.uint32), points)
    if preserve_shape:
        codes = codes.reshape(image.shape)

    final = histogram.fullhistogram(codes.astype(np.uint32))

    codes = np.arange(2**points, dtype=np.uint32)
    iters = codes.copy()
    codes = _lbp.map(codes.astype(np.uint32), points)
    pivots = (codes == iters)
    npivots = np.sum(pivots)
    compressed = final[pivots[:len(final)]]
    compressed = np.append(compressed, np.zeros(npivots - len(compressed)))
    return compressed