Пример #1
0
def rand_spot():
    coord = [
        random.randint(spotR, w - spotR),
        random.randint(spotR, h - spotR),
        random.randint(spotR, d - spotR)
    ]
    return RealPoint(array(coord, 'd'))
def show(title, nuclei, radius, bounds, scale=1.0):
    points = [RealPoint.wrap([c * scale for c in coords]) for coords in nuclei]
    interval = FinalInterval([int(b * scale) for b in bounds[0]],
                             [int(b * scale) for b in bounds[1]])
    img = virtualPointsRAI(points, radius * scale, interval)
    imp = showStack(img, title=title)
    return imp, img, points
def withVirtualStack(time_window=None, subsample=None):
    with open(os.path.join(baseDir, csvFilename), 'r') as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar='"')
        header = reader.next()
        peaks = [
            RealPoint.wrap(imap(float, peak.split('::')))
            for peak in islice(header, 1, None)
        ]
        frames = [
            virtualPointsRAI(peaks,
                             radius,
                             interval,
                             inside=to8bitRange(
                                 map(float, islice(row, 1, None))))
            for row in reader
        ]
        if time_window:
            first, last = time_window
            frames = frames[first:last + 1]
        img4D = Views.stack(frames)
        # Scale by a factor of 'subsample' in every dimension by nearest neighbor, sort of:
        if subsample:
            img4D = Views.subsample(img4D, subsample)
        imp = ImagePlus("deltaF/F", ImageJVirtualStackUnsignedByte.wrap(img4D))
        imp.setDimensions(1, img4D.dimension(2), img4D.dimension(3))
        imp.setDisplayRange(0, 255)
        com = CompositeImage(imp, CompositeImage.GRAYSCALE)
        com.show()
        univ = Image3DUniverse(512, 512)
        univ.show()
        univ.addVoltex(com)
Пример #4
0
def withIcospheres(time_window=None):
  with open(os.path.join(baseDir, csvFilename), 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='"')
    header = reader.next()
    peaks = [RealPoint.wrap(imap(float, peak.split('::'))) for peak in islice(header, 1, None)]
    # Template icosahedron
    ico = MeshMaker.createIcosahedron(2, radius)
    # Share lists of Point3f across all timepoints
    icos = [MeshMaker.copyTranslated(ico, peak.getFloatPosition(0), peak.getFloatPosition(1) , peak.getFloatPosition(2)) for peak in peaks]
    #
    univ = Image3DUniverse(512, 512)
    instants = TreeMap()
    #
    rows = reader if time_window is None else islice(reader, time_window[0], time_window[1])
    for row in rows:
      # Values mapped to 0-1: Color3f takes 3 values in domain [0, 1].
      # So: ensure the value is inside [minimum, maximum] range, then rezero by subtracting minimum, and divide by span (maximum - minimum)
      values = ((min(max(float(v), minimum), maximum) - minimum) / span for v in islice(row, 1, None))
      meshes = [CustomTriangleMesh(mesh, Color3f(v, v, v), 0)
                for v, mesh in izip(values, icos)]
      ci = ContentInstant(str(row[0]))
      ci.display(CustomMultiMesh(meshes)) # each mesh has its color
      ci.setLocked(True)
      print row[0]
      instants.put(int(row[0]), ci)
    
    print "n instants:", instants.size()
    univ.addContent(Content("deltaF/F", instants, False))
    univ.show()
    univ.updateStartAndEndTime(0, len(instants) -1)
Пример #5
0
def findEdgePixels(img):
  edge_pix = []
  zero = img.firstElement().createVariable()
  zero.setZero()
  imgE = Views.extendValue(img, zero)
  pos = zeros(img.numDimensions(), 'l')
  inc = partial(operator.add, 1)
  dec = partial(operator.add, -1)
  cursor = img.cursor()
  while cursor.hasNext():
    t = cursor.next()
    # A pixel is on the edge of the binary mask
    # if it has a non-zero value
    if 0 == t.getByte():
      continue
    # ... and its immediate neighbors ...
    cursor.localize(pos)
    minimum = array(imap(dec, pos), 'l') # map(dec, pos) also works, less performance
    maximum = array(imap(inc, pos), 'l') # map(inc, pos) also works, less performance
    neighborhood = Views.interval(imgE, minimum, maximum)
    # ... have at least one zero value:
    # Good performance: the "if x in <iterable>" approach stops upon finding the first x    
    if 0 in imap(UnsignedByteType.getByte, neighborhood):
      edge_pix.append(RealPoint(array(list(pos), 'f')))
  return edge_pix
Пример #6
0
def findEdgePixels(img):
    edge_pix = []
    zero = img.firstElement().createVariable()
    zero.setZero()
    imgE = Views.extendValue(img, zero)
    pos = zeros(img.numDimensions(), 'l')
    inc = partial(operator.add, 1)
    dec = partial(operator.add, -1)
    cursor = img.cursor()
    while cursor.hasNext():
        t = cursor.next()
        if 0 == t.getIntegerLong():
            continue
        # Sum neighbors of non-zero pixel: if any is zero, sum is less than 27
        # and we have found an edge pixel
        cursor.localize(pos)
        minimum = map(dec, pos)
        maximum = map(inc, pos)
        box = Views.interval(imgE, minimum, maximum)
        if sum(imap(UnsignedByteType.getIntegerLong, box)) < 27:
            edge_pix.append(RealPoint(array(list(pos), 'f')))
    return edge_pix
Пример #7
0
t3 = System.currentTimeMillis()

for peak in peaks:
    hsc.updateCenter([int(peak[0]), int(peak[1]), int(peak[2])])
    s = sum(imap(FloatType.getRealFloat, hsc))
    intensities2.append(float(s) / size)

t4 = System.currentTimeMillis()

print "Elapsed time:", (t4 - t3), "ms"

#print intensities2

# Try now with the deprecated ellipse
sphere = EllipseRegionOfInterest(RealPoint(3), [radius, radius, radius])
ii = sphere.getIterableIntervalOverROI(copy2)
size = ii.size()
intensities3 = []

t5 = System.currentTimeMillis()

for peak in peaks:
    sphere.setOrigin([int(peak[0]), int(peak[1]), int(peak[2])])
    s = sum(imap(FloatType.getRealFloat, ii.cursor()))
    intensities3.append(float(s) / size)

t6 = System.currentTimeMillis()

print "Elapsed time:", (t6 - t5), "ms"
Пример #8
0
        "calibration": calibration,
        "minPeakValue": 0.2,  # determined by hand: the bright peaks
        "sigmaSmaller": somaDiameter / 4.0,  # in calibrated units: 1/4 soma
        "sigmaLarger": somaDiameter / 2.0,  # in calibrated units: 1/2 soma
    }

    csv_path = os.path.join(
        tgtDir, "peaks_somaDiameter=%0.1f_minPeakValue=%0.3f.csv" %
        (somaDiameter, params["minPeakValue"]))

    if os.path.exists(csv_path):
        print "Parsing CSV file %s" % csv_path
        with open(csv_path, 'r') as csvfile:
            reader = csv.reader(csvfile, delimiter=',', quotechar="\"")
            reader.next()  # skip first line: the header
            peaks = [RealPoint.wrap(map(float, coords)) for coords in reader]

    else:
        peaks = doGPeaks(max_projection, params)
        print "Detected %i peaks with somaDiameter %f" % (len(peaks),
                                                          somaDiameter)

        if len(peaks) > 0:
            with open(csv_path, 'w') as csvfile:
                w = csv.writer(csvfile,
                               delimiter=",",
                               quoting=csv.QUOTE_NONNUMERIC)
                w.writerow(["x", "y", "z"])  # header
                for peak in peaks:
                    w.writerow([peak.getFloatPosition(d) for d in xrange(3)])
Пример #9
0
		this.search.search(this);
		if (this.search.getSquareDistance() < this.radius_squared)
		{
			return inside;
		}
		return outside;
	}
}

public final Spheres createSpheres(final KDTree kdtree,
                                   final double radius,
	                               final UnsignedShortType inside,
	                               final UnsignedShortType outside)
{
	return new Spheres(kdtree, radius, inside, outside);
}

""", [
        RealPoint, RealRandomAccess, KDTree, NearestNeighborSearchOnKDTree,
        UnsignedShortType
    ])

points = [RealPoint([i, i, i]) for i in xrange(10)]
kdtree = KDTree(points, points)

# Works:
ws = ws.createSpheres(kdtree, 2, UnsignedShortType(255), UnsignedShortType(0))

# Mysteriously fails with "expected 5 args, got 4". Has to do with calling the subclass constructor like a method.
#ws = ws.Spheres(kdtree, 2, UnsignedShortType(255), UnsignedShortType(0))
def measureFluorescence(series_name, img4D, mask=None):
    csv_fluorescence = os.path.join(srcDir,
                                    "%s_fluorescence.csv" % series_name)
    if not os.path.exists(csv_fluorescence):
        # Generate projection over time (the img3D) and extract peaks with difference of Gaussian using the params
        # (Will check if file for projection over time exists and just load it)
        img3D_filepath = os.path.join(
            srcDir, "%s_4D-to-3D_max_projection.zip" % series_name)
        img3D, peaks, spheresRAI, impSpheres = findNucleiByMaxProjection(
            img4D, params, img3D_filepath, show=True)
        comp = showAsComposite([wrap(img3D), impSpheres])
        # Measure intensity over time, for every peak
        # by averaging the signal within a radius of each peak.
        measurement_radius = somaDiameter / 3.0
        spheres = [
            ClosedWritableSphere([peak.getFloatPosition(d)
                                  for d in xrange(3)], measurement_radius)
            for peak in peaks
        ]
        insides = [
            Regions.iterable(
                Views.interval(
                    Views.raster(Masks.toRealRandomAccessible(sphere)),
                    Intervals.largestContainedInterval(sphere)))
            for sphere in spheres
        ]

        count = float(Regions.countTrue(insides[0]))  # same for all
        measurements = []

        with open(csv_fluorescence, 'w') as csvfile:
            w = csv.writer(csvfile,
                           delimiter=",",
                           quotechar='"',
                           quoting=csv.QUOTE_NONNUMERIC)
            # Header: with peak coordinates
            w.writerow(["timepoint"] + [
                "%.2f::%.2f::%.2f" %
                tuple(peak.getFloatPosition(d) for d in xrange(3))
                for peak in peaks
            ])
            # Each time point
            for t in xrange(img4D.dimension(3)):
                img3D = Views.hyperSlice(img4D, 3, t)
                mean_intensities = array(
                    ((sum(t.get()
                          for t in Regions.sample(inside, img3D)) / count)
                     for inside in insides), 'f')
                w.writerow([t] + mean_intensities.tolist())
                measurements.append(mean_intensities)

    else:
        # Parse CSV file
        with open(csv_fluorescence, 'r') as csvfile:
            reader = csv.reader(csvfile, delimiter=',', quotechar='"')
            header = reader.next()
            # Parse header, containing peak locations
            peaks = [
                RealPoint.wrap(map(float, h.split("::")))
                for h in islice(header, 1, None)
            ]
            # Parse rows
            measurements = [map(float, islice(row, 1, None)) for row in reader]

    return peaks, measurements
Пример #11
0
# Test whether the first nearest neighbor is the point itself
from net.imglib2 import RealPoint, KDTree
from net.imglib2.neighborsearch import RadiusNeighborSearchOnKDTree

points = [RealPoint.wrap([1.0, 1.0, float(i)]) for i in xrange(10)]

tree = KDTree(points, points)
search = RadiusNeighborSearchOnKDTree(tree)

radius = 3
search.search(RealPoint.wrap([1.0, 1.0, 1.0]), 3, False) # unordered

for i in xrange(search.numNeighbors()):
  print "Point " + str(i), search.getSampler(i).get()


# Prints:
# Point 0 (1.0,1.0,3.0)
# Point 1 (1.0,1.0,4.0)
# Point 2 (1.0,1.0,0.0)
# Point 3 (1.0,1.0,1.0)
# Point 4 (1.0,1.0,2.0)


# So yes: the first point is always the query point.
Пример #12
0
import sys
sys.path.append("/home/albert/lab/scripts/python/imagej/IsoView-GCaMP/")
from lib.io import readN5
from lib.dogpeaks import createDoG
from lib.synthetic import virtualPointsRAI
from lib.ui import showStack
from net.imglib2 import RealPoint, FinalInterval


points = [RealPoint.wrap([255, 255, 255]),
          RealPoint.wrap([255, 255, 0]),
          RealPoint.wrap([128, 384, 128])]

rai = virtualPointsRAI(points, 70, FinalInterval([512, 512, 512]))
imp = showStack(rai, title="test virtualPointsRAI")