def grid2D(self, drift_corrected = False):
     image = numpy.zeros(self.im_shape_2D, dtype = numpy.int32)
     for locs in self.locsInFrameRangeIterator(self.fmin, self.fmax, ["x", "y"]):
         if drift_corrected:
             locs["x"] += self.dx
             locs["y"] += self.dy
         i_x = numpy.floor(locs["x"]*self.scale).astype(numpy.int32)
         i_y = numpy.floor(locs["y"]*self.scale).astype(numpy.int32)
         gridC.grid2D(i_x, i_y, image)
     return image
Example #2
0
def renderImage(image, x, y, sigma):
    """
    A helper function that does the actual rendering.
    """
    # Histogram.
    if sigma is None:
        gridC.grid2D(numpy.round(y), numpy.round(x), image)
    # Gaussians.
    else:
        dg.drawGaussiansXYOnImage(image, y, x, sigma=sigma)
Example #3
0
 def grid2D(self, drift_corrected=False):
     image = numpy.zeros(self.im_shape_2D, dtype=numpy.int32)
     for locs in self.locsInFrameRangeIterator(self.fmin, self.fmax,
                                               ["x", "y"]):
         if drift_corrected:
             locs["x"] += self.dx
             locs["y"] += self.dy
         i_x = numpy.floor(locs["x"] * self.scale).astype(numpy.int32)
         i_y = numpy.floor(locs["y"] * self.scale).astype(numpy.int32)
         gridC.grid2D(i_x, i_y, image)
     return image
def renderImage(image, x, y, sigma):
    """
    A helper function that does the actual rendering.
    """
    # Histogram.
    if sigma is None:
        gridC.grid2D(numpy.round(y),
                     numpy.round(x),
                     image)
    # Gaussians.
    else:
        dg.drawGaussiansXYOnImage(image, y, x, sigma = sigma)
Example #5
0
def render2DImage(i3_reader, shape, category = None, offsets = None, scale = 2, sigma = None):
    """
    Create a grayscale image from a Insight3 format binary data.

    i3_reader - A readinsight3.I3Reader object.
    shape - The shape of the output image. This will be multiplied by scale.
    category - Filter for localizations of this category. The default is all categories.
    offsets - X,Y offset of the image origin.  The default is 0.0.
    scale - The 'zoom' level of the output image, i.e. if the original STORM movie was
            256x256 and scale = 2 then the output image will be 512x512.
    sigma - The sigma to use when rendering gaussians (pixels). If this is None then
            the image will be a histogram.
    """
    image = numpy.zeros((shape[0]*scale, shape[1]*scale))

    # Make sure we are starting at the beginning.
    i3_reader.resetFp()

    # Load the first block of data.
    i3_data = i3_reader.nextBlock()
    while (i3_data is not False):
        sys.stdout.write(".")
        sys.stdout.flush()

        # Filter by category, if requested.
        if category is not None:
            i3_data = i3dtype.maskData(i3_data, (i3_data['c'] == category))

        # Adjust by offsets, if specified. Note, not adjusted for scale.
        if offsets is not None:
            i3_data['xc'] -= offsets[0]
            i3_data['yc'] -= offsets[1]

        # Adjust x,y by scale.
        xc = i3_data['xc']*scale
        yc = i3_data['yc']*scale

        # Histogram.
        if sigma is None:
            gridC.grid2D(numpy.round(xc),
                         numpy.round(yc),
                         image)
        # Gaussians.
        else:
            dg.drawGaussiansXYOnImage(image, xc, yc, sigma = sigma)

        # Load next block of data.
        i3_data = i3_reader.nextBlock()

    print()
    return image
Example #6
0
    def gridTracks2D(self, dx = 0.0, dy = 0.0, verbose = False):
        image = numpy.zeros(self.im_shape_2D, dtype = numpy.int32)
        for locs in self.tracksIterator(fields = ["x", "y"]):
            if verbose:
                sys.stdout.write(".")
                sys.stdout.flush()

            f_x = locs["x"] + dx
            f_y = locs["y"] + dy
            
            i_x = numpy.floor(f_x*self.scale).astype(numpy.int32)
            i_y = numpy.floor(f_y*self.scale).astype(numpy.int32)
            gridC.grid2D(i_x, i_y, image)
            
        if verbose:
            sys.stdout.write("\n")
            
        return image
Example #7
0
    def i3To2DGrid(self, fmin = 0, fmax = 500000, zmin = -1000.0, zmax = 1000.0, uncorrected = False, matrix = False, translate = False, verbose = True):

        if uncorrected:
            [x, y, z] = [self.i3data['x'],
                         self.i3data['y'],
                         self.i3data['z']]
        else:
            [x, y, z] = [self.i3data['xc'],
                         self.i3data['yc'],
                         self.i3data['zc']]
            
        cat = self.i3data['c']
        f = self.i3data['fr']

        [image_x, image_y] = self.im_size
        scale = int(self.scale)

        if type(matrix) == type(numpy.array([])):
            if translate:
                [x, y] = regfilereader.applyTransform(matrix, x, y)
            else:
                [x, y] = regfilereader.applyTransformNoTranslation(matrix, x, y)

        max_max = 0.0
        max_counts = []
        image_data = []
        for channel in self.channels:
            mask = (cat == channel) & (f >= fmin) & (f < fmax) & (z > zmin) & (z < zmax)
            #print numpy.sum(mask)
            i_x = numpy.round(x[mask] * scale).astype(int)
            i_y = numpy.round(y[mask] * scale).astype(int)
            if (i_x.shape[0] > 0):
                channel_data = grid_c.grid2D(i_x,i_y,(image_x*scale,image_y*scale))
            else:
                channel_data = numpy.zeros((image_x*scale, image_y*scale))
            image_data.append(channel_data.astype(numpy.float32))
            max_count = numpy.max(channel_data)
            if max_count > max_max:
                max_max = max_count
            max_counts.append(max_count)

        return [image_data, self.channels, max_counts, max_max]
Example #8
0
    def i3To2DGrid(self, fmin = 0, fmax = 500000, zmin = -1000.0, zmax = 1000.0, uncorrected = False, matrix = False, translate = False, verbose = True):

        if uncorrected:
            [x, y, z] = [self.i3data['x'],
                         self.i3data['y'],
                         self.i3data['z']]
        else:
            [x, y, z] = [self.i3data['xc'],
                         self.i3data['yc'],
                         self.i3data['zc']]
            
        cat = self.i3data['c']
        f = self.i3data['fr']

        [image_x, image_y] = self.im_size
        scale = int(self.scale)

        if type(matrix) == type(numpy.array([])):
            if translate:
                [x, y] = regfilereader.applyTransform(matrix, x, y)
            else:
                [x, y] = regfilereader.applyTransformNoTranslation(matrix, x, y)

        max_max = 0.0
        max_counts = []
        image_data = []
        for channel in self.channels:
            mask = (cat == channel) & (f >= fmin) & (f < fmax) & (z > zmin) & (z < zmax)
            #print numpy.sum(mask)
            i_x = numpy.round(x[mask] * scale).astype(int)
            i_y = numpy.round(y[mask] * scale).astype(int)
            if (i_x.shape[0] > 0):
                channel_data = grid_c.grid2D(i_x,i_y,(image_x*scale,image_y*scale))
            else:
                channel_data = numpy.zeros((image_x*scale, image_y*scale))
            image_data.append(channel_data.astype(numpy.float32))
            max_count = numpy.max(channel_data)
            if max_count > max_max:
                max_max = max_count
            max_counts.append(max_count)

        return [image_data, self.channels, max_counts, max_max]
Example #9
0
def frcCalc2d(h5_name, frc_name, scale = 8, verbose = True, show_plot = True):
    """
    Calculate the 2D FRC by putting half the tracks in the first
    image and half of them in the second image.
    """
    with saH5Py.SAH5Py(h5_name) as h5:

        pixel_size = h5.getPixelSize()
        n_tracks = h5.getNTracks()
        mx, my = h5.getMovieInformation()[:2]

        grid1 = numpy.zeros((mx * scale, my * scale), dtype = numpy.int32)
        grid2 = numpy.zeros((mx * scale, my * scale), dtype = numpy.int32)

        if verbose:
            print("Generating images.")
        for locs in h5.tracksIterator(fields = ["track_id", "x", "y"]):
            if verbose:
                sys.stdout.write(".")
                sys.stdout.flush()

            # We put all the even numbered tracks in the first image, all
            # the odd ones in the second.
            #
            mask = ((locs["track_id"]%2)==0)

            i_x = numpy.floor(locs["x"][mask] * scale).astype(numpy.int32)
            i_y = numpy.floor(locs["y"][mask] * scale).astype(numpy.int32)
            gridC.grid2D(i_x, i_y, grid1)

            i_x = numpy.floor(locs["x"][~mask] * scale).astype(numpy.int32)
            i_y = numpy.floor(locs["y"][~mask] * scale).astype(numpy.int32)
            gridC.grid2D(i_x, i_y, grid2)

        if verbose:
            sys.stdout.write("\n")

    # Compute FFT
    if verbose:
        print(numpy.sum(grid1), "points in image 1.")
        print(numpy.sum(grid2), "points in image 2.")
        print("Calculating FRC.")
        
    grid1_fft = numpy.fft.fftshift(numpy.fft.fft2(grid1))
    grid2_fft = numpy.fft.fftshift(numpy.fft.fft2(grid2))

    grid1_fft_sqr = grid1_fft * numpy.conj(grid1_fft)
    grid2_fft_sqr = grid2_fft * numpy.conj(grid2_fft)
    grid1_grid2 = grid1_fft * numpy.conj(grid2_fft)

    [frc, frc_counts] = frcC.frc(grid1_fft, grid2_fft)

    for i in range(frc.size):
        if (frc_counts[i] > 0):
            frc[i] = frc[i]/float(frc_counts[i])
        else:
            frc[i] = 0.0

    xvals = numpy.arange(frc.size)
    xvals = xvals/(float(grid1_fft.shape[0]) * pixel_size * (1.0/float(scale)))
    frc = numpy.real(frc)

    numpy.savetxt(frc_name, numpy.transpose(numpy.vstack((xvals, frc))))

    if show_plot:
        storm_analysis.configureMatplotlib()
           
        pyplot.scatter(xvals, frc, s = 4, color = 'black')
        pyplot.xlim([xvals[0], xvals[-1]])
        pyplot.ylim([-0.2,1.2])
        pyplot.xlabel("Spatial Frequency (nm-1)")
        pyplot.ylabel("Correlation")
        pyplot.show()
def render3DImage(i3_reader,
                  shape,
                  category=None,
                  offsets=None,
                  scale=2,
                  sigma=None,
                  z_edges=None):
    """
    Create a stack of grayscale images from a Insight3 format binary data.

    i3_reader - A readinsight3.I3Reader object.
    shape - The shape of the output image. This will be multiplied by scale.
    category - Filter for localizations of this category. The default is all categories.
    offsets - X,Y offset of the image origin.  The default is 0.0.
    scale - The 'zoom' level of the output image, i.e. if the original STORM movie was
            256x256 and scale = 2 then the output image will be 512x512.
    sigma - The sigma to use when rendering gaussians (pixels). If this is None then
            the image will be a histogram.
    z_edges - A list of z values specifying the z range for each image. This should be
            in nanometers.
    """
    num_z = len(z_edges) - 1
    images = []
    for i in range(num_z):
        images.append(numpy.zeros((shape[0] * scale, shape[1] * scale)))

    # Make sure we are starting at the beginning.
    i3_reader.resetFp()

    # Load the first block of data.
    i3_data = i3_reader.nextBlock()
    while (i3_data is not False):
        sys.stdout.write(".")
        sys.stdout.flush()

        # Filter by category, if requested.
        if category is not None:
            i3_data = i3dtype.maskData(i3_data, (i3_data['c'] == category))

        # Adjust by offsets, if specified. Note, not adjusted for scale.
        if offsets is not None:
            i3_data['xc'] -= offsets[0]
            i3_data['yc'] -= offsets[1]

        # Adjust x,y by scale.
        xc = i3_data['xc'] * scale
        yc = i3_data['yc'] * scale

        # Iterate through z ranges.
        for i in range(num_z):
            z_mask = (i3_data['zc'] > z_edges[i]) & (i3_data['zc'] <
                                                     z_edges[i + 1])

            xc_z = xc[z_mask]
            yc_z = yc[z_mask]

            # Histogram.
            if sigma is None:
                images[i] += gridC.grid2D(numpy.round(xc_z), numpy.round(yc_z),
                                          images[0].shape)
            # Gaussians.
            else:
                dg.drawGaussiansXYOnImage(images[i], xc_z, yc_z, sigma=sigma)

        # Load next block of data.
        i3_data = i3_reader.nextBlock()

    print()
    return images
Example #11
0
def frcCalc2d(h5_name, frc_name, scale=8, verbose=True, show_plot=True):
    """
    Calculate the 2D FRC by putting half the tracks in the first
    image and half of them in the second image.
    """
    with saH5Py.SAH5Py(h5_name) as h5:

        pixel_size = h5.getPixelSize()
        n_tracks = h5.getNTracks()
        mx, my = h5.getMovieInformation()[:2]

        grid1 = numpy.zeros((mx * scale, my * scale), dtype=numpy.int32)
        grid2 = numpy.zeros((mx * scale, my * scale), dtype=numpy.int32)

        if verbose:
            print("Generating images.")
        for locs in h5.tracksIterator(fields=["track_id", "x", "y"]):
            if verbose:
                sys.stdout.write(".")
                sys.stdout.flush()

            # We put all the even numbered tracks in the first image, all
            # the odd ones in the second.
            #
            mask = ((locs["track_id"] % 2) == 0)

            i_x = numpy.floor(locs["x"][mask] * scale).astype(numpy.int32)
            i_y = numpy.floor(locs["y"][mask] * scale).astype(numpy.int32)
            gridC.grid2D(i_x, i_y, grid1)

            i_x = numpy.floor(locs["x"][~mask] * scale).astype(numpy.int32)
            i_y = numpy.floor(locs["y"][~mask] * scale).astype(numpy.int32)
            gridC.grid2D(i_x, i_y, grid2)

        if verbose:
            sys.stdout.write("\n")

    # Compute FFT
    if verbose:
        print(numpy.sum(grid1), "points in image 1.")
        print(numpy.sum(grid2), "points in image 2.")
        print("Calculating FRC.")

    grid1_fft = numpy.fft.fftshift(numpy.fft.fft2(grid1))
    grid2_fft = numpy.fft.fftshift(numpy.fft.fft2(grid2))

    grid1_fft_sqr = grid1_fft * numpy.conj(grid1_fft)
    grid2_fft_sqr = grid2_fft * numpy.conj(grid2_fft)
    grid1_grid2 = grid1_fft * numpy.conj(grid2_fft)

    [frc, frc_counts] = frcC.frc(grid1_fft, grid2_fft)

    for i in range(frc.size):
        if (frc_counts[i] > 0):
            frc[i] = frc[i] / float(frc_counts[i])
        else:
            frc[i] = 0.0

    xvals = numpy.arange(frc.size)
    xvals = xvals / (float(grid1_fft.shape[0]) * pixel_size *
                     (1.0 / float(scale)))
    frc = numpy.real(frc)

    numpy.savetxt(frc_name, numpy.transpose(numpy.vstack((xvals, frc))))

    if show_plot:
        storm_analysis.configureMatplotlib()

        pyplot.scatter(xvals, frc, s=4, color='black')
        pyplot.xlim([xvals[0], xvals[-1]])
        pyplot.ylim([-0.2, 1.2])
        pyplot.xlabel("Spatial Frequency (nm-1)")
        pyplot.ylabel("Correlation")
        pyplot.show()