Example #1
0
def filesInit(savePath, name, nbFrames, maxFrames):
    """
    Initialize the right number of .tif files to save the frames.
    Initialize a .txt file to save metadata related to each frame.
    """
    #Initiate a list of TiffWriter object (one per file)
    tifList = []
    if ((nbFrames % maxFrames) >
            0):  ##checking if nbFrames/maxFrames returned an int
        for i in range(0, int(nbFrames / maxFrames) + 1):
            filename = savePath + "/" + name + '%(number)04d.tif' % {
                "number": i + 1
            }  #%04d return a 4 char string : 1-->0001
            tif = tifffile.TiffWriter(
                filename)  #See tifffile.py for others param
            tifList.append(tif)
    else:
        for i in range(0, (nbFrames / maxFrames)):
            filename = savePath + "/" + name + '%(number)04d.tif' % {
                "number": i + 1
            }  #%04d return a 4 char string : 1-->0001
            tif = tifffile.TiffWriter(
                filename)  #See tifffile.py for others param
            tifList.append(tif)
    print len(tifList), ' Tif(s) initiated'

    #Inititate a .txt file where the metadata will be written
    textFile = open(savePath + "/" + name + ".txt", 'w')

    return (tifList, textFile)
Example #2
0
    def peakFinder(self, fit_peaks_image):
        """
        This method does the actual peak finding.
        """
        # Calculate background variance.
        #
        # Note the assumption here that we are working in units of photo-electrons
        # so Poisson statistics applies, variance = mean.
        #
        bg_var = self.background + fit_peaks_image
        
        # Add camera variance if set.
        if self.camera_variance is not None:
            bg_var += self.camera_variance

        # Calculate weighted variance if the image is being smoothed.
        if self.fg_vfilter is not None:
            bg_var = self.fg_vfilter.convolve(bg_var)

        if self.check_mode:
            with tifffile.TiffWriter("variances.tif") as tf:
                tf.save(bg_var.astype(numpy.float32))
            
        # Remove problematic values.
        #
        mask = (bg_var <= 0.1)
        if (numpy.sum(mask) > 0):
            if self.check_mode:
                print("Warning! small and/or negative values detected in background variance!")
            bg_var[mask] = 0.1
                
        # Convert to standard deviation.
        bg_std = numpy.sqrt(bg_var)

        # Calculate foreground.
        foreground = self.image - self.background - fit_peaks_image
        
        # Calculate smoothed image if we have a foreground filter.
        if self.fg_mfilter is not None:
            foreground = self.fg_mfilter.convolve(foreground)

        if self.check_mode:
            with tifffile.TiffWriter("foreground.tif") as tf:
                tf.save(foreground.astype(numpy.float32))
            
        # Calculate foreground in units of signal to noise.
        foreground = foreground/bg_std
        
        if self.check_mode:
            with tifffile.TiffWriter("fg_bg_ratio.tif") as tf:
                tf.save(foreground.astype(numpy.float32))
        
        # Mask the image so that peaks are only found in the AOI.
        masked_image = foreground * self.peak_mask

        # Identify local maxima in the masked image.
        [x, y, z] = self.mfinder.findMaxima([masked_image])
        return {"x" : x, "y" : y, "z" : z, "sigma" : numpy.ones(x.size)*self.sigma}
Example #3
0
def splitColorChannel(filesName, txtArray, tifsList, processedFolderPath):
    """
    Takes the metadat and a list of .tif path to create a folder with
    one channel tif and the time stamps corresponding
    """
    #Correction of the txtFile size
    #(Because the metadata and )

    #Separate infos from the .txt file
    time = txtArray[:, 0]
    channel = txtArray[:, 1]
    #frames = txtFile[:,2] #Useless
    odourValve = txtArray[:, 3]
    #respiration = txtFile[:,4] #useless
    #ledOnDuration =txtFile[:,5] #useless

    #Create or verify that processed folder exsits
    #    savePath = filesFolder+'/Processed'
    #    if not os.path.exists(savePath):
    #        os.makedirs(savePath)
    #Create a txt file
    redTextFile = open(processedFolderPath + "/" + filesName + "_R" + ".txt",
                       'w')
    greenTextFile = open(processedFolderPath + "/" + filesName + "_G" + ".txt",
                         'w')
    blueTextFile = open(processedFolderPath + "/" + filesName + "_B" + ".txt",
                        'w')
    print '.txt init'
    #Create a tiffWriter
    redTif = tifffile.TiffWriter(processedFolderPath + "/" + filesName + "_R" +
                                 ".tif",
                                 bigtiff=True)
    greenTif = tifffile.TiffWriter(processedFolderPath + "/" + filesName +
                                   "_G" + ".tif",
                                   bigtiff=True)
    blueTif = tifffile.TiffWriter(processedFolderPath + "/" + filesName +
                                  "_B" + ".tif",
                                  bigtiff=True)
    print '.itf init'

    splitTifs(redTif, tifsList, 0, channel)
    splitTifs(greenTif, tifsList, 1, channel)
    splitTifs(blueTif, tifsList, 2, channel)
    print 'split .tif done'

    splitTimestamps(redTextFile, time, odourValve, 0, channel)
    splitTimestamps(greenTextFile, time, odourValve, 1, channel)
    splitTimestamps(blueTextFile, time, odourValve, 2, channel)
    print 'split .txt done'

    redTextFile.close()
    greenTextFile.close()
    blueTextFile.close()

    redTif.close()
    greenTif.close()
    blueTif.close()
 def __init__(self, bigtiff=False, **kwds):
     super().__init__(**kwds)
     self.metadata = {'unit': 'um'}
     if bigtiff:
         self.resolution = (25400.0 / self.film_settings.getPixelSize(),
                            25400.0 / self.film_settings.getPixelSize())
         self.tif = tifffile.TiffWriter(self.filename, bigtiff=bigtiff)
     else:
         self.resolution = (1.0 / self.film_settings.getPixelSize(),
                            1.0 / self.film_settings.getPixelSize())
         self.tif = tifffile.TiffWriter(self.filename, imagej=True)
Example #5
0
 def saveImage(self, output_directory):
     tiff = tifffile.TiffWriter(output_directory + os.sep +
                                str(self.FILECOUNTER).zfill(2) + ".tif",
                                append=True)
     tiff.save(
         data=self.BGimg_1,  # np.ushort image data array from the camera
         compress=
         0,  # amount of compression (0-9), by default it is uncompressed (0)
         extratags=[
             (TAG_BITDEPTH, 'I', 1, self.camera.bit_depth,
              False),  # custom TIFF tag for bit depth
             (TAG_EXPOSURE, 'I', 1, self.camera.exposure_time_us, False)
         ]  # custom TIFF tag for exposure
     )
     tiff = tifffile.TiffWriter(output_directory + os.sep +
                                str(self.FILECOUNTER).zfill(2) + ".tif",
                                append=True)
     tiff.save(
         data=self.WVimg,  # np.ushort image data array from the camera
         compress=
         0,  # amount of compression (0-9), by default it is uncompressed (0)
         extratags=[
             (TAG_BITDEPTH, 'I', 1, self.camera.bit_depth,
              False),  # custom TIFF tag for bit depth
             (TAG_EXPOSURE, 'I', 1, self.camera.exposure_time_us, False)
         ]  # custom TIFF tag for exposure
     )
     tiff = tifffile.TiffWriter(output_directory + os.sep +
                                str(self.FILECOUNTER).zfill(2) + ".tif",
                                append=True)
     tiff.save(
         data=self.BGimg_2,  # np.ushort image data array from the camera
         compress=
         0,  # amount of compression (0-9), by default it is uncompressed (0)
         extratags=[
             (TAG_BITDEPTH, 'I', 1, self.camera.bit_depth,
              False),  # custom TIFF tag for bit depth
             (TAG_EXPOSURE, 'I', 1, self.camera.exposure_time_us, False)
         ]  # custom TIFF tag for exposure
     )
     tiff = tifffile.TiffWriter(output_directory + os.sep +
                                str(self.FILECOUNTER).zfill(2) + ".tif",
                                append=True)
     tiff.save(
         data=self.Diffimg,  # np.ushort image data array from the camera
         compress=
         0,  # amount of compression (0-9), by default it is uncompressed (0)
         extratags=[
             (TAG_BITDEPTH, 'I', 1, self.camera.bit_depth,
              False),  # custom TIFF tag for bit depth
             (TAG_EXPOSURE, 'I', 1, self.camera.exposure_time_us, False)
         ]  # custom TIFF tag for exposure
     )
     self.FILECOUNTER = self.FILECOUNTER + 1
Example #6
0
 def avgMapSaving(self, color, tiffWriter=None):
     """
     Process a folder
     """
     if color == 0:
         if tiffWriter is None:
             tiffWriter = tifffile.TiffWriter(self.resultSavePath +
                                              '/avgMaps_R.tif')
         tiffWriter.save(self.redOdMapAvg)
     elif color == 1:
         if tiffWriter is None:
             tiffWriter = tifffile.TiffWriter(self.resultSavePath +
                                              '/avgMaps_B.tif')
         tiffWriter.save(self.blueOdMapAvg)
     return tiffWriter
def generate_distanceto_binary(fns_binary,
                               out_file,
                               allinverted=False,
                               addinverted=False):
    """

    :param fn_stack:
    :param fn_label:
    :param outfolder:
    :param basename:
    :param scale:
    :param extend:
    :return:
    """

    imgs = list()

    with tifffile.TiffWriter(out_file, imagej=True) as outtif:
        for fn in fns_binary:
            with tifffile.TiffFile(fn) as tif:
                img = tif.asarray()
                if allinverted:
                    img = (img > 0) == False
                else:
                    img = img > 0
                outtif.save(
                    lib.distance_transform_wrapper(img).astype(np.float32))
                if addinverted:
                    outtif.save(
                        lib.distance_transform_wrapper(img == False).astype(
                            np.float32))

    return 1
Example #8
0
    def save(self, data, omexml=None, channel_names=None, image_name="IMAGE0", pixels_physical_size=None, channel_colors=None):
        """Save an image with the proper OME xml metadata.

        :param data: An array of dimensions TZCYX, ZCYX, or CYX to be written out to a file.
        :param channel_names: The names for each channel to be put into the OME metadata
        :param image_name: The name of the image to be put into the OME metadata
        :param pixels_physical_size: The physical size of each pixel in the image
        :param channel_colors: The channel colors to be put into the OME metadata
        """
        tif = tifffile.TiffWriter(self.file_path)

        shape = data.shape
        assert (len(shape) == 5 or len(shape) == 4 or len(shape) == 3)

        if omexml is None:
            self._make_meta(data, channel_names=channel_names, image_name=image_name,
                            pixels_physical_size=pixels_physical_size, channel_colors=channel_colors)
        else:
            pixels = omexml.image().Pixels
            pixels.populate_TiffData()
            self.omeMetadata = omexml
        xml = self.omeMetadata.to_xml()

        # check data shape for TZCYX or ZCYX or ZYX
        dims = len(shape)
        if dims == 5 or dims == 4 or dims == 3:
            # minisblack instructs TiffWriter to not try to infer rgb color within the data array
            # metadata param fixes the double image description bug
            tif.save(data, compress=9, description=xml, photometric='minisblack', metadata=None)

        tif.close()
Example #9
0
    def subtractBackground(self, image, fit_peaks_image, bg_estimate):
        """
        FIXME: This method has a really bad name as it only estimates the 
               background, it does not subtract it.

        Estimate the background for the image.
        
        image - The image to estimate the background of.
        fit_peaks_image - The current best fit image.
        bg_estimate - An estimate of the background.

        Returns the current background estimate.
        """        
        # If we are provided with an estimate of the background then just use it.
        if bg_estimate is not None:
            self.background = bg_estimate

        # Otherwise make our own estimate.
        else:
            image = image - fit_peaks_image
            self.background = self.backgroundEstimator(image)

        if self.check_mode:
            with tifffile.TiffWriter("bg_estimate.tif") as tf:
                tf.save(self.background.astype(numpy.float32))

        return self.background
Example #10
0
def save_as_hdr(arr, filename, gamma=2.2, allow_negative=True):
    """Saves a float32 ndarray to a high dynamic range (OpenEXR or float32 TIFF) file.

    Args:
        arr (ndarray): The input array.
        filename (str | Path): The output filename.
        gamma (Optional[float]): The encoding gamma of arr.
        allow_negative (Optional[bool]): Clip negative values to zero if false."""
    arr = arr.astype(np.float32)/255
    if not allow_negative:
        arr[arr < 0] = 0
    if gamma != 1:
        arr = np.sign(arr)*np.abs(arr)**gamma
    filename = str(filename)
    extension = filename.rpartition('.')[2].lower()
    if extension == 'exr':
        import OpenEXR
        exr = OpenEXR.OutputFile(filename, OpenEXR.Header(arr.shape[1], arr.shape[0]))
        exr.writePixels({'R': arr[..., 0].tobytes(),
                         'G': arr[..., 1].tobytes(),
                         'B': arr[..., 2].tobytes()})
        exr.close()
    elif extension == 'tif' or extension == 'tiff':
        import tifffile
        tiff = tifffile.TiffWriter(filename)
        tiff.save(arr, photometric='rgb')
        tiff.close()
    else:
        raise Exception('Unknown HDR file format.')
Example #11
0
def test_io_4():
    """
    Test TIF movie IO (1 page, multiple frames per page).
    """
    movie_h = 50
    movie_w = 40
    movie_l = 10

    data = numpy.random.randint(0, 60000, (movie_l, movie_h, movie_w)).astype(
        numpy.uint16)

    movie_name = storm_analysis.getPathOutputTest("test_dataio.tif")

    # Write tif movie.
    with tifffile.TiffWriter(movie_name, imagej=True) as tf:
        tf.save(data, truncate=True)

    # Read & check.
    rd = datareader.inferReader(movie_name)
    [mw, mh, ml] = rd.filmSize()

    assert (mh == movie_h)
    assert (mw == movie_w)
    assert (ml == movie_l)
    for i in range(movie_l):
        assert (numpy.allclose(data[i, :, :], rd.loadAFrame(i)))
Example #12
0
def test_otf_scaler_1():
    """
    Test that the C and the Python libraries agree on the calculation
    of an OTF scaled PSF.
    """
    otf_sigma = 1.8

    geo = pupilMath.Geometry(128, 0.1, 0.6, 1.5, 1.4)
    pf = geo.createFromZernike(1.0, [[1.3, 2, 2]])

    pf_c = pfFnC.PupilFunction(geometry=geo)
    pf_c.setPF(pf)

    otf_sc = otfSC.OTFScaler(size=geo.size)

    gsf = geo.gaussianScalingFactor(otf_sigma)
    psf_py = geo.pfToPSF(pf, [0.0], scaling_factor=gsf)

    psf_c = pf_c.getPSFIntensity()
    otf_sc.setScale(gsf)
    psf_c = otf_sc.scale(psf_c)

    if False:
        with tifffile.TiffWriter(
                storm_analysis.getPathOutputTest(
                    "test_otf_scaler_1.tif")) as tf:
            tf.save(psf_c.astype(numpy.float32))
            tf.save(psf_py.astype(numpy.float32))

    assert numpy.allclose(psf_c, psf_py)

    pf_c.cleanup()
    otf_sc.cleanup()
Example #13
0
    def startFilm(self, film_settings):
        # Open file to save the lock status at each frame.
        if self.working:
            if film_settings.isSaved():

                # Only save images when in diagnostics mode and only for a QPDCameraFunctionality.
                if self.diagnostics_mode and (self.qpd_functionality.getType()
                                              == "camera"):
                    self.tiff_counter = 0
                    self.tiff_fp = tifffile.TiffWriter(
                        film_settings.getBasename() + "_qpd.tif", bigtiff=True)

                self.offset_fp = open(film_settings.getBasename() + ".off",
                                      "w")

                headers = [
                    "frame", "offset", "power", "stage-z", "good-offset"
                ]
                if self.tiff_fp is not None:
                    headers.append("tif-counter")

                self.offset_fp.write(" ".join(headers) + "\n")

            # Check for a waveform from a hardware timed lock mode that uses the DAQ.
            waveform = self.lock_mode.getWaveform()
            if waveform is not None:
                self.controlMessage.emit(
                    halMessage.HalMessage(m_type="daq waveforms",
                                          data={"waveforms": [waveform]}))

            self.lock_mode.startFilm()
Example #14
0
    def save_animation(self, filename, verbose=False):
        self.run()
        if verbose:
            _tqdm = tqdm
        else:
            _tqdm = lambda x: x

        from ctypes import c_char_p, c_int, cdll
        lib = cdll.LoadLibrary("./Animation/animation.go.so")
        lib.createAnimation.argtypes = [c_char_p]

        temp_file = "_temp_animation_file.json"
        with open(temp_file, "w") as f:
            f.write(self.to_json())
        lib.createAnimation(temp_file.encode())
        os.remove(temp_file)

        max_norm = maximum_value(range(self.number_of_frames))
        MAX_INT16 = np.int16((2**15 - 1))
        converter = np.int16(MAX_INT16 / max_norm)
        constant = np.int16(0)

        with tifffile.TiffWriter(filename, imagej=True) as stack:
            for idx in _tqdm(range(self.number_of_frames)):
                image_filename = "{}.json".format(idx)
                with open(image_filename) as f:
                    frame = json.loads(f.read())
                os.remove(image_filename)
                stack.save(
                    np.array(constant +
                             self._add_noise_to_frame(frame) * converter,
                             dtype=np.int16))
Example #15
0
def test_pupilfn_3():
    """
    Test PF X derivative (C library).
    """
    dx = 1.0e-6
    geo = pupilMath.Geometry(20, 0.1, 0.6, 1.5, 1.4)
    pf = geo.createFromZernike(1.0, [[1.3, 2, 2]])

    pf_c = pfFnC.PupilFunction(geometry=geo)
    pf_c.setPF(pf)

    # Calculate derivative of magnitude as a function of x.
    psf_c = pf_c.getPSF()
    psf_c_dx = pf_c.getPSFdx()
    mag_dx_calc = 2.0 * (numpy.real(psf_c) * numpy.real(psf_c_dx) +
                         numpy.imag(psf_c) * numpy.imag(psf_c_dx))

    # Estimate derivative using (f(x+dx) - f(x))/dx
    mag = pupilMath.intensity(psf_c)
    pf_c.translate(dx, 0.0, 0.0)
    mag_dx_est = (pupilMath.intensity(pf_c.getPSF()) - mag) / dx

    if False:
        with tifffile.TiffWriter(
                storm_analysis.getPathOutputTest("test_pupilfn_3.tif")) as tf:
            #tf.save(mag.astype(numpy.float32))
            tf.save(mag_dx_calc.astype(numpy.float32))
            tf.save(mag_dx_est.astype(numpy.float32))
            tf.save(numpy.abs(mag_dx_calc - mag_dx_est).astype(numpy.float32))

    assert numpy.allclose(mag_dx_calc, mag_dx_est, atol=1.0e-6)

    pf_c.cleanup()
Example #16
0
def test_pupilfn_2():
    """
    Test PF translation.
    """
    dx = 0.5
    dy = 0.25
    dz = 0.2
    geo = pupilMath.Geometry(20, 0.1, 0.6, 1.5, 1.4)
    pf = geo.createFromZernike(1.0, [[1.3, 2, 2]])

    pf_c = pfFnC.PupilFunction(geometry=geo)
    pf_c.setPF(pf)

    pf_c.translate(dx, dy, dz)
    psf_c = pupilMath.intensity(pf_c.getPSF())

    defocused = geo.changeFocus(pf, dz)
    translated = geo.translatePf(defocused, dx, dy)
    psf_py = pupilMath.intensity(pupilMath.toRealSpace(translated))

    if False:
        with tifffile.TiffWriter(
                storm_analysis.getPathOutputTest("test_pupilfn_2.tif")) as tf:
            tf.save(psf_c.astype(numpy.float32))
            tf.save(psf_py.astype(numpy.float32))

    assert numpy.allclose(psf_c, psf_py)

    pf_c.cleanup()
Example #17
0
def test_pupilfn_7():
    """
    Test that PF translation is correct (i.e. independent of size).
    """
    sizes = [10, 20, 40]
    dx = 1.0

    for size in sizes:
        geo = pupilMath.Geometry(size, 0.1, 0.6, 1.5, 1.4)
        pf = geo.createFromZernike(1.0, [[1.3, 2, 2]])

        pf_c = pfFnC.PupilFunction(geometry=geo)
        pf_c.setPF(pf)

        psf_untranslated = numpy.roll(pupilMath.intensity(pf_c.getPSF()),
                                      1,
                                      axis=0)

        pf_c.translate(dx, 0.0, 0.0)
        psf_translated = pupilMath.intensity(pf_c.getPSF())

        if False:
            with tifffile.TiffWriter(
                    storm_analysis.getPathOutputTest(
                        "test_pupilfn_7.tif")) as tf:
                tf.save(psf_untranslated.astype(numpy.float32))
                tf.save(psf_translated.astype(numpy.float32))

        assert numpy.allclose(psf_untranslated, psf_translated)

        pf_c.cleanup()
Example #18
0
def test_pupilfn_4():
    """
    Test PF X derivative (Python library).
    """
    dx = 1.0e-6
    geo = pupilMath.Geometry(20, 0.1, 0.6, 1.5, 1.4)
    pf = geo.createFromZernike(1.0, [[1.3, 2, 2]])

    # Calculate derivative of magnitude as a function of x.
    psf_py = pupilMath.toRealSpace(pf)
    psf_py_dx = pupilMath.toRealSpace(geo.dx(pf))
    mag_dx_calc = 2.0 * (numpy.real(psf_py) * numpy.real(psf_py_dx) +
                         numpy.imag(psf_py) * numpy.imag(psf_py_dx))

    # Estimate derivative using (f(x+dx) - f(x))/dx
    mag = pupilMath.intensity(psf_py)
    translated = geo.translatePf(pf, dx, 0.0)
    mag_dx_est = (pupilMath.intensity(pupilMath.toRealSpace(translated)) -
                  mag) / dx

    if False:
        with tifffile.TiffWriter(
                storm_analysis.getPathOutputTest("test_pupilfn_4.tif")) as tf:
            #tf.save(mag.astype(numpy.float32))
            tf.save(mag_dx_calc.astype(numpy.float32))
            tf.save(mag_dx_est.astype(numpy.float32))
            tf.save(numpy.abs(mag_dx_calc - mag_dx_est).astype(numpy.float32))

    assert numpy.allclose(mag_dx_calc, mag_dx_est, atol=1.0e-6)
Example #19
0
File: io.py Project: rhacking/dST
def save_tiff_chunks(vol: Volume,
                     path: str,
                     size: int,
                     stride: int,
                     b_8bit: bool = False):
    import shutil
    import pathlib

    if os.path.isdir(path):
        shutil.rmtree(path)

    pathlib.Path(path).mkdir(parents=True)

    i = 0
    for x in range(0, vol.shape[0] - size + 1, stride):
        for y in range(0, vol.shape[1] - size + 1, stride):
            for z in range(0, vol.shape[2] - size + 1, stride):
                data = vol[x:x + size, y:y + size, z:z + size]
                chunk_path = os.path.join(path, f'{i}.tif')

                with tifffile.TiffWriter(chunk_path, bigtiff=False) as f:
                    f.save(np.moveaxis(data if not b_8bit else data / 2**8,
                                       [2, 0, 1], [0, 1, 2]),
                           resolution=(np.round(1 / (data.spacing[0] / 10000),
                                                decimals=5),
                                       np.round(1 / (data.spacing[1] / 10000),
                                                decimals=5), 'CENTIMETER'))

                i += 1
def generate_distanceto_spheres(fn_label, cur_label, out_file, bg_label=0):
    """

    :param fn_stack:
    :param fn_label:
    :param outfolder:
    :param basename:
    :param scale:
    :param extend:
    :return:
    """

    with tifffile.TiffFile(fn_label) as tif:
        labels = tif.asarray()

    is_cur = (labels != cur_label)
    is_bg = (labels != bg_label)
    is_other = (is_bg == False) | (is_cur == False)

    with tifffile.TiffWriter(out_file + '.tif', imagej=True) as tif:
        tif.save(lib.distance_transform_wrapper(is_cur).astype(np.float32))
        tif.save(lib.distance_transform_wrapper(is_bg).astype(np.float32))
        tif.save(lib.distance_transform_wrapper(is_other).astype(np.float32))

    return 1
def write_two_planes(filepaths: List[str], outpath: str, z_level: float,
                     x_min: int, x_max: int, y_min: int, y_max: int,
                     scale_x: float, scale_y: float, flip_x: bool,
                     flip_y: bool):
    """Writes out a cropped, scaled, and flipped TIFF file interpolated between two TIFFs
    Order of operations: cropping, scaling, flipping

    Parameters
    ----------
    filepaths : List[str]
        List of file paths of original two TIFFs
    outpath : str
        File path to output TIFF
    z_level : float
        Float between 0 and 1 describing interpolation position between two planes, 0 being close to bottom
    x_min : int
        Minimum x-coordinate to keep in the output TIFF file
    x_max : int
        Maximum x-coordinate to keep in the output TIFF file
    y_min : int
        Minimum y-coordinate to keep in the output TIFF file
    y_max : int
        Maximum y-coordinate to keep in the output TIFF file
    scale_x : float
        Scaling factor in the x-dimension
    scale_y : float
        Scaling factor in the y-dimension
    flip_x : bool
        True if the output image should be reflected about the y axis (reversing the image along the x-dimension)
    flip_y : bool
        True if the output image should be reflected about the x axis (reversing the image along the y-dimension)

    Returns
    -------
    None
    """
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        p1 = img_as_uint(
            zoom(
                tifffile.imread(filepaths[0])[y_min - 1:y_max,
                                              x_min - 1:x_max],
                (scale_y, scale_x)))
        p2 = img_as_uint(
            zoom(
                tifffile.imread(filepaths[1])[y_min - 1:y_max,
                                              x_min - 1:x_max],
                (scale_y, scale_x)))

    # Uses linear spline to interpolate between two planes
    p_comb = ((1 - z_level) * p1) + (z_level * p2)
    p_comb = img_as_uint(np.around(p_comb).astype(np.uint16))

    if flip_x:
        p_comb = np.flip(p_comb, 1)
    if flip_y:
        p_comb = np.flip(p_comb, 0)

    with tifffile.TiffWriter(outpath) as file:
        file.save(p_comb)
Example #22
0
def generate_distanceto_spheres(fn_label, cur_label, out_file, bg_label=0):
    """

    :param fn_stack:
    :param fn_label:
    :param outfolder:
    :param basename:
    :param scale:
    :param extend:
    :return:
    """
    warnings.warn(
        '''generate_distanceto_spheres is deprecated and
                  will not be supported in future versions.
                  Please use the `MaskToBinstack` together with
                  `Transform Binary`
                  module from Bodenmillergroup/ImcPluginsCP
                  in CellProfiler!''', DeprecationWarning)

    with tifffile.TiffFile(fn_label) as tif:
        labels = tif.asarray()

    is_cur = (labels != cur_label)
    is_bg = (labels != bg_label)
    is_other = (is_bg == False) | (is_cur == False)

    with tifffile.TiffWriter(out_file + '.tif', imagej=True) as tif:
        tif.save(lib.distance_transform_wrapper(is_cur).astype(np.float32))
        tif.save(lib.distance_transform_wrapper(is_bg).astype(np.float32))
        tif.save(lib.distance_transform_wrapper(is_other).astype(np.float32))

    return 1
Example #23
0
def test_tiff_imread(tmpdir, seed, nframes, shape, runtime_warning, dtype,
                     is_pathlib_Path):
    np.random.seed(seed)

    dirpth = tmpdir.mkdir("test_imread")
    dtype = np.dtype(dtype).type

    low, high = 0.0, 1.0
    if isinstance(dtype, numbers.Integral):
        low, high = np.iinfo(dtype).min, np.iinfo(dtype).max

    a = np.random.uniform(low=low, high=high, size=shape).astype(dtype)

    fn = str(dirpth.join("test.tiff"))
    with tifffile.TiffWriter(fn) as fh:
        for i in range(len(a)):
            fh.save(a[i], contiguous=True)

    with pytest.warns(None if runtime_warning is None else RuntimeWarning,
                      match=runtime_warning):
        if is_pathlib_Path:
            fn = pathlib.Path(fn)
        d = dask_image.imread.imread(fn, nframes=nframes)

    if nframes == -1:
        nframes = shape[0]

    assert min(nframes, shape[0]) == max(d.chunks[0])

    if shape[0] % nframes == 0:
        assert nframes == d.chunks[0][-1]
    else:
        assert (shape[0] % nframes) == d.chunks[0][-1]

    dau.assert_eq(a, d)
Example #24
0
def _writesetup(outfn:Path, Nimg:int, img:np.ndarray):
    if not outfn:
        return

    outfn = Path(outfn).expanduser()

    # note: these file types must be .close() when done!
    if outfn.suffix == '.nc':
        f=outfn
    elif outfn.suffix == '.h5':
        import h5py
        f = h5py.File(outfn,'w',libver='earliest')
        f.create_dataset(KEY,
                         shape=(Nimg,img.shape[0],img.shape[1]),
                         maxshape=(None,img.shape[0],img.shape[1]),
                         dtype=img.dtype,
                         compression='gzip',
                         compression_opts=CLVL,
                         chunks=True)
    elif outfn.suffix in ('.tif','.tiff'):
        import tifffile
        f = tifffile.TiffWriter(str(outfn)) # NO append/compress keywords
    else:
        raise ValueError('unknown file type {}'.format(outfn))

    print('writing',outfn)

    return f
Example #25
0
def test_tiff_imread(tmpdir, seed, nframes, shape, dtype):
    np.random.seed(seed)

    dirpth = tmpdir.mkdir("test_imread")
    dtype = np.dtype(dtype).type

    low, high = 0.0, 1.0
    if isinstance(dtype, numbers.Integral):
        low, high = np.iinfo(dtype).min, np.iinfo(dtype).max

    a = np.random.uniform(low=low, high=high, size=shape).astype(dtype)

    fn = str(dirpth.join("test.tiff"))
    with tifffile.TiffWriter(fn) as fh:
        for i in range(len(a)):
            fh.save(a[i])

    d = dask_image.imread.imread(fn, nframes=nframes)

    if nframes == -1:
        nframes = shape[0]

    assert min(nframes, shape[0]) == max(d.chunks[0])

    if shape[0] % nframes == 0:
        assert nframes == d.chunks[0][-1]
    else:
        assert (shape[0] % nframes) == d.chunks[0][-1]

    dau.assert_eq(a, d)
def test_mfit_9():
    """
    Test peak significance calculation.
    """
    height = 10.0
    sigma = 1.5
    x_size = 100
    y_size = 120
    background = numpy.zeros((x_size, y_size)) + 10.0
    image = dg.drawGaussians((x_size, y_size),
                             numpy.array([[50.0, 30.0, height, sigma, sigma],
                                          [50.0, 50.0, 2.0*height, sigma, sigma],
                                          [50.0, 70.0, 3.0*height, sigma, sigma]]))
    image += background

    mfit = daoFitC.MultiFitter2D(sigma_range = [1.0, 2.0])
    mfit.initializeC(image)
    mfit.newImage(image)
    mfit.newBackground(background)

    peaks = {"x" : numpy.array([30.0, 50.0, 70.0]),
             "y" : numpy.array([50.0, 50.0, 50.0]),
             "z" : numpy.array([0.0, 0.0, 0.0]),
             "sigma" : numpy.array([sigma, sigma, sigma])}

    mfit.newPeaks(peaks, "finder")

    if False:
        with tifffile.TiffWriter("test_mfit_9.tif") as tf:
            tf.save(image.astype(numpy.float32))
    
    sig = mfit.getPeakProperty("significance")
    sig = sig/sig[0]
    assert(numpy.allclose(sig, numpy.arange(1,4)))
Example #27
0
def generate_binary(fn_label, cur_label, out_file, bg_label=0):
    """

    :param fn_stack:
    :param fn_label:
    :param outfolder:
    :param basename:
    :param scale:
    :param extend:
    :return:
    """

    with tifffile.TiffFile(fn_label) as tif:
        labels = tif.asarray()

    is_cur = labels == cur_label
    is_bg = labels == bg_label
    is_other = (is_bg == False) & (is_cur == False)

    with tifffile.TiffWriter(out_file + '.tif', imagej=True) as tif:
        tif.save(is_cur.astype(np.uint8))
        tif.save(is_bg.astype(np.uint8))
        tif.save(is_other.astype(np.uint8))

    return 1
    def save_stack(self, filePath, stack, pos):
        super().save_stack(filePath, stack, pos)

        with tifffile.TiffWriter(filePath + ".tif") as tf:
            for elt in stack:
                tmp = np.clip(elt, 0, 2**16 - 1)
                tf.save(elt.astype(np.uint16).transpose())
Example #29
0
def _writesetup(outfn: Path, Nimg: int, img: np.ndarray):
    if not outfn:
        return

    outfn = Path(outfn).expanduser()

    # note: these file types must be .close() when done!
    if outfn.suffix == ".nc":
        f = outfn
    elif outfn.suffix == ".h5":
        import h5py

        f = h5py.File(outfn, "w", libver="earliest")
        f.create_dataset(
            KEY,
            shape=(Nimg, img.shape[0], img.shape[1]),
            maxshape=(None, img.shape[0], img.shape[1]),
            dtype=img.dtype,
            compression="gzip",
            compression_opts=CLVL,
            chunks=True,
        )
    elif outfn.suffix in (".tif", ".tiff"):
        import tifffile

        f = tifffile.TiffWriter(str(outfn))  # NO append/compress keywords
    else:
        raise ValueError("unknown file type {}".format(outfn))

    print("writing", outfn)

    return f
def manual_save(tiff_file, image, data_type=None, metadata=None):
    tiff_path = Path(tiff_file)
    image = np.asarray(image)
    image = _cast_to_dtype(image, data_type)
    if metadata is not None:
        meta_img = metadata.image()
        meta_img.Pixels.set_PixelType(str(image.dtype))
        meta_img.set_Name(tiff_path.stem)
        metadata = metadata.to_xml().encode()

    tiff_dir = tiff_path.resolve().parent
    tiff_dir.mkdir(parents=True, exist_ok=True)
    num_frames = len(image)
    bigtiff = image.size * image.itemsize >= np.iinfo(
        np.uint32).max  # Check if data bigger than 4GB TIFF limit

    logging.info("Saving image as %s with %i frames", tiff_path.name,
                 num_frames)

    with tf.TiffWriter(str(tiff_path), bigtiff=bigtiff, ome=False) as tif:
        tif.write(image,
                  photometric='MINISBLACK',
                  description=metadata,
                  metadata={'axes': 'ZYX'},
                  software=f"txrm2tiff {__version__}")