Пример #1
0
def invertVolume2D(data, sizeFilter=[2, 1000]):
    res = numpy.zeros(data.shape)

    #invert each layer
    for z in range(res.shape[2]):
        layer = vigra.Image(data[:, :, z])
        layer = vigra.analysis.labelImageWithBackground(1 - layer)
        feat   = vigra.analysis.extractRegionFeatures(\
                vigra.Image(layer)\
                ,numpy.array(layer),[\
                'Count',\
                'Mean'\
                ])

        #Remove BG
        Valid1 = feat["Mean"][numpy.argwhere(
            feat["Count"] > sizeFilter[0]).T[0]]
        Valid2 = feat["Mean"][numpy.argwhere(
            feat["Count"] < sizeFilter[1]).T[0]]
        Valid = numpy.intersect1d(Valid1, Valid2)
        tmp = numpy.zeros(layer.shape)
        for c in Valid:
            if c == 0: continue
            tmp_c = (layer == c)
            res[:, :, z][tmp_c] = 1

    return res
Пример #2
0
def vigra_gaussfast(data,kernels):
  img = vigra.Image(data)
  out = []
  for k in kernels:
    tmp = vigra.filters.convolveOneDimension(img,0,k)
    out.append(vigra.filters.convolveOneDimension(tmp,1,k))
  return out
Пример #3
0
def vigra_gauss(data,sigmas):
  out = []
  for d in data:
    img = vigra.Image(d)
    for sigma in sigmas:
      out.append(np.asarray(vigra.filters.gaussianSmoothing(img, sigma)))

  return out
Пример #4
0
    def test_basic(self):
        n = Nerve(vagus_data)

        n.sigmaSmooth = 1
        n.thresMembra = 0.5
        n.sizeFilter = [20, 1000]
        n.run()
        res = n.seg

        layer = res[:, :, 50]
        assert (numpy.max(layer) == 1)
        assert (numpy.min(layer) == 0)

        components = vigra.analysis.labelImageWithBackground(
            vigra.Image(layer))
        assert (len(components) > 5)
Пример #5
0
def calc_features(data):
  img = vigra.Image(data)

  sigmas = [0.7, 1.0, 1.6, 3.5, 5, 10]
  features = np.zeros((8*len(sigmas) + 1, data.shape[0], data.shape[1]))

  features[0,:,:] = np.asarray(vigra.filters.gaussianSmoothing(img, 0.3))

  for i, sigma in enumerate(sigmas):
    stensor = vigra.filters.structureTensorEigenvalues(img, sigma, sigma/2.0)
    hogev = vigra.filters.hessianOfGaussianEigenvalues(img, sigma)

    features[1 + 0*len(sigmas) + i, :, :] = np.asarray(vigra.filters.gaussianSmoothing(img, sigma))
    features[1 + 1*len(sigmas) + i, :, :] = np.asarray(vigra.filters.laplacianOfGaussian(img, sigma))
    features[1 + 2*len(sigmas) + i, :, :] = np.asarray(vigra.filters.gaussianGradientMagnitude(img, sigma))
    features[1 + 3*len(sigmas) + i, :, :] = np.asarray(vigra.filters.gaussianSmoothing(img, sigma) - vigra.filters.gaussianSmoothing(img, 0.66*sigma))
    features[1 + 4*len(sigmas) + i, :, :] = np.asarray(stensor[:,:,0])
    features[1 + 5*len(sigmas) + i, :, :] = np.asarray(stensor[:,:,1])
    features[1 + 6*len(sigmas) + i, :, :] = np.asarray(hogev[:,:,0])
    features[1 + 7*len(sigmas) + i, :, :] = np.asarray(hogev[:,:,1])

  features = features.swapaxes(0, 2).swapaxes(0, 1)
  return features
Пример #6
0
import time
import numpy as np
import vigra
import h5py
import matplotlib.pyplot as plt
import dist

set = h5py.File(
    '/export/home/abailoni/datasets/cremi/SOA_affinities/sampleB_train.h5')

groundtruth = set['segmentations/groundtruth_fixed']

example = groundtruth[100, :, :]
example_edges = np.empty_like(example)
example_edges[:] = vigra.analysis.shenCastanEdgeImage(vigra.Image(example), 1.,
                                                      0.5, 1)
"""
example_edges = np.empty_like(example)
for layer in range(example.shape[0]):
    example_layer = vigra.Image(example[layer])
    example_edges[layer] = vigra.analysis.shenCastanEdgeImage(example_layer, 1., 0.5, 1)
    print(f'finished layer {layer}')
"""


def get_top_left_distance(arr):
    """
    get the distance to the next 1 in the top left direction
    :param arr: 2d-arr (m, n)
    :return: dist_arr: (m, n)
    """
Пример #7
0
    af_convolve[i] = end-start

    start = time.clock()
    #---
    afres_h = afres.__array__()
    af.sync()
    #---
    end = time.clock()
    af_cpy_dh[i] = end-start

    ksize = int(3*args.sigma)*2+1
    convopts = vigra.blockwise.convolutionOptions((ksize,ksize),sigma=args.sigma,numThreads=8)
    ## vigra measurement
    start = time.clock()
    #---
    vimg = vigra.Image(img)
    vres = np.asarray(vigra.blockwise.gaussianSmooth(vimg, options=convopts))
    #---
    end = time.clock()
    vigra_t[i] = end-start

  if not args.raw:
    print "--- Results ---"
    print "\tAf kernel creation =",af_kernel
    print "\tMean copy h->d =",np.mean(af_cpy_hd),"("+str(np.sqrt(np.var(af_cpy_hd)))+")"
    print "\tMean convolve =",np.mean(af_convolve),"("+str(np.sqrt(np.var(af_convolve)))+")"
    print "\tMean copy d->h =",np.mean(af_cpy_dh),"("+str(np.sqrt(np.var(af_cpy_dh)))+")"
    print "\tMean arrayfire =",np.mean(af_cpy_hd+af_cpy_dh+af_convolve),"("+str(np.sqrt(np.var(af_cpy_hd+af_cpy_dh+af_convolve)))+")"
    print "\tMean vigra =",np.mean(vigra_t),"("+str(np.sqrt(np.var(vigra_t)))+")"

  else: # print raw
Пример #8
0
 def vigra_image(self):
     ar = self.image.toArray()
     return vigra.Image(ar, dtype=ar.dtype)
Пример #9
0
import vigra
import h5py
import numpy as np

file = h5py.File('gt_cleaned.h5')
data = np.array(file['data'][:, :, :])
"""
print(data.shape)
boundaries = np.empty_like(data, dtype=np.int32)
for i in range(data.shape[0]):
    boundaries[i] = vigra.analysis.shenCastanEdgeImage(vigra.Image(data[i]), 1., 0.5, 1)
    print(i)
"""

#distances = vigra.filters.boundaryDistanceTransform(data)

distances = np.empty((*data.shape, 2), dtype=np.float32)

for i in range(data.shape[0]):
    edge = vigra.analysis.regionImageToEdgeImage(data[i])
    distances[i] = vigra.filters.vectorDistanceTransform(vigra.Image(edge))

#targetfile = h5py.File('./vector_dist_trans.h5', 'w')
#target_data = targetfile.create_dataset('data', data=distances, dtype=np.float32)
#print(target_data.shape)
Пример #10
0
def marchingSquares(image,
                    level=0,
                    variant=True,
                    border=True,
                    initialize=True,
                    markOuter=1):
    """Return a new GeoMap with sub-pixel level contours extracted by
    the marching squares method.  (Pixels with values < level are
    separated from pixels >= level.)

    If the image does not have an attribute 'siv', standard linear
    interpolation is used.  If image.siv exists, it should be a
    SplineImageView that is used for the Newton-Raphson method to
    perform another subsequent sub-pixel correction.

    The optional parameter `variant` determines the handling of the
    ambiguous diagonal configuration:

    `variant` = True (default)
      always let the two sampling points above `level` be connected

    `variant` = False
      always let the two opposite sampling points < `level` be connected

    `variant` = SplineImageView(...)
      for each ambiguous configuration, check the midpoint of the
      square; then handle as if variant = (midpoint >= level)

    If `initialize` is a true value (default), the map will be
    initialized.

    If markOuter is != 0, the faces above(outer == 1) / below(outer == -1)
    the threshold are marked with the OUTER_FACE flag (this only works
    if the map is initialized)."""

    connections1 = ((1, 0), (0, 2), (1, 2), (3, 1), (3, 0), (0, 2), (3, 1),
                    (3, 2), (2, 3), (1, 0), (2, 3), (0, 3), (1, 3), (2, 1),
                    (2, 0), (0, 1))
    connections2 = ((1, 0), (0, 2), (1, 2), (3, 1), (3, 0), (0, 1), (3, 2),
                    (3, 2), (2, 3), (1, 3), (2, 0), (0, 3), (1, 3), (2, 1),
                    (2, 0), (0, 1))
    configurations = (0, 0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 16)

    result = geomap.GeoMap(image.shape)

    def addNodeDirectX(x, y, ofs):
        pos = Vector2(x + ofs, y)
        # out of three successive pixels, the middle one may be the
        # threshold, then we would get duplicate points already in the
        # horizontal pass:
        node = result.nearestNode(pos, 1e-8)
        return node or result.addNode(pos)

    def addNodeDirectY(x, y, ofs):
        pos = Vector2(x, y + ofs)
        node = result.nearestNode(pos, 1e-8)  # already exists? (e.g. hNodes?)
        return node or result.addNode(pos)

    def addNodeNewtonRefinementX(x, y, ofs):
        for i in range(100):
            o = -(image.siv(x + ofs, y) - level) / image.siv.dx(x + ofs, y)
            if abs(o) > 0.5:
                o = vigra.sign(o) * 0.05
            ofs += o
            if ofs <= 0 or ofs >= 1:
                ofs -= o
                break
            if abs(o) < 1e-4:
                break
        return addNodeDirectX(x, y, ofs)

    def addNodeNewtonRefinementY(x, y, ofs):
        for i in range(100):
            o = -(image.siv(x, y + ofs) - level) / image.siv.dy(x, y + ofs)
            if abs(o) > 0.5:
                o = vigra.sign(o) * 0.05
            ofs += o
            if ofs <= 0 or ofs >= 1:
                ofs -= o
                break
            if abs(o) < 1e-4:
                break
        return addNodeDirectY(y, y, ofs)

    if hasattr(image, "siv"):
        addNodeX = addNodeNewtonRefinementX
        addNodeY = addNodeNewtonRefinementY
    else:
        addNodeX = addNodeDirectX
        addNodeY = addNodeDirectY

    hNodes = vigra.Image(image.shape, numpy.uint32)
    v1 = image[:-1]
    v2 = image[1:]
    ofs = (level - v1) / (v2 - v1)
    for x, y in numpy.transpose(numpy.nonzero((v1 < level) != (v2 < level))):
        hNodes[x, y] = addNodeX(x, y, ofs).label()

    vNodes = vigra.Image(image.shape, numpy.uint32)
    v1 = image[:, :-1]
    v2 = image[:, 1:]
    ofs = (level - v1) / (v2 - v1)
    for x, y in numpy.transpose(numpy.nonzero((v1 < level) != (v2 < level))):
        vNodes[x, y] = addNodeY(x, y, ofs).label()

    nodes = (hNodes, vNodes, vNodes, hNodes)
    offsets = numpy.array(((0, 0), (0, 0), (1, 0), (0, 1)))

    defaultConnections = connections1
    if variant == False:
        defaultConnections = connections2
    if isinstance(variant, bool):
        variant = None

    configurations = ((image[:-1, :-1] < level) +
                      (image[1:, :-1] < level) * 2 +
                      (image[:-1, 1:] < level) * 4 +
                      (image[1:, 1:] < level) * 8)
    for x, y in numpy.transpose(numpy.nonzero(configurations)):
        config = configurations[x, y]

        connections = connections1
        if variant is not None and config in (6, 9):
            if variant(x + 0.5, y + 0.5) < level:
                connections = connections2

        for s, e in connections[configurations[config]:configurations[config +
                                                                      1]]:
            startNode = result.node(int(nodes[s][tuple(offsets[s] + (x, y))]))
            endNode = result.node(int(nodes[e][tuple(offsets[e] + (x, y))]))
            if startNode != endNode:
                result.addEdge(startNode, endNode,
                               [startNode.position(),
                                endNode.position()])

    maputils.mergeDegree2Nodes(result)  # node suppression
    result = maputils.copyMapContents(result)[0]  # compress edge labels

    if border:
        maputils.connectBorderNodes(result, 0.5)
        result.sortEdgesEventually(0.4, 0.01)

    if not initialize:
        return result

    result.initializeMap()
    if markOuter:
        markOuter = markOuter > 0
        it = result.faceIter()
        if border:
            it.next().setFlag(flag_constants.OUTER_FACE)
        for face in it:
            face.setFlag(flag_constants.OUTER_FACE,
                         (face.contours().next().label() < 0) == markOuter)

    return result