Exemplo n.º 1
0
def save_random_chunks(xs, ys, labs, out_dir):
    '''
    Save the random chunks as they are sampled
    '''
    os.makedirs(out_dir, exist_ok=True)
    assert len(xs) == len(ys)
    ids = []
    # iterate over the sample
    for i in range(len(xs)):
        # get the datetime to give the samples unique names
        now = datetime.now()
        d = now.strftime("%y%m%d_%H%M%S") + '_' + str(i)
        ids.append(d)
        # save the image
        i_name = d + '_image.tif'
        i_path = os.path.join(out_dir, i_name)
        with TiffWriter(i_path) as tiff:
            tiff.write(xs[i].numpy())
        # save the labels
        l_name = d + '_labels.tif'
        l_path = os.path.join(out_dir, l_name)
        with TiffWriter(l_path) as tiff:
            tiff.write(ys[i].numpy())
        # save the ground truth segmentation
        s_name = d + '_GT.tif'
        s_path = os.path.join(out_dir, s_name)
        with TiffWriter(s_path) as tiff:
            tiff.write(labs[i])  # this is already ndarray not tensor
    assert len(ids) == len(ys)
    print('------------------------------------------------------------')
    print('Training data saved at:')
    print(out_dir)
    return ids
def main():
    global dirName, dishId, subStart
    parsecmd(desc)
    if dishId:
        print("Work directory: %s/%s" % (dirName, dishId))
        platesfile = "%s/%s/plates-%s.tif" % (dirName, dishId, dishId)
        plates = loadTiff(platesfile)
        mask, report = procPlateSet(plates,
                                    gsigma=gsigma,
                                    mergelevel=mergelevel)
        with TiffWriter("%s/%s/seeds-%s.tif" %
                        (dirName, dishId, dishId)) as tif:
            tif.save(img3mask(plates[0], mask), compress=5)
        with TiffWriter("%s/%s/seeds-mask-%s.tif" %
                        (dirName, dishId, dishId)) as tif:
            tif.save(img3mask(plates[0] + 1, 1 - mask), compress=5)
    else:
        for p in range(subStart, 200):
            dishId = "%03d" % p
            fnames = glob.glob("%s/%s" % (dirName, dishId))
            if fnames == []: continue  # no such plant
            fnames = glob.glob("%s/%s/seeds-%s.tif" %
                               (dirName, dishId, dishId))
            print("Work directory: %s/%s" % (dirName, dishId))
            platesfile = "%s/%s/plates-%s.tif" % (dirName, dishId, dishId)
            plates = loadTiff(platesfile)
            mask, report = procPlateSet(plates,
                                        gsigma=gsigma,
                                        mergelevel=mergelevel)
            with TiffWriter("%s/%s/seeds-%s.tif" %
                            (dirName, dishId, dishId)) as tif:
                tif.save(img3mask(plates[0], mask), compress=5)
            with TiffWriter("%s/%s/seeds-mask-%s.tif" %
                            (dirName, dishId, dishId)) as tif:
                tif.save(img3mask(plates[0] + 1, 1 - mask), compress=5)
def tiff_to_bigtiff(tiff32_name,
                    header_size=8,
                    page_size=655654,
                    page_resolution=(640, 512),
                    page_mode='I;16'):
    """ 
    Convert 32 bit multipage tiff file to 64 bit multipage big tiff file.
    This is not a general tool! It was made to convert tiff files from a specific source. See assumptions.  
    
    Args:
        tiff32_name (str):          The name of the tiff file to be converted if in this directory, or the path to the file.
        header_size (int):          The header size in bytes of the tiff file to be converted.
        page_size (int):            The constant size in bytes of each page in the tiff file to be converted.
        page_resolution (tuple):    The constant resolution of each page in the tiff file to be converted.
        page_mode (str):            The color mode of each page in the tiff file to be converted (default is 16 bit grayscale).

    Assumptions:
        1. Image data in the tiff file to be converted is uncompressed and of constant resolution because there must be a 
            constant number of bytes between each page.
        2. Tiff file is of .tif or .tiff file extension.
        3. Tiff image data is 16 bit grayscale. This script has not been tested with RGB images so performance on RGB images is unknown.
        4. All arguments are given properly and in the correct order. Some prior analysis of the tiff file may be necessary.
    """

    if tiff32_name[-4:] == '.tif':
        extension = '.tif'
    elif tiff32_name[-5:] == '.tiff':
        extension = '.tiff'
    else:
        raise ValueError('File to convert must be a .tif or .tiff file')

    with open(tiff32_name,
              'rb') as tiff32, TiffWriter(tiff32_name[:-len(extension)] +
                                          'x64.tiff',
                                          bigtiff=True) as tiff64:

        tiff32.seek(0, 2)
        end_of_file = tiff32.tell()

        # Skip header
        tiff32.seek(header_size)

        i = 0
        while tiff32.tell() < end_of_file:
            # Construct and validate each frame
            img_data = tiff32.read(page_size)
            img = Image.frombytes(mode=page_mode,
                                  size=page_resolution,
                                  data=img_data,
                                  decoder_name='raw')
            tiff64.save(np.asarray(img))

            i += 1
            if i % 200 == 0:
                sys.stdout.write(
                    f'\rConverting {file_to_convert} to 64 bit... {tiff32.tell()/end_of_file*100 :.2f}%'
                )
                sys.stdout.flush()

        print('\nFinished conversion\n')
Exemplo n.º 4
0
def convert_slide_tiff(infilename, outfilename, ome=False, overwrite=False):
    if overwrite or not os.path.exists(outfilename):
        print(f'{infilename} -> {outfilename}')
        try:
            tiff = TiffFile(infilename)
            outpath = os.path.dirname(outfilename)
            if not os.path.exists(outpath):
                os.makedirs(outpath)
            with TiffWriter(outfilename, ome=ome, bigtiff=True) as writer:
                for page in tiff.pages:
                    if page.is_tiled:
                        tile_size = (page.tilelength, page.tilewidth)
                        if ome:
                            if page.is_ome:
                                metadata = tifffile.xml2dict(tiff.ome_metadata)
                            else:
                                metadata = tags_to_dict(
                                    page.tags)  # create pseudo OME metadata
                            description = None
                        else:
                            metadata = None
                            description = page.description
                        writer.write(page.asarray(),
                                     tile=tile_size,
                                     compression=['JPEG2000', 10],
                                     metadata=metadata,
                                     description=description)
        except Exception as e:
            print('file:', infilename, e)
Exemplo n.º 5
0
def save_tiff(filename, image, tile_size, compression, metadata):
    with TiffWriter(filename, bigtiff=True, ome=True) as writer:
        writer.write(image,
                     photometric='RGB',
                     tile=tile_size,
                     compression=compression,
                     metadata=metadata)
Exemplo n.º 6
0
def disk_im_gry_pyr(tmpdir_factory):
    out_im = tmpdir_factory.mktemp("image").join("image_fp_gry_pyr.tiff")
    subifds = 2
    full_im = np.random.randint(0, 255, (2048, 2048), dtype=np.uint16)
    with TiffWriter(out_im) as tif:
        options = dict(
            tile=(256, 256),
            compression="deflate",
            photometric="minisblack",
            metadata=None,
        )
        tif.write(
            full_im,
            subifds=subifds,
            **options,
        )

        for pyr_idx in range(subifds):
            if pyr_idx == 0:
                subresimage = full_im[::2, ::2]
            else:
                subresimage = subresimage[::2, ::2]

            tif.write(subresimage, **options, subfiletype=1)
    return out_im
Exemplo n.º 7
0
def test_commandline(tmpdir, runner):
    input = tmpdir / 'in.tif'
    output = tmpdir / 'out.tif'

    data = np.array([
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1, 0, 0, 1, 1, 0],
        [1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
        [1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
        [0, 1, 1, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 1, 1, 1, 0],
        [0, 0, 0, 0, 0, 0, 1, 1, 1, 0],
        [0, 0, 0, 0, 0, 0, 1, 1, 1, 0],
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    ],
                    dtype='uint32')
    TiffWriter(str(input)).save(data * 5)

    result = runner.invoke(main, ["segment", "run"] +
                           list(map(str, [input, output, '--threshold', 2])))
    assert result.exit_code == 0

    r = TiffFile(str(output)).asarray()
    assert r[2, 8] == 0
    assert r[1, 2] > 0
    assert r[8, 8] > 0
    assert r[1, 2] != r[8, 8]
Exemplo n.º 8
0
def iterate_over_stream(stream: pa.RecordBatchStreamReader,
                        data_shape: Tuple[int, int, int],
                        new_fname: pathlib.Path, channels: List[int]):
    """Iterate over the Arrow stream, producing one frame of rendered data
    on each step per channel."""
    with TiffWriter(str(new_fname), bigtiff=True) as tif:
        # Iterate over the Batches in the Arrow stream
        for batch in stream:
            mask_per_channel = _get_row_mask_per_channel(batch[0], channels)
            channel_data = []
            for mask in mask_per_channel:
                coords, data = create_coords_list(batch, mask)
                channel_data.append(
                    sparse.COO(coords,
                               data,
                               data_shape,
                               has_duplicates=False,
                               sorted=False))
            assert len(channel_data) == len(channels)
            for channel_datum in channel_data:
                # Do something with the single channel data. We can also make it a
                # standard array:
                # channel_datum.todense()  # numpy array with the original shape
                # Although many operations are available on the sparse representation
                # of the data, like summing, averaging and so on.
                # Here we write it to disk in an interleaved manner:
                data = channel_datum.todense().squeeze()
                tif.write(data, contiguous=True)
Exemplo n.º 9
0
    def __enter__(self):
        if self.write:
            self.tif = TiffWriter(self.filename, bigtiff=True, append=True)
        if self.read:
            self.tif = TiffFile(self.filename)
            self.array = self.tif.asarray()  # memmap=True)

        return self
Exemplo n.º 10
0
def _save_output(y_hats, ids, out_dir, suffix=''):
    assert len(y_hats) == len(ids)
    os.makedirs(out_dir, exist_ok=True)
    for i in range(len(y_hats)):
        n = ids[i] + suffix + '_output.tif'
        p = os.path.join(out_dir, n)
        with TiffWriter(p) as tiff:
            tiff.write(y_hats[i].detach().cpu().numpy())
Exemplo n.º 11
0
def getDensityImg(saveDir, saveName, points, shape, order):
    img = getVoxelCounts(points, shape, order)
    img = np.round(img * 1000000 / (16 * 16 * 16))
    img = img.astype(np.uint16)
    savePath = os.path.join(saveDir, saveName)
    with TiffWriter(savePath) as tiff:
        tiff.save(img)
    return img
Exemplo n.º 12
0
    def event_page(self, doc):
        '''Add event page document information to a ".tiff" file.

        This method adds event_page document information to a ".tiff" file,
        creating it if nesecary.

        .. warning::

            All non 2D 'image like' data is explicitly ignored.

        .. note::

            The data in Events might be structured as an Event, an EventPage,
            or a "bulk event" (deprecated). The DocumentRouter base class takes
            care of first transforming the other representations into an
            EventPage and then routing them through here, so no further action
            is required in this class. We can assume we will always receive an
            EventPage.

        Parameters:
        -----------
        doc : dict
            EventPage document
        '''
        event_model.verify_filled(doc)
        descriptor = self._descriptors[doc['descriptor']]
        stream_name = descriptor.get('name')
        for field in doc['data']:
            for img in doc['data'][field]:
                # Check that the data is 2D or 3D; if not ignore it.
                data_key = descriptor['data_keys'][field]
                ndim = len(data_key['shape'] or [])
                if data_key['dtype'] == 'array' and 1 < ndim < 4:
                    # there is data to be written so
                    # create a file for this stream and field
                    # if one does not exist yet
                    if not self._tiff_writers.get(stream_name, {}).get(field):
                        filename = get_prefixed_filename(
                            file_prefix=self._file_prefix,
                            start_doc=self._start,
                            stream_name=stream_name,
                            field=field)
                        file = self._manager.open('stream_data', filename,
                                                  'xb')
                        tw = TiffWriter(file, **self._init_kwargs)
                        self._tiff_writers[stream_name][field] = tw

                    # write the data
                    img_asarray = numpy.asarray(img, dtype=self._astype)
                    if ndim == 2:
                        # handle 2D data just like 3D data
                        # by adding a 3rd dimension
                        img_asarray = numpy.expand_dims(img_asarray, axis=0)
                    for i in range(img_asarray.shape[0]):
                        img_asarray_2d = img_asarray[i, :]
                        # append the image to the file
                        tw = self._tiff_writers[stream_name][field]
                        tw.save(img_asarray_2d, *self._kwargs)
Exemplo n.º 13
0
def calc_image_and_save(img_sum: np.ndarray, img_num: int, dk_img: tp.Union[None, np.ndarray],
                        tiff_path: tp.Union[str, Path]) -> None:
    """Average the image, subtract the dark image and export the image in a tiff file."""
    avg_img = img_sum / img_num
    if dk_img is not None:
        avg_img = avg_img - dk_img
    tw = TiffWriter(tiff_path)
    tw.write(avg_img)
    return
Exemplo n.º 14
0
def write_tiff_volume(imagedir: pathlib.Path,
                      imagefile: pathlib.Path,
                      space_scale: float = 1.0,
                      time_scale: float = 1.0):
    """ Write a directory of tiff files out to a volume

    :param Path imagedir:
        The directory to process
    :param Path imagefile:
        The path to write the tiff volume to
    :param float space_scale:
        The width of a single pixel (in um)
    :param float time_scale:
        The number of minutes between frames
    :param float cmin:
        The minimum grey value for the input volume
    :param float cmax:
        The maximum grey value for the input volume
    """
    # Write out the 3D tiff, using compression to reduce the file size
    imagefile.parent.mkdir(parents=True, exist_ok=True)

    # Save metadata on each frame
    options = {
        'resolution': (1.0 / space_scale, 1.0 / space_scale),
        'metadata': {
            'frame interval': time_scale,
            'unit': 'um',
            'axes': 'TYX',
        },
    }
    input_pct_low = []
    input_pct_high = []
    with TiffWriter(imagefile, bigtiff=True, byteorder='<') as tif:
        # Read all the files in, in order
        for p in sorted(imagedir.iterdir()):
            if p.name.startswith('.'):
                continue
            if not p.is_file():
                continue
            if p.suffix not in IMAGE_SUFFIXES:
                continue
            print(f'Loading {p}')

            # Load and clip it to range
            img = load_image(p, ctype='gray').astype(np.uint16)
            pct_low, pct_high = np.percentile(img, [2, 98])
            input_pct_low.append(pct_low)
            input_pct_high.append(pct_high)

            # Convert the image to 8-bit
            tif.write(img, contiguous=True, dtype=np.uint16, **options)
    print(f'Wrote {imagefile}')

    print(f'Low/High: {np.min(input_pct_low)} {np.max(input_pct_high)}')
    print(f'Time scale:  {time_scale:0.2f} min/frame')
    print(f'Space scale: {space_scale:0.2f} um/pixel')
def plot_image(data, **kwargs):
    p = functools.partial(plt.imshow, cmap='gray', clim=(0, 500))  # noqa
    p(data, **kwargs)
    from tifffile import TiffWriter
    
    ##File saving needs to be done properly via suite-case
    with open('/nsls2/xf07bm/data/pe1_data/2019/05/23/Diffraction_Image.tiff', 'xb') as f:
        tw = TiffWriter(f)
        tw.save(data)
def saveAll(outDirName, dishId, plates, reportLog):
    #report = configparser.ConfigParser()
    #report["platealign.py"] = reportLog
    #with open("%s/%s/result.txt"%(outDirName, dishId), 'w') as reportfile: report.write(reportfile)
    with TiffWriter("%s/%s/plates-%s.tif" %
                    (outDirName, dishId, dishId)) as tif:
        tif.save(plates)
    imageio.imwrite("%s/%s/plates-%s.png" % (outDirName, dishId, dishId),
                    plates.max(axis=0)[::4, ::4, :])
Exemplo n.º 17
0
def test_create_project_dropped_tiff(client):
    tifffile = io.BytesIO()
    with TiffWriter(tifffile) as writer:
        writer.save(np.zeros((1, 1, 1, 1)))
        tifffile.seek(0)
    data = {'file': (tifffile, 'test.tiff')}
    response = client.post('/api/project/dropped',
                           data=data,
                           content_type='multipart/form-data')
    assert response.status_code == 200
Exemplo n.º 18
0
def writeSubsTiff(filedir, filename, data, subsection):
    x_st = subsection.pop('x_start')
    x_en = subsection.pop('x_end')
    y_st = subsection.pop('y_start')
    y_en = subsection.pop('x_end')
    img = data[:, y_st:y_en, x_st:x_en]
    filepath = os.path.join(filedir, filename)
    with TiffWriter(filepath, bigtiff=True) as tiff:
        for i in range(img.shape[0]):
            tiff.save(img[i, :, :])
    return img
Exemplo n.º 19
0
    def event(self, doc):
        '''Add event document information to a ".tiff" file.

        This method adds event document information to a ".tiff" file,
        creating it if necessary.

        .. warning::

            All non 2D 'image-like' data is explicitly ignored.

        .. note::

            The data in Events might be structured as an Event, an EventPage,
            or a "bulk event" (deprecated). The DocumentRouter base class takes
            care of first transforming the other representations into an
            EventPage and then routing them through here, as we require Event
            documents _in this case_ we overwrite both the `event` method and
            the `event_page` method so we can assume we will always receive an
            Event.

        Parameters:
        -----------
        doc : dict
            Event document
        '''
        event_model.verify_filled(event_model.pack_event_page(*[doc]))
        descriptor = self._descriptors[doc['descriptor']]
        stream_name = descriptor.get('name')
        for field in doc['data']:
            img = doc['data'][field]
            # Check that the data is 2D or 3D; if not ignore it.
            data_key = descriptor['data_keys'][field]
            ndim = len(data_key['shape'] or [])
            if data_key['dtype'] == 'array' and 1 < ndim < 4:
                img_asarray = numpy.asarray(img, dtype=self._astype)
                if ndim == 2:
                    # handle 2D data just like 3D data
                    # by adding a 3rd dimension
                    img_asarray = numpy.expand_dims(img_asarray, axis=0)
                for i in range(img_asarray.shape[0]):
                    img_asarray_2d = img_asarray[i, :]
                    num = next(self._counter[stream_name][field])
                    filename = get_prefixed_filename(
                        file_prefix=self._file_prefix,
                        start_doc=self._start,
                        descriptor_doc=descriptor,
                        event_doc=doc,
                        num=num,
                        stream_name=stream_name,
                        field=field)
                    file = self._manager.open('stream_data', filename, 'xb')
                    tw = TiffWriter(file, **self._init_kwargs)
                    self._tiff_writers[stream_name][field + f'-{num}'] = tw
                    tw.save(img_asarray_2d, *self._kwargs)
Exemplo n.º 20
0
def write_tif(fp, image):
    """Simple wrapper for tifffile.TiffWriter"""
    # Convert to grey scale 16-bit image
    with warnings.catch_warnings():      # Suppress precision
        warnings.simplefilter('ignore')  # loss warnings
        image = img_as_uint(rgb2gray(image))

    # Save to disk with `TiffWriter`
    fp.parent.mkdir(parents=False, exist_ok=True)
    with TiffWriter(fp.as_posix()) as tif:
        tif.save(image)
Exemplo n.º 21
0
    def perform_stitching(self, ids, x_size, y_size, plane_path_list,
                          field_path_list, metadata):
        nplanes = len(plane_path_list[self._reference_channel])
        gc.collect()

        if self._stitching_mode == 'stack':
            output_path_stack = self._out_dir + self._img_name
            delete = '\b' * 25
            with TiffWriter(output_path_stack, bigtiff=True) as TW:
                for i, channel in enumerate(self._channel_names):
                    print('\nprocessing channel no.{0}/{1} {2}'.format(
                        i + 1, self._nchannels, channel))
                    print('started at', datetime.now())
                    for j, plane in enumerate(plane_path_list[channel]):
                        print('{0}plane {1}/{2}'.format(
                            delete, j + 1, nplanes),
                              end='',
                              flush=True)
                        TW.save(stitch_plane(plane, ids, x_size, y_size,
                                             self._y_pos,
                                             self._ill_cor_ch[channel],
                                             self._scan),
                                photometric='minisblack',
                                contiguous=True,
                                description=metadata)

        elif self._stitching_mode == 'maxz':
            output_path_maxz = self._out_dir + self._img_name
            with TiffWriter(output_path_maxz, bigtiff=True) as TW:
                for i, channel in enumerate(self._channel_names):
                    print('\nprocessing channel no.{0}/{1} {2}'.format(
                        i + 1, self._nchannels, channel))
                    print('started at', datetime.now())

                    TW.save(stitch_z_projection(channel, field_path_list, ids,
                                                x_size, y_size, self._y_pos,
                                                self._ill_cor_ch[channel],
                                                self._scan),
                            photometric='minisblack',
                            contiguous=True,
                            description=metadata)
Exemplo n.º 22
0
def writeCroppedTiffStack(directory, outDir, y_ind, x_ind):
    fileList = os.listdir(directory)
    for _file in fileList:
        imPath = os.path.join(directory, _file)
        image = imread(imPath)
        image = image[:, y_ind[0]:y_ind[1], x_ind[0]:x_ind[1]]
        imPath = os.path.join(outDir, _file)
        print('for {}, the new image shape is {}'.format(_file, image.shape))
        with TiffWriter(imPath, bigtiff=True) as tif:
            for i in range(image.shape[0]):
                tif.save(image[i, :, :])
        print('the image {} was saved at:\n {}'.format(_file, imPath))
Exemplo n.º 23
0
def save_tiff(path, image):
    tag = ('InterColorProfile', TIFF.DATATYPES.BYTE, len(srgb_profile),
           srgb_profile, False)
    try:
        with TiffWriter(path) as writer:
            writer.save(image,
                        photometric='rgb',
                        resolution=(72, 72),
                        extratags=[tag])
    except OSError as err:
        print_error(err)
        sys.exit(1)
Exemplo n.º 24
0
def test_load_raw_and_labeled_tiff():
    """Load raw and labeled array from separate tiff files."""
    expected_raw = np.zeros((1, 1, 1, 1))
    expected_labeled = np.ones((1, 1, 1, 1))
    raw = io.BytesIO()
    labeled = io.BytesIO()
    with TiffWriter(raw) as writer:
        writer.save(expected_raw)
        raw.seek(0)
    with TiffWriter(labeled) as writer:
        writer.save(expected_labeled)
        labeled.seek(0)
    url = 'http://example.com/mocked/raw.tiff'
    labeled_url = 'http://example.com/mocked/labeled.tiff'
    responses.add(responses.GET, url, body=io.BufferedReader(raw))
    responses.add(responses.GET, labeled_url, body=io.BufferedReader(labeled))

    loader = URLLoader({'url': url, 'labeled_url': labeled_url})

    np.testing.assert_array_equal(loader.raw_array, expected_raw)
    np.testing.assert_array_equal(loader.label_array, expected_labeled)
    assert loader.cell_ids is not None
    assert loader.cell_info is not None
Exemplo n.º 25
0
def procPlateSet(dirPath, sid, plates, seeds, rWidth):
    '''
    simplified version, uses the original masks to evaluate growth
    rootthrsigma: estimated value 4.0
    '''

    contours = cv2.findContours(seeds.astype(np.uint8), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)[0]
    centers=[]
    for cnt in contours:
        #rect =cv2.boundingRect(cnt)
        x,y,w,h=cv2.boundingRect(cnt)
        centers.append([int((x+x+w)/2),int((y+y+h)/2)])

    #sort and split
    # Y direction
    centers.sort(key = lambda centers: centers[1])
    y0 = int(np.mean([c[1] for c in centers[:12]]))
    y1 = int(np.mean([c[1] for c in centers[12:]]))
    #positions
    x0 = sorted([c[0] for c in centers[:12]])
    x1 = sorted([c[0] for c in centers[12:]])
    #mean half distance between seeds
    xd0 = int((x0[-1] - x0[0])/2/(len(x0) - 1))
    xd1 = int((x1[-1] - x1[0])/2/(len(x1) - 1))

    #load all plates
    pmax = plates.max(axis=0)

    #save individual plants
    ytop = 450
    ybot = 1800
    cnt=0
    colors=((200,200,0),(200,0,200),(0,200,200))
    reportLog={}
    for yy, xx, xd in zip([y0, y1], [x0,x1], [xd0, xd1]):
        for px in xx: 
            rw = int(xd*rWidth/100) #region width
            ulx, uly, lrx, lry = px-rw, yy-ytop, px+rw, yy+ybot
            cv2.rectangle(pmax, (ulx,uly-20*(cnt%2)), (lrx, lry+20*(cnt%2)), colors[cnt%3], 9)
            subname = "%s/plant-%s-%02d_%04d-%04d_%04d-%04d.tif"%(dirPath, sid, cnt, ulx, uly, lrx, lry)  
            print(subname)
            reportLog["Plant %2d"%cnt] = str((ulx, uly, lrx, lry))
            subplates=plates[:,uly:lry,ulx:lrx,:]
            with TiffWriter(subname) as tif:
                tif.save(subplates, compress=5)
            cnt += 1
    
    subname = "%s/plant-regions-%s.png"%(dirPath, sid)
    imageio.imwrite(subname, pmax[::4,::4])
    return reportLog
Exemplo n.º 26
0
def save_tiff(mov: np.ndarray, fname: str) -> None:
    """
    Save image stack array to tiff file.

    Parameters
    ----------
    mov: nImg x Ly x Lx
        The frames to save
    fname: str
        The tiff filename to save to

    """
    with TiffWriter(fname) as tif:
        for frame in np.floor(mov).astype(np.int16):
            tif.save(frame)
Exemplo n.º 27
0
def test_load_raw_tiff():
    """Load raw array from tiff file."""
    expected = np.zeros((1, 1, 1, 1))
    tifffile = io.BytesIO()
    with TiffWriter(tifffile) as writer:
        writer.save(expected)
        tifffile.seek(0)
    url = 'http://example.com/mocked/raw.tiff'
    responses.add(responses.GET, url, body=io.BufferedReader(tifffile))

    loader = URLLoader({'url': url})

    np.testing.assert_array_equal(loader.raw_array, expected)
    np.testing.assert_array_equal(loader.label_array, expected)
    assert loader.cell_ids is not None
    assert loader.cell_info is not None
Exemplo n.º 28
0
def main():
    parser = argparse.ArgumentParser(
        description=
        "auto-rotation tool [using techniques of https://dx.doi.org/10.1371/journal.pone.0163453 ]"
    )

    parser.add_argument("input", type=str, help="input file name")
    parser.add_argument("--output",
                        type=str,
                        default="",
                        help="output file name")
    parser.add_argument("--channel",
                        type=int,
                        default=0,
                        help="bright field channel")

    args = parser.parse_args()
    if args.output == '':
        args.output = args.input + '_rotated-%04d.tif'

    ims = MultiImageStack.open(args.input)

    mp = ims.get_meta('multipoints')

    channels = ims.get_meta('channels')

    bright_field_channel = args.channel

    for p in range(mp):
        first = ims.get_image(t=0, pos=p, channel=bright_field_channel)

        angle = find_rotation(first)

        buffer = numpy.zeros((channels, ) + first.shape, dtype=first.dtype)

        try:
            output_name = args.output % p
        except TypeError:
            output_name = args.output

        with TiffWriter(output_name, imagej=True) as tiff:
            for t in range(ims.get_meta('timepoints')):
                for c in range(channels):
                    buffer[c, :, :] = rotate_image(
                        ims.get_image(t=t, pos=p, channel=c), angle)

                tiff.save(buffer)
Exemplo n.º 29
0
def saveRandom(data, n, size, prefix, saveDir):
    shape = data.shape
    sample_z = np.random.choice(shape[0] - size[0], n)
    sample_y = np.random.choice(shape[1] - size[1], n)
    sample_x = np.random.choice(shape[2] - size[2], n)
    for i in range(n):
        z_end = sample_z[i] + size[0]
        y_end = sample_y[i] + size[1]
        x_end = sample_x[i] + size[2]
        sample = data[sample_z[i]:z_end, sample_y[i]:y_end, sample_x[i]:x_end]
        fileCoord = '_z{}-{}_y{}-{}_x{}-{}.tif'.format(sample_z[i], z_end,
                                                       sample_y[i], y_end,
                                                       sample_x[i], x_end)
        fileName = prefix + fileCoord
        filePath = os.path.join(saveDir, fileName)
        with TiffWriter(filePath) as tif:
            tif.save(sample)
Exemplo n.º 30
0
    def event_page(self, doc):
        '''Add event page document information to a ".tiff" file.

        This method adds event_page document information to a ".tiff" file,
        creating it if nesecary.

        .. warning::

            All non 2D 'image like' data is explicitly ignored.

        .. note::

            The data in Events might be structured as an Event, an EventPage,
            or a "bulk event" (deprecated). The DocumentRouter base class takes
            care of first transforming the other repsentations into an
            EventPage and then routing them through here, so no further action
            is required in this class. We can assume we will always receive an
            EventPage.

        Parameters:
        -----------
        doc : dict
            EventPage document
        '''
        event_model.verify_filled(doc)
        streamname = self._descriptors[doc['descriptor']].get('name')
        self._templated_file_prefix = self._file_prefix.format(
            start=self._start)
        for field in doc['data']:
            for img in doc['data'][field]:
                # check that the data is 2D, if not ignore it
                img_asarray = numpy.asarray(img,
                                            dtype=numpy.dtype(self._astype))
                if img_asarray.ndim == 2:
                    # create a file for this stream and field if required
                    if not self._tiff_writers.get(streamname, {}).get(field):
                        filename = (f'{self._templated_file_prefix}'
                                    f'{streamname}-{field}.tiff')
                        file = self._manager.open('stream_data', filename,
                                                  'xb')
                        tw = TiffWriter(file, **self._init_kwargs)
                        self._tiff_writers[streamname][field] = tw
                    # append the image to the file
                    tw = self._tiff_writers[streamname][field]
                    tw.save(img_asarray, *self._kwargs)