Ejemplo n.º 1
0
def read_channels(img_path, series):
    dapi = bioformats.load_image(img_path, c=0, series=series, rescale=False)
    mt = bioformats.load_image(img_path, c=1, series=series, rescale=False)
    rsv1 = bioformats.load_image(img_path, c=2, series=series, rescale=False)
    tub = bioformats.load_image(img_path, c=3, series=series, rescale=False)

    return dapi, mt, rsv1, tub
Ejemplo n.º 2
0
def plot_overlay_from_czi_timepoints(path_file, timepoint_one, timepoint_two):
        """
        Plot two timepoints from a czi image in a red/green overlay.  Warning: requires a running javabridge
        :param path_file: Path to the czi file
        :param timepoint_one: First timepoint
        :param timepoint_two: Second timepoint
        :return:
        """
        array_one = bf.load_image(str(path_file), t=timepoint_one)
        array_two = bf.load_image(str(path_file), t=timepoint_two)
        image_one = sitk.GetImageFromArray(array_one)
        image_two = sitk.GetImageFromArray(array_two)
        itkplot.plot_overlay(image_one, image_two, sitk.Transform(2, sitk.sitkIdentity), continuous_update=True,
                             downsample=False)
Ejemplo n.º 3
0
class ImageReader(object):
    def ReadImages(self, fds):
        '''fds -- list of file descriptors (filenames or urls)
        returns a list of channels as numpy float32 arrays
        '''
        return self.read_images_via_bioformats(fds)

    def _read_image_via_bioformats(self, filename_or_url):
        # The opener's destructor deletes the temprary files, so the
        # opener must not be GC'ed until the image has been loaded.
        opener = ThrowingURLopener()
        if p.image_url_prepend:
            parsed = urlparse.urlparse(p.image_url_prepend + filename_or_url)
            if parsed.scheme:
                try:
                    filename_or_url, ignored_headers = opener.retrieve(
                        parsed.geturl())
                except IOError, e:
                    if e.args[0] == 'http error':
                        status_code, message = e.args[1:3]
                        raise ClearException(
                            'Failed to load image from %s' % parsed.geturl(),
                            '%d %s' % (status_code, message))
                    else:
                        raise
        logging.info('Loading image from "%s"' % filename_or_url)
        return bioformats.load_image(filename_or_url)
Ejemplo n.º 4
0
def main(args):
    if hasattr(sys, 'frozen'):
        jar_path = os.path.join(os.path.dirname(sys.executable), "jars")
        jars = [os.path.join(jar_path, os.path.split(jar)[1])
                for jar in bioformats.JARS]
    else:
        jars = bioformats.JARS
    javabridge.start_vm(class_path=jars)
    try:
        filenames = sum(map(glob.glob, sys.argv[1:]), [])
        app = wx.PySimpleApp()
        if len(filenames) == 0:
            with wx.FileDialog(
                None,
                "Pick files for z-stack",
                wildcard="Tiff files (*.tif)|*.tif|All files (*.*)|*.*",
                style = wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE | wx.FD_OPEN) as dlg:
                assert isinstance(dlg, wx.FileDialog)
                if dlg.ShowModal() != wx.ID_OK:
                    return
                filenames = dlg.Paths
        planes = [bioformats.load_image(filename) for filename in filenames]
        img_red, img_green, img_blue = [
            np.dstack([plane[:, :, i] for plane in planes]) *255
            for i in range(3)]
        frame = Q3DFrame(img_red, img_green, img_blue, None,
                         size=(1024, 768))
        frame.SetTitle("Q3DStack: %s" %filenames[0])
        app.MainLoop()
        
    finally:
        javabridge.kill_vm()
Ejemplo n.º 5
0
def load_image(image_path,
               c=None,
               z=0,
               t=0,
               series=None,
               index=None,
               rescale=True,
               wants_max_intensity=False,
               channel_names=None):
    """
    Load in image from a file using bioformats, always returning a tuple of
    (image, scale) where the image is a numpy.ndarray object, and the scale
    is an integer or None.
    """
    result = bioformats.load_image(path=image_path,
                                   c=c,
                                   z=z,
                                   t=t,
                                   series=series,
                                   index=index,
                                   rescale=rescale,
                                   wants_max_intensity=wants_max_intensity,
                                   channel_names=channel_names)
    if wants_max_intensity:
        # The value of result is a tuple: ( image, scale )
        image, scale = result
    else:
        image = result
        scale = None
    # The image is a numpy.ndarray object, and the scale is an integer or None.
    return image, scale
Ejemplo n.º 6
0
 def run(self, workspace):
     image_name = self.image_name.value
     measurements = workspace.measurements
     image_set = workspace.image_set
     
     M_FILE_NAME = cpmeas.C_FILE_NAME + "_" + image_name
     M_PATH_NAME = cpmeas.C_PATH_NAME + "_" + image_name
     #
     # Use measurements.get_measurement to get the file name and path name
     # for this cycle
     #
     path_name = measurements.get_measurement(cpmeas.IMAGE, M_PATH_NAME)
     file_name = measurements.get_measurement(cpmeas.IMAGE, M_FILE_NAME)
     #
     # use os.path.join(pathname, filename) to get the name for BioFormats
     #
     path = os.path.join(path_name, file_name)
     #
     # call load_image(path) to load the file into a numpy array
     #
     pixel_data = load_image(path)
     #
     # make a cpi.Image for the image data
     #
     image = cpi.Image(pixel_data, path_name = path_name, file_name = file_name)
     #
     # call image_set.add to add the image to the image set
     #
     image_set.add(image_name, image)
Ejemplo n.º 7
0
    def ProcessFileList(self):
        self.Nfiles = len(self.video_list)
        for idx in range(self.Nfiles):
            input_video = self.video_list[idx]
            input_roif  = self.roif_list[idx]
            input_ext   = os.path.splitext(input_video)[1]

            self.output_prefix = os.path.join(self.save_direct,
                                 os.path.splitext(
                                 os.path.basename(input_video))[0])

            #File that contains the ROI coordinates
            this_roif   = np.array(bioformats.load_image(input_roif,rescale=False))
            self.roi_buff_dict,self.roi_path_dict = self.growROI(this_roif,self.roi_buffer)

            #Output file for intensity timeseries
            self.this_ofile = os.path.join(
                              self.save_direct,
                              os.path.basename(
                              input_video
                              ).replace(input_ext,'.csv')
                              )
            self.this_nofile = self.this_ofile.replace('.csv','_normalized.csv')
            self.this_noplot = self.this_nofile.replace('.csv','.pdf')
            #Currently tested importing nd2 files or TIFF files...theoretically can load any bioformats file
            if input_ext=='.nd2':
                self.ProcessND2(input_video)
            else:
                self.ProcessOther(input_video)
def test_load_using_bioformats():
    path = os.path.join(os.path.dirname(__file__), 'resources',
                        'Channel1-01-A-01.tif')
    image, scale = bioformats.load_image(path,
                                         rescale=False,
                                         wants_max_intensity=True)
    print(image.shape)
Ejemplo n.º 9
0
def measure_image(image_name):
    sample = re.sub('_pc_fov_[0-9]*_[0-9]*.czi', '', image_name)
    image = bioformats.load_image(image_name, rescale=False)
    confocal_image_name = '{}_fov_1_488.czi'.format(sample)
    confocal_image = bioformats.load_image(confocal_image_name, rescale=False)
    segmentation = segment_images(image)
    cells = skimage.measure.regionprops(segmentation)
    average_photon_count = np.empty((len(cells), image.shape[2]))
    total_photon_count = np.empty((len(cells), image.shape[2]))
    for k in range(0, image.shape[2]):
        cells = skimage.measure.regionprops(segmentation,
                                            intensity_image=image[:, :, k])
        average_photon_count[:, k] = [x.mean_intensity for x in cells]
        total_photon_count[:, k] = [x.mean_intensity * x.area for x in cells]
    average_confocal_intensity = np.empty((len(cells), image.shape[2]))
    total_confocal_intensity = np.empty((len(cells), image.shape[2]))
    for k in range(0, image.shape[2]):
        cells = skimage.measure.regionprops(
            segmentation, intensity_image=confocal_image[:, :, k])
        average_confocal_intensity[:, k] = [x.mean_intensity for x in cells]
        total_confocal_intensity[:, k] = [
            x.mean_intensity * x.area for x in cells
        ]
    cell_areas = [x.area * 0.07 * 0.07 for x in cells]
    fig = plt.figure()
    fig.set_size_inches(cm_to_inches(8), cm_to_inches(5))
    plt.hist(cell_areas, bins=100, color=(0, 0.5, 1), histtype='step')
    plt.xlabel(r'$A_c$ [$\mu m^2$]', fontsize=8, color=theme_color)
    plt.ylabel('Frequency', fontsize=8, color=theme_color)
    plt.tick_params(direction='in', length=2, labelsize=8, colors=theme_color)
    plt.axes().spines['left'].set_color(theme_color)
    plt.axes().spines['bottom'].set_color(theme_color)
    plt.axes().spines['right'].set_color(theme_color)
    plt.axes().spines['top'].set_color(theme_color)
    plt.subplots_adjust(left=0.22, bottom=0.25, right=0.98, top=0.97)
    plt.savefig('{}_cell_area.pdf'.format(sample), dpi=300, transparent=True)
    plt.close()
    save_segmentation(segmentation, sample)
    average_photon_counts_filename = '{}_average_photon_counts.csv'.format(
        sample)
    total_photon_counts_filename = '{}_total_photon_counts.csv'.format(sample)
    pd.DataFrame(average_photon_count).to_csv(average_photon_counts_filename,
                                              index=None)
    pd.DataFrame(total_photon_count).to_csv(total_photon_counts_filename,
                                            index=None)
    return
def max_projection(path, t_slice, z_slices, image_channel):
    count = 0
    for z in z_slices:
        if z == np.min(z_slices):
            test_img = bioformats.load_image(path=path,
                                             t=t_slice,
                                             z=z,
                                             series=0)
            shape = np.shape(test_img)
            img_array = np.zeros([shape[0], shape[1], len(z_slices)])
        img_loop = bioformats.load_image(path=path, t=t_slice, z=z,
                                         series=0) * 65535
        if len(np.shape(img_loop)) > 2:
            img_loop = img_loop[:, :, image_channel]
        img_array[:, :, count] = img_loop
        count += 1
    max_intensity = np.amax(img_array, axis=2)
    return max_intensity
Ejemplo n.º 11
0
def read_test_image(file_name, **kwargs):
    '''Read an image from the test directory
    
    file_name - name of the file within the test directory
    
    **kwargs - arguments passe into load_image
    '''
    from bioformats import load_image
    path = os.path.join(testimages_directory, file_name)
    return load_image(path, **kwargs)
Ejemplo n.º 12
0
def read_test_image(file_name, **kwargs):
    '''Read an image from the test directory
    
    file_name - name of the file within the test directory
    
    **kwargs - arguments passe into load_image
    '''
    from bioformats import load_image
    path = os.path.join(testimages_directory, file_name)
    return load_image(path, **kwargs)
Ejemplo n.º 13
0
def load_tif_stack(fname, limit=None):
    stack = []
    for i in itertools.count():
        if not limit or i < limit:
            try:
                stack.append(bioformats.load_image(fname, t=i))
            except javabridge.jutil.JavaException:
                break
        else:
            break
    return np.array(stack)
Ejemplo n.º 14
0
def load_tif_stack(fname, limit=None):
    stack = []
    for i in itertools.count():
        if not limit or i < limit:
            try:
                stack.append(bioformats.load_image(fname, t=i))
            except javabridge.jutil.JavaException:
                break
        else:
            break
    return np.array(stack)
Ejemplo n.º 15
0
def read_example_image(folder, file_name, **kwargs):
    '''Read an example image from one of the example image directories
    
    folder - folder containing images, e.g. "ExampleFlyImages"
    
    file_name - the name of the file within the folder
    
    **kwargs - any keyword arguments are passed onto load_image
    '''
    from bioformats import load_image
    path = os.path.join(example_images_directory(), folder, file_name)
    return load_image(path, **kwargs)
Ejemplo n.º 16
0
    def provide_image(self, image_set):
        """Load an image from a pathname
        """

        if self.__image is not None:
            return self.__image

        if self.volume:
            return self.get_image_volume()

        self.cache_file()
        filename = self.get_filename()
        channel_names = []
        url = self.get_url()
        properties = {}
        if self.index is None:
            metadata = bioformats.get_omexml_metadata(self.get_full_name())

            ometadata = bioformats.omexml.OMEXML(metadata)
            pixel_metadata = ometadata.image(
                0 if self.series is None else self.series).Pixels
            nplanes = pixel_metadata.SizeC * pixel_metadata.SizeZ * pixel_metadata.SizeT
            indexes = list(range(nplanes))
        elif numpy.isscalar(self.index):
            indexes = [self.index]
        else:
            indexes = self.index
        planes = []
        offset = 0
        for i, index in enumerate(indexes):
            properties["index"] = str(index)
            if self.series is not None:
                if numpy.isscalar(self.series):
                    properties["series"] = self.series
                else:
                    properties["series"] = self.series[i]
            img = bioformats.load_image(self.get_full_name(),
                                        rescale=False,
                                        **properties).astype(int)
            img = convert_image_to_objects(img).astype(numpy.int32)
            img[img != 0] += offset
            offset += numpy.max(img)
            planes.append(img)

        image = Image(
            numpy.dstack(planes),
            path_name=self.get_pathname(),
            file_name=self.get_filename(),
            convert=False,
        )
        self.__image = image
        return image
Ejemplo n.º 17
0
def read_example_image(folder, file_name, **kwargs):
    '''Read an example image from one of the example image directories

    folder - folder containing images, e.g. "ExampleFlyImages"

    file_name - the name of the file within the folder

    **kwargs - any keyword arguments are passed onto load_image
    '''
    from bioformats import load_image
    path = os.path.join(example_images_directory(), folder, file_name)
    maybe_download_example_image([folder], file_name)
    return load_image(path, **kwargs)
Ejemplo n.º 18
0
def czi_timepoint_to_sitk_image(path_file, position, resolution, resolution_unit='microns'):
        """
        Open a timepoint from a czi image and make it into an ITK image.  Warning: requires a running javabridge.
        
        :param path_file: Path to the czi file
        :param position: Timepoint to open
        :param resolution: Resolution of the czi image
        :param resolution_unit: The unit of measure (e.g. microns) of the czi image
        :return: A SimpleITK image made from the timepoint
        """
        array = bf.load_image(str(path_file), t=position)
        image = sitk.GetImageFromArray(array)
        image.SetSpacing([resolution, resolution])
        image.SetMetaData('Unit', resolution_unit)
        
        return image
Ejemplo n.º 19
0
 def _read_image(self, filename_or_url, log_io=True):
     # The opener's destructor deletes the temprary files, so the
     # opener must not be GC'ed until the image has been loaded.
     opener = ThrowingURLopener()
     if p.image_url_prepend:
         parsed = urllib.parse.urlparse(p.image_url_prepend +
                                        filename_or_url)
         if parsed.scheme:
             try:
                 filename_or_url, ignored_headers = opener.retrieve(
                     parsed.geturl())
             except IOError as e:
                 if e.args[0] == 'http error':
                     status_code, message = e.args[1:3]
                     raise ClearException(
                         'Failed to load image from %s' % parsed.geturl(),
                         '%d %s' % (status_code, message))
                 else:
                     raise
     if not p.force_bioformats and os.path.splitext(
             filename_or_url)[-1].lower() in IMAGEIO_FORMATS:
         if log_io:
             logging.info('ImageIO: Loading image from "%s"' %
                          filename_or_url)
         try:
             return imageio.imread(filename_or_url)
         except FileNotFoundError:
             logging.error(f"File not found: {filename_or_url}")
             return
         except:
             logging.info(
                 'Loading with ImageIO failed, falling back to BioFormats')
     if javabridge.get_env() is None:
         logging.debug("Starting javabridge")
         javabridge.start_vm(class_path=bioformats.JARS, run_headless=True)
         javabridge.attach()
     if log_io:
         logging.info('BioFormats: Loading image from "%s"' %
                      filename_or_url)
     try:
         return bioformats.load_image(filename_or_url, rescale=False)
     except FileNotFoundError:
         logging.error(f"File not found: {filename_or_url}")
     except:
         logging.error(
             'Loading with BioFormats failed, file may be corrupted or unavailable'
         )
Ejemplo n.º 20
0
def load_TIFF(path, opath, serie=0):
    meta, _ = _metadata(path, serie=serie)
    image = np.empty((meta['SizeX'], meta['SizeY'], meta['SizeC']))

    #with bioformats.ImageReader(path) as rdr:
    #    for t in range(0, meta['SizeT']):
    #        for z in range(0, meta['SizeZ']):
    #            for c in  range(0, meta['SizeC']):
    #                image[:,:,c]=rdr.read(c=c, z=z, t=t, series=serie,
    #                                      index=None, rescale=False, wants_max_intensity=False,
    #                                      channel_names=None)

    img = bioformats.load_image(path, c=0)

    directory = _new_directory(opath, meta)

    return (img, directory, meta)
Ejemplo n.º 21
0
    def load_slide_scanner_image(self, z=0, serie=4):

        self.downfactor = 1

        self._img_vsi = bf.load_image(self.path.as_posix(),
                                      t=0,
                                      series=serie,
                                      z=z)

        metadata = bf.get_omexml_metadata(self.path.as_posix())

        o = bf.OMEXML(metadata)

        n_zslices = o.image_count

        self.n_slices_known.emit(n_zslices, self._img_vsi.shape[-1], 4, 1)

        self.slice_slide_scanner()
Ejemplo n.º 22
0
def read_bf(path):
    """

    read an image into a np-array using BioFormats

    Parameters
    ----------
    path: str
        file path to read

    Returns
    -------
    img: np.array
        image as np-array
    """
    javabridge.start_vm(class_path=bioformats.JARS, run_headless=True)
    img = bioformats.load_image(path, rescale=False)
    return img
 def _read_image_via_bioformats(self, filename_or_url):
     # The opener's destructor deletes the temprary files, so the
     # opener must not be GC'ed until the image has been loaded.
     opener = ThrowingURLopener()
     if p.image_url_prepend:
         parsed = urlparse.urlparse(p.image_url_prepend + filename_or_url)
         if parsed.scheme:
             try:
                 filename_or_url, ignored_headers = opener.retrieve(parsed.geturl())
             except IOError as e:
                 if e.args[0] == 'http error':
                     status_code, message = e.args[1:3]
                     raise ClearException(
                         'Failed to load image from %s' % parsed.geturl(),
                         '%d %s' % (status_code, message))
                 else:
                     raise
     logging.info('Loading image from "%s"' % filename_or_url)
     return bioformats.load_image(filename_or_url)
Ejemplo n.º 24
0
 def _read_image_via_bioformats(self, filename_or_url):
     # The opener's destructor deletes the temprary files, so the
     # opener must not be GC'ed until the image has been loaded.
     opener = ThrowingURLopener()
     if p.image_url_prepend:
         parsed = urlparse.urlparse(p.image_url_prepend + filename_or_url)
         if parsed.scheme:
             try:
                 filename_or_url, ignored_headers = opener.retrieve(
                     parsed.geturl())
             except IOError as e:
                 if e.args[0] == 'http error':
                     status_code, message = e.args[1:3]
                     raise ClearException(
                         'Failed to load image from %s' % parsed.geturl(),
                         '%d %s' % (status_code, message))
                 else:
                     raise
     logging.info('Loading image from "%s"' % filename_or_url)
     return bioformats.load_image(filename_or_url)
def measure_reference_images(image_name, cal_toggle, calibration_norm):
    sample = re.sub('_[0-9]*.czi', '', image_name[0])
    print('Analyzing sample {}...'.format(sample))
    image_stack = [bioformats.load_image(filename) for filename in image_name]
    segmentation, image_stack = segment_images(image_stack)
    if cal_toggle == 'T':
        image_ffc = correct_images(image_stack, calibration_norm)
    else:
        image_ffc = image_stack.copy()
    cells = skimage.measure.regionprops(segmentation)
    avgint = np.empty((len(cells), image_ffc.shape[2]))
    for k in range(0, image_ffc.shape[2]):
        cells = skimage.measure.regionprops(segmentation,
                                            intensity_image=image_ffc[:, :, k])
        avgint[:, k] = [x.mean_intensity for x in cells]
    save_segmentation(segmentation, sample)
    avgint_norm = avgint / np.max(avgint, axis=1)[:, None]
    avgintfilename = sample + '_avgint.csv'
    avgintnormfilename = sample + '_avgint_norm.csv'
    np.savetxt(avgintfilename, avgint, delimiter=',')
    np.savetxt(avgintnormfilename, avgint_norm, delimiter=',')
    return (segmentation, avgint)
Ejemplo n.º 26
0
    def correctBackground(self,input_frame,input_video,channel,is_nd2=False):
        if self.ts == 0:
            for idx in range(self.irrad_frame):
                if is_nd2:
                    this_frame = input_video.get_frame_2D(c=channel,t=idx)
                else:
                    this_frame = np.array(bioformats.load_image(input_video,c=self.protein_channel,t=self.ts,rescale=False))
                self.histogram,bins = np.histogram(this_frame,
                              bins=np.arange(1,np.max(this_frame)+1))
        
                #Smooth the histogram out
                temp    = np.convolve(self.histogram,
                                  np.ones(3,dtype=int),'valid')
                ranges  = np.arange(1,2,2)
                start   = np.cumsum(self.histogram[:2])[::2]/ranges
                stop    = (np.cumsum(self.histogram[:-3:-1])[::2]/ranges)[::-1]
                self.smoothed_hist  = np.concatenate((start,temp,stop))
                self.peaks    = scipy.signal.find_peaks(self.smoothed_hist)[0]
                self.min_peak_int = np.max(self.smoothed_hist[self.peaks])
                self.min_peak = np.where(self.smoothed_hist==self.min_peak_int)[0][0]
                self.bg_value       = bins[np.where(
                                      self.smoothed_hist[self.min_peak:]<=\
                                      (0.67*self.min_peak_int))[0][0]]\
                                      +self.min_peak
                self.avg_bg         = np.average(this_frame[np.where(
                                      input_frame<=self.bg_value)])

                try:
                    self.arr_of_avgs = np.append(self.arr_of_avgs,
                                                 self.avg_bg)
                except:
                    self.arr_of_avgs = np.array([self.avg_bg])

            self.bg_correction  = np.average(self.arr_of_avgs)

        output_frame = input_frame - self.bg_correction
        output_frame[np.where(output_frame < 0)] = 0
        return output_frame
Ejemplo n.º 27
0
def load_image( image_path, c=None, z=0, t=0, series=None, index=None,
                rescale=True, wants_max_intensity=False, channel_names=None ):
    """
    Load in image from a file using bioformats, always returning a tuple of
    (image, scale) where the image is a numpy.ndarray object, and the scale
    is an integer or None.
    """
    result = bioformats.load_image( path=image_path,
                                    c=c,
                                    z=z,
                                    t=t,
                                    series=series,
                                    index=index,
                                    rescale=rescale,
                                    wants_max_intensity=wants_max_intensity,
                                    channel_names=channel_names )
    if wants_max_intensity:
        # The value of result is a tuple: ( image, scale )
        image, scale = result
    else:
        image = result
        scale = None
     # The image is a numpy.ndarray object, and the scale is an integer or None.
    return image, scale
Ejemplo n.º 28
0
 import sys
 matplotlib.use('WXAgg')
 from wx.lib.inspection import InspectionTool
 import matplotlib.pyplot
 from scipy.ndimage import label
 from centrosome.otsu import otsu
 
 javabridge.start_vm(class_path=bioformats.JARS)
 try:
     app = wx.PySimpleApp()
     figure = matplotlib.figure.Figure()
     images = []
     objects = []
     masks = []
     for i, arg in enumerate(sys.argv[1:]):
         img = bioformats.load_image(arg)
         images.append(
             ImageData("Image %d" % (i+1), img,
                       alpha = 1.0 / (len(sys.argv) - 1),
                       mode = MODE_COLORIZE))
         thresh = otsu(img)
         l, _ = label(img >= thresh, np.ones((3,3), bool))
         outline_color = tuple([int(idx == i) for idx in range(3)])
         objects.append(ObjectsData(
             "Objects %d" % (i+1), [l], 
             outline_color = outline_color,
             mode = MODE_LINES))
         ii = np.linspace(-1, 1, num = img.shape[0])[:, np.newaxis]
         jj = np.linspace(-1, 1, num = img.shape[1])[np.newaxis, :]
         mask = (ii ** (2*i+2) + jj ** (2*i+2)) ** (1.0 / (2*i+2)) < .75
         masks.append(MaskData("Mask %d" % (i+1), mask, 
Ejemplo n.º 29
0
 def test_01_08_get_height(self):
     file_name = os.path.join(self.root_dir, "ExampleSBSImages",
                              "Channel1-01-A-01.tif")
     ip = I.load_imageplus(file_name)
     target = load_image(file_name)
     self.assertEqual(ip.getHeight(), target.shape[0])
def generate_2d_segmentation(sample):
    excitations = ['488', '514', '561', '633']
    image_name = ['{}_{}.czi'.format(sample, x) for x in excitations]
    image_stack = [bioformats.load_image(filename) for filename in image_name]
    image_sum = [np.sum(image, axis=2) for image in image_stack]
    shift_vectors = [
        skimage.feature.register_translation(np.log(image_sum[0] + 1e-4),
                                             np.log(image_sum[i]))[0]
        for i in range(1, 4)
    ]
    shift_vectors.insert(0, np.asarray([0.0, 0.0]))
    image_registered = [np.zeros(image.shape) for image in image_stack]
    shift_filter_mask = [
        np.full((image.shape[0], image.shape[1]), False, dtype=bool)
        for image in image_stack
    ]
    image_shape = image_stack[0].shape[0]
    for i in range(len(image_stack)):
        shift_row = int(shift_vectors[i][0])
        shift_col = int(shift_vectors[i][1])
        if np.abs(shift_row) > 15:
            shift_row = 0
        if np.abs(shift_col) > 15:
            shift_col = 0
        print(shift_row, shift_col)
        original_row_min = int(np.maximum(0, shift_row))
        original_row_max = int(image_shape + np.minimum(0, shift_row))
        original_col_min = int(np.maximum(0, shift_col))
        original_col_max = int(image_shape + np.minimum(0, shift_col))
        registered_row_min = int(-np.minimum(0, shift_row))
        registered_row_max = int(image_shape - np.maximum(0, shift_row))
        registered_col_min = int(-np.minimum(0, shift_col))
        registered_col_max = int(image_shape - np.maximum(0, shift_col))
        image_registered[i][
            original_row_min:original_row_max,
            original_col_min:original_col_max, :] = image_stack[i][
                registered_row_min:registered_row_max,
                registered_col_min:registered_col_max, :]
        shift_filter_mask[i][original_row_min:original_row_max,
                             original_col_min:original_col_max] = True
    image_channel = np.dstack(image_registered)
    image_registered_sum = np.sum(image_channel, axis=2)
    image_registered_sum_norm = image_registered_sum / np.max(
        image_registered_sum)
    image_noise_variance = skimage.restoration.estimate_sigma(
        image_registered_sum_norm)
    image_registered_sum_nl = skimage.restoration.denoise_nl_means(
        image_registered_sum_norm, h=0.02)
    image_padded = skimage.util.pad(image_registered_sum_nl, 5, mode='edge')
    image_lp = line_profile_2d_v2(image_padded.astype(np.float64), 11, 9)
    image_lp = np.nan_to_num(image_lp)
    image_lp_min = np.min(image_lp, axis=3)
    image_lp_max = np.max(image_lp, axis=3)
    image_lp_max = image_lp_max - image_lp_min
    image_lp = image_lp - image_lp_min[:, :, :, None]
    image_lp_rel_norm = image_lp / image_lp_max[:, :, :, None]
    image_lp_rnc = image_lp_rel_norm[:, :, :, 5]
    image_lprns = np.average(image_lp_rnc, axis=2)
    image_lprn_lq = np.percentile(image_lp_rnc, 25, axis=2)
    image_lprn_uq = np.percentile(image_lp_rnc, 75, axis=2)
    image_lprn_qcv = np.zeros(image_lprn_uq.shape)
    image_lprn_qcv_pre = (image_lprn_uq - image_lprn_lq) / (
        image_lprn_uq + image_lprn_lq + 1e-8)
    image_lprn_qcv[image_lprn_uq > 0] = image_lprn_qcv_pre[image_lprn_uq > 0]
    image_final = image_lprns * (1 - image_lprn_qcv)
    intensity_rough_seg = KMeans(n_clusters=2, random_state=0).fit_predict(
        image_final.reshape(np.prod(image_final.shape),
                            1)).reshape(image_final.shape)
    image0 = image_final * (intensity_rough_seg == 0)
    image1 = image_final * (intensity_rough_seg == 1)
    i0 = np.average(image0[image0 > 0])
    i1 = np.average(image1[image1 > 0])
    if (i0 < i1):
        intensity_rough_seg_mask = (intensity_rough_seg == 1)
        intensity_rough_seg_bkg = (intensity_rough_seg == 0)
    else:
        intensity_rough_seg_mask = (intensity_rough_seg == 0)
        intensity_rough_seg_bkg = (intensity_rough_seg == 1)
    image_lprns_rsfbo = skimage.morphology.binary_opening(
        intensity_rough_seg_mask)
    image_lprns_rsfbosm = skimage.morphology.remove_small_objects(
        image_lprns_rsfbo, 10)
    image_lprns_rsfbosm_bfh = binary_fill_holes(image_lprns_rsfbosm)
    intensity_rough_seg_mask_bfh = binary_fill_holes(intensity_rough_seg_mask)
    image_watershed_seeds = skimage.measure.label(image_lprns_rsfbosm_bfh *
                                                  intensity_rough_seg_mask_bfh)
    image_registered_sum_nl_log = np.log10(image_registered_sum_nl)
    image_bkg_filter = KMeans(n_clusters=2, random_state=0).fit_predict(
        image_registered_sum_nl_log.reshape(
            np.prod(image_registered_sum_nl_log.shape),
            1)).reshape(image_registered_sum_nl_log.shape)
    image0 = image_registered_sum_nl * (image_bkg_filter == 0)
    image1 = image_registered_sum_nl * (image_bkg_filter == 1)
    i0 = np.average(image0[image0 > 0])
    i1 = np.average(image1[image1 > 0])
    if (i0 < i1):
        image_bkg_filter_mask = (image_bkg_filter == 1)
    else:
        image_bkg_filter_mask = (image_bkg_filter == 0)
    image_final_bkg_filtered = image_registered_sum_nl_log * image_bkg_filter_mask
    image_sum_bkg_filtered = image_registered_sum * image_bkg_filter_mask
    image_watershed_seeds_bkg_filtered = image_watershed_seeds * image_bkg_filter_mask
    image_watershed_sauvola = threshold_sauvola(image_registered_sum_nl)
    image_watershed_mask_bkg_filtered = (
        image_registered_sum_nl >
        image_watershed_sauvola) * image_bkg_filter_mask
    image_seg = skimage.morphology.watershed(
        -image_final_bkg_filtered,
        image_watershed_seeds_bkg_filtered,
        mask=image_watershed_mask_bkg_filtered)
    image_seg = skimage.segmentation.relabel_sequential(image_seg)[0]
    adjacency_seg = skimage.morphology.watershed(
        -image_sum_bkg_filtered,
        image_watershed_seeds_bkg_filtered,
        mask=image_bkg_filter_mask)
    adjacency_seg = skimage.segmentation.relabel_sequential(adjacency_seg)[0]
    save_segmentation(image_seg, sample)
    return (image_registered_sum, image_channel, image_final_bkg_filtered,
            image_seg, adjacency_seg)
def test_load_using_bioformats():
    path = os.path.join(os.path.dirname(__file__), 'resources', 'Channel1-01-A-01.tif')
    image, scale = bioformats.load_image(path, rescale=False, wants_max_intensity=True)
    print(image.shape)
def z_and_t_area(path,meta_number=None, cycle_vm=True,crop_img=False,print_number=5,edge=False,binary=False,
                 image_channel=1,rescale_factor=255,meta_stage_loop=True,t_sample=1,show=True,
                 rebin=True,compute_height=False,canny_range=.33,
                               hist_cutoff=0.01,manual_thresh=False,m_thresh_high=1000,m_thresh_low=100):
    
    # start javabridge
    if cycle_vm:
        javabridge.start_vm(class_path=bioformats.JARS)
    # read in metadata using bioformats and make ararys for t ans z slices
    metadata=v.extract_metadata(path,cycle_vm=False,meta_number=meta_number,stage_loop=meta_stage_loop)
    z_slices=np.arange(0,metadata['size_Z'])
    z_slices_scaled=z_slices*float(metadata['relative step width'])
    t_slices=np.arange(0,metadata['size_T']-1)
    t_slices=t_slices[::t_sample]
    t_slices_scaled=t_slices*float(metadata['cycle time'])
    # declare dataframes to store analysis results in
    area_df=pd.DataFrame()
    if compute_height:
        height_df=pd.DataFrame()
    # crop image option to do if specified
    if crop_img:
        # determine cropping bounds
        img=bioformats.load_image(path=path,z=z_slices[3],t=t_slices[-1],series=0)
        img = (img * rescale_factor).astype('uint8')
        bounds = get_bounds(img,scale=0.4)
    print_thresh=np.linspace(0,100,print_number)
    print_count=0
    plot_grid_count=1
    finished_plotting=False
    # iterate through time slices, stop before the last one
    for i in range(len(t_slices)-1):
        percent=t_slices[i]/(len(t_slices)-1)
        if percent>print_thresh[print_count]:
            # print('\tt: {:.2f} S'.format(t_slices_scaled[i]))
            print_count+=1
        # declare surface_area array outside of z-stack loop
        area=np.zeros(len(z_slices))
        for j in range(len(z_slices)):
            # read image
            img=bioformats.load_image(path=path,z=z_slices[j],t=t_slices[i],
                                      rescale=False)
            # if the image consists of multiple channels take just one channel 
            if len(np.shape(img))>2:
                img=img[:,:,image_channel]
            equalize_hist=exposure.equalize_adapthist(img,clip_limit=hist_cutoff,nbins=65535)
            ratio=np.amax(equalize_hist)/65535
            equalize_hist=np.round(equalize_hist/ratio,0).astype(int)
            
            # if rebin is specified rebin image using 2x2 binning
            if rebin:
                equalize_hist=bin2d(img,2)
            
            if crop_img:
                crop=equalize_hist[int(bounds[1]):int(bounds[1] + bounds[3]), int(bounds[0]):int(bounds[0] + bounds[2])]
            else:
                crop=equalize_hist
            # threshold image
            if edge:
                bw=edge_and_fill(crop,canny_range=canny_range)
            else:
                if manual_thresh:
                    bw=thresh_and_fill(img,low=m_thresh_low)
                else:
                    bw=auto_threshold(img,'triangle')
            # if compute height specified and on the firt step of loop make a zeros array
            # the length and width of the image and height of the z_stacks number
            if compute_height:
                if j==0:
                    img_shape=np.shape(img)
                    img_stack=np.zeros([img_shape[0],img_shape[1],len(z_slices)])
                img_stack[:,:,j]=bw
            # subpart of program to show images comparing plots andbin
            if show:
                f1=plt.figure()
                z_count=0
                t_count=0
                count_satisfied,t_count,z_count=show_handler(i,len(t_slices),
                                                             j,len(z_slices),
                                                             t_count,z_count)
                if count_satisfied and not finished_plotting:
                    plt.subplot(6,6,plot_grid_count)
                    plt.imshow(equalize_hist)
                    plt.axis('off')
                    plt.subplot(6,6,plot_grid_count+1)
                    plt.imshow(bw)
                    plt.axis('off')
                    plot_grid_count+=2
                    if plot_grid_count>=36:
                        finished_plotting=True
                f1.show()
            # calculate area of thresholded image
            if rebin:
                scale=metadata['scale']**2
            else:
                scale=metadata['scale']**2
            area[j]=get_area(bw,scale)
            if compute_height:
                average_height,length=calc_height(img_stack,scale,metadata['relative step width'])
                loop_height=pd.DataFrame({
                    'Length (um)':length,
                    'Height (um)':average_height,
                    'time (s)':[t_slices_scaled[i]]*len(length)
                    })
                height_df=height_df.append(loop_height,ignore_index=True)
                
        # store in datafame along with other imporant variables
        loop_area_df=pd.DataFrame({'Thrombus Area (um^2)':area,
                                   'Z loc (um)':z_slices_scaled,
                                   'time (s)':[t_slices_scaled[i]]*len(area)
                                   })
        area_df=area_df.append(loop_area_df,ignore_index=True)
    if cycle_vm:
        javabridge.kill_vm()
    if compute_height:
        return area_df,height_df
    else:
        return area_df
Ejemplo n.º 33
0
#### load z-stack

i = 0

nt = ox.image(i).Pixels.SizeT
nx = ox.image(i).Pixels.SizeX
ny = ox.image(i).Pixels.SizeY
nz = ox.image(i).Pixels.SizeZ
nc = ox.image(i).Pixels.SizeC

na = np.zeros((nt,nx,ny,nz,nc), dtype = 'uint8')

for it in range(nt):
  for iz in range(nz):
      na[it,:,:,iz,:] = bf.load_image(path, c=None, z=iz, t=it, series=i, index=None, rescale=False, wants_max_intensity=False, channel_names=None)

bg = np.zeros((nx,ny,nz), dtype = 'uint8')

viewer = vv.Viewer()
viewer.addGrayscaleLayer(bg, name="black")
green_layer = viewer.addAlphaModulatedLayer(na[0,...,0], name="green", tintColor=QColor(0,255,0))
blue_layer = viewer.addAlphaModulatedLayer(na[0,...,1], name="blue", tintColor=QColor(0,0,255))
green_layer.opacity = 1.0
blue_layer.opacity = 1.0
viewer.show()


#### load z-stack

Ejemplo n.º 34
0
def get_preview_image(fname, meta_xml=None, maxwh=256, series=0):
    """ Generate a thumbnail of an image at the specified path. Gets the
    middle Z plane of channel=0 and timepoint=0 of the specified series.

    Parameters
    ----------
    fname: str
        Path to image file.
    meta_xml: str
        OME XML metadata.
    maxwh: int
        Maximum width or height of the output thumbnail. If the extracted
        image is larger in either x or y, the image will will be downsized
        to fit.
    series: int
        Series for multi-stack formats (default=0)

    Returns
    -------
    img: numpy.ndarray
        N x M array of grayscale pixel intentsities.
    """
    name, ext = os.path.splitext(os.path.basename(fname))

    if ext[1:] not in bioformats.READABLE_FORMATS:
        raise Exception("Format not supported: %s" % ext[1:])

    if not meta_xml:
        meta_xml = bioformats.get_omexml_metadata(fname)
    ome = bioformats.OMEXML(meta_xml)

    if series > ome.get_image_count():
        raise Exception(
            "Specified series number %s exceeds number of series " "in the image file: %s" % (series, fname)
        )

    # Get metadata for first series
    meta = ome.image(0).Pixels

    # Determine resize factor
    sizex = meta.SizeX
    sizey = meta.SizeY
    if sizex > maxwh or sizey > maxwh:
        f = min(float(maxwh) / float(sizex), float(maxwh) / float(sizey))
    else:
        f = max(float(maxwh) / float(sizex), float(maxwh) / float(sizey))

    # Determine which Z slice
    z = 0

    # Determine middle Z plane
    # Note: SizeZ doesn't seem to be reliable. Might need to check BF.
    # Stick with first slice for now.
    # if meta.SizeZ > 1:
    #     z = int(math.floor(float(meta.SizeZ)/2))

    # Load image plane
    if meta.channel_count == 1 and meta.SizeC == 4:
        # RGB Image
        img = bioformats.load_image(fname, t=0, z=z, series=series, rescale=False)
        return zoom(img, (f, f, 1))
    else:
        # Grayscale, grab channel 0 only
        img = bioformats.load_image(fname, c=0, t=0, z=z, series=series, rescale=False)
        # if img.dtype in (np.uint16, np.uint32, np.int16, np.int32):
        img = stretch_contrast(img)
        return zoom(img, f)
Ejemplo n.º 35
0
def get_preview_image(fname, meta_xml=None, maxwh=256, series=0):
    """ Generate a thumbnail of an image at the specified path. Gets the
    middle Z plane of channel=0 and timepoint=0 of the specified series.

    Parameters
    ----------
    fname: str
        Path to image file.
    meta_xml: str
        OME XML metadata.
    maxwh: int
        Maximum width or height of the output thumbnail. If the extracted
        image is larger in either x or y, the image will will be downsized
        to fit.
    series: int
        Series for multi-stack formats (default=0)

    Returns
    -------
    img: numpy.ndarray
        N x M array of grayscale pixel intentsities.
    """
    name, ext = os.path.splitext(os.path.basename(fname))

    if ext[1:] not in bioformats.READABLE_FORMATS:
        raise Exception("Format not supported: %s" % ext[1:])

    if not meta_xml:
        meta_xml = bioformats.get_omexml_metadata(fname)
    ome = bioformats.OMEXML(meta_xml)

    if series > ome.get_image_count():
        raise Exception("Specified series number %s exceeds number of series "
                        "in the image file: %s" % (series, fname))

    # Get metadata for first series
    meta = ome.image(0).Pixels

    # Determine resize factor
    sizex = meta.SizeX
    sizey = meta.SizeY
    if sizex > maxwh or sizey > maxwh:
        f = min(float(maxwh) / float(sizex), float(maxwh) / float(sizey))
    else:
        f = max(float(maxwh) / float(sizex), float(maxwh) / float(sizey))

    # Determine which Z slice
    z = 0

    # Determine middle Z plane
    # Note: SizeZ doesn't seem to be reliable. Might need to check BF.
    # Stick with first slice for now.
    # if meta.SizeZ > 1:
    #     z = int(math.floor(float(meta.SizeZ)/2))

    # Load image plane
    if meta.channel_count == 1 and meta.SizeC == 4:
        # RGB Image
        img = bioformats.load_image(fname,
                                    t=0,
                                    z=z,
                                    series=series,
                                    rescale=False)
        return zoom(img, (f, f, 1))
    else:
        # Grayscale, grab channel 0 only
        img = bioformats.load_image(fname,
                                    c=0,
                                    t=0,
                                    z=z,
                                    series=series,
                                    rescale=False)
        # if img.dtype in (np.uint16, np.uint32, np.int16, np.int32):
        img = stretch_contrast(img)
        return zoom(img, f)
 def test_file_not_found(self):
     # Regression test of issue #6
     path = os.path.join(os.path.dirname(__file__), 'Channel5-01-A-01.tif')
     self.assertRaises(exceptions.IOError, 
                       lambda :load_image(path))
Ejemplo n.º 37
0
from __future__ import absolute_import, print_function, unicode_literals

import os
import javabridge
import bioformats
from bioformats import log4j
import sys

javabridge.start_vm(class_path=bioformats.JARS, run_headless=True)
try:
    log4j.basic_config()
    if len(sys.argv) < 2:
        image_path = os.path.join(os.path.dirname(bioformats.__file__), '..',
                                  'tests', 'resources', 'Channel1-01-A-01.tif')
    else:
        image_path = sys.argv[1]
    image, scale = bioformats.load_image(image_path,
                                         rescale=False,
                                         wants_max_intensity=True)
    try:
        import pylab

        pylab.imshow(image)
        pylab.gca().set_title(image_path)
        pylab.show()
    except:
        print(image.shape)
finally:
    javabridge.kill_vm()
Ejemplo n.º 38
0
if __name__ == "__main__":
    javabridge.start_vm(class_path=bioformats.JARS)
    sequences = glob('./VoxelMorph/data/Series009*.tif')
    print(len(sequences))

    for name in sequences:  # filter(lambda name: name.find('Seq') != -1, sequences)
        def_x_name = '/home/nadya/Projects/VoxelMorph/data/deformations/ics/' \
                     + name.split('/')[-1].split('.tif')[0] + '_ffXsh_fwd.ics'
        def_y_name = '/home/nadya/Projects/VoxelMorph/data/deformations/ics/' \
                     + name.split('/')[-1].split('.tif')[0] + '_ffYsh_fwd.ics'
        seq = io.imread(name)
        deform = np.empty(seq.shape + (2, ))
        print(deform.shape)
        print(name, def_x_name)
        for i in tqdm(range(len(seq))):
            deform[i, :, :, 0] = bioformats.load_image(def_x_name, z=i)[None]
            deform[i, :, :, 1] = bioformats.load_image(def_y_name, z=i)[None]

        tmp = deform[0].copy()
        deform = deform[1:]
        deform = deform[::-1]
        deform = np.concatenate([tmp[None], deform], 0)

        named = './VoxelMorph/data/deformations/numpy/' + name.split(
            '/')[-1].split('.tif')[0] + '_fwd.npy'
        np.save(named, deform)

        def_x_name = './VoxelMorph/data/deformations/ics/' + name.split(
            '/')[-1].split('.tif')[0] + '_ffXsh_bcw.ics'
        def_y_name = './VoxelMorph/data/deformations/ics/' + name.split(
            '/')[-1].split('.tif')[0] + '_ffYsh_bcw.ics'
def load_ztslice(filename, z_index, t_index):
    image = bioformats.load_image(filename, z=z_index, t=t_index)
    return (image)
    def test_02_01_compare_to_matlab(self):
        path = os.path.split(__file__)[0]
        png_file = 'Channel2-01-A-01Mask.png'
        mat_file = 'texturemeasurements.mat'
        mask_file = os.path.join(path, png_file)
        if not os.path.isfile(mask_file):
            github_fmt = github_url + "/cellprofiler/modules/tests/%s"
            mask = load_using_bioformats_url(github_fmt % png_file) != 0
            fin = urllib2.urlopen(github_fmt % mat_file)
            fd, tempmat = tempfile.mkstemp(".mat")
            fout = os.fdopen(fd, "wb")
            shutil.copyfileobj(fin, fout)
            fout.close()
            texture_measurements = loadmat(tempmat, struct_as_record=True)
            os.remove(tempmat)
        else:
            mask = load_image(mask_file) != 0
            texture_measurements = loadmat(
                os.path.join(path, mat_file), 
                struct_as_record=True)
                
        texture_measurements = texture_measurements['m'][0,0]
        folder = 'ExampleSBSImages'
        file_name = 'Channel1-01-A-01.tif'
        image_file = os.path.join(
            example_images_directory(), folder, file_name)
        maybe_download_example_image([folder], file_name)
        image = load_image(image_file, rescale=False).astype(float)/255.0
        labels,count = scind.label(mask.astype(bool),np.ones((3,3),bool))
        centers = scind.center_of_mass(np.ones(labels.shape), labels, 
                                       np.arange(count)+1)
        centers = np.array(centers)
        X = 1 # the index of the X coordinate
        Y = 0 # the index of the Y coordinate
        order_python = np.lexsort((centers[:,X],centers[:,Y]))
        workspace, module = self.make_workspace(image, labels, convert = False)
        module.scale_groups[0].scale.value = 3
        my_angle = M.H_HORIZONTAL
        module.scale_groups[0].angles.value = my_angle

        module.run(workspace)
        m = workspace.measurements
        tm_center_x = texture_measurements['Location_Center_X'][0,0][:,0]
        tm_center_y = texture_measurements['Location_Center_Y'][0,0][:,0]
        order_matlab = np.lexsort((tm_center_x,tm_center_y))
            
        for measurement in M.F_HARALICK:
            mname = '%s_%s_%s_%d'%(M.TEXTURE, measurement, INPUT_IMAGE_NAME, 3)
            pymname = mname + "_" + M.H_TO_A[my_angle]
            pytm = m.get_current_measurement(INPUT_OBJECTS_NAME, pymname)
            tm = texture_measurements[mname][0,0][:,]
            error_count = 0
            for i in range(count):
                matlab_val = tm[order_matlab[i]]
                python_val = pytm[order_python[i]]
                self.assertAlmostEqual(tm[order_matlab[i]],
                                       pytm[order_python[i]],7,
                                       "Measurement = %s, Loc=(%.2f,%.2f), Matlab=%f, Python=%f"%
                                       (mname, tm_center_x[order_matlab[i]],
                                        tm_center_y[order_matlab[i]],
                                        tm[order_matlab[i]],
                                        pytm[order_python[i]]))
        image_measurements =\
        (('Texture_AngularSecondMoment_Cytoplasm_3', 0.5412),
         ('Texture_Contrast_Cytoplasm_3',0.1505),
         ('Texture_Correlation_Cytoplasm_3', 0.7740),
         ('Texture_Variance_Cytoplasm_3', 0.3330),
         ('Texture_InverseDifferenceMoment_Cytoplasm_3',0.9321),
         ('Texture_SumAverage_Cytoplasm_3',2.5684),
         ('Texture_SumVariance_Cytoplasm_3',1.1814),
         ('Texture_SumEntropy_Cytoplasm_3',0.9540),
         ('Texture_Entropy_Cytoplasm_3',1.0677),
         ('Texture_DifferenceVariance_Cytoplasm_3',0.1314),
         ('Texture_DifferenceEntropy_Cytoplasm_3',0.4147),
         ('Texture_InfoMeas1_Cytoplasm_3',-0.4236),
         ('Texture_InfoMeas2_Cytoplasm_3',0.6609))
        for feature_name, value in image_measurements:
            py_feature_name = feature_name + "_" + M.H_TO_A[my_angle]
            pytm = m.get_current_image_measurement(py_feature_name)
            self.assertAlmostEqual(pytm, value,3,
                                   "%s failed. Python=%f, Matlab=%f" %
                                   (feature_name, pytm, value))
Ejemplo n.º 41
0
    def run_as_data_tool(self):
        from cellprofiler.gui.editobjectsdlg import EditObjectsDialog
        import wx
        from wx.lib.filebrowsebutton import FileBrowseButton
        from cellprofiler.modules.namesandtypes import ObjectsImageProvider
        from bioformats import load_image

        with wx.Dialog(None) as dlg:
            dlg.Title = "Choose files for editing"
            dlg.Sizer = wx.BoxSizer(wx.VERTICAL)
            sub_sizer = wx.BoxSizer(wx.HORIZONTAL)
            dlg.Sizer.Add(sub_sizer, 0, wx.EXPAND | wx.ALL, 5)
            new_or_existing_rb = wx.RadioBox(dlg,
                                             style=wx.RA_VERTICAL,
                                             choices=("New", "Existing"))
            sub_sizer.Add(new_or_existing_rb, 0, wx.EXPAND)
            objects_file_fbb = FileBrowseButton(
                dlg,
                size=(300, -1),
                fileMask=
                "Objects file (*.tif, *.tiff, *.png, *.bmp, *.jpg)|*.tif;*.tiff;*.png;*.bmp;*.jpg",
                dialogTitle="Select objects file",
                labelText="Objects file:",
            )
            objects_file_fbb.Enable(False)
            sub_sizer.AddSpacer(5)
            sub_sizer.Add(objects_file_fbb, 0, wx.ALIGN_TOP | wx.ALIGN_RIGHT)

            def on_radiobox(event):
                objects_file_fbb.Enable(new_or_existing_rb.GetSelection() == 1)

            new_or_existing_rb.Bind(wx.EVT_RADIOBOX, on_radiobox)

            image_file_fbb = FileBrowseButton(
                dlg,
                size=(300, -1),
                fileMask=
                "Objects file (*.tif, *.tiff, *.png, *.bmp, *.jpg)|*.tif;*.tiff;*.png;*.bmp;*.jpg",
                dialogTitle="Select guide image file",
                labelText="Guide image:",
            )
            dlg.Sizer.Add(image_file_fbb, 0, wx.EXPAND | wx.ALL, 5)

            allow_overlap_checkbox = wx.CheckBox(dlg, -1,
                                                 "Allow objects to overlap")
            allow_overlap_checkbox.Value = True
            dlg.Sizer.Add(allow_overlap_checkbox, 0, wx.EXPAND | wx.ALL, 5)

            buttons = wx.StdDialogButtonSizer()
            dlg.Sizer.Add(buttons, 0,
                          wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL,
                          5)
            buttons.Add(wx.Button(dlg, wx.ID_OK))
            buttons.Add(wx.Button(dlg, wx.ID_CANCEL))
            buttons.Realize()
            dlg.Fit()
            result = dlg.ShowModal()
            if result != wx.ID_OK:
                return
            self.allow_overlap.value = allow_overlap_checkbox.Value
            fullname = objects_file_fbb.GetValue()
            guidename = image_file_fbb.GetValue()

        if new_or_existing_rb.GetSelection() == 1:
            provider = ObjectsImageProvider("InputObjects",
                                            pathname2url(fullname), None, None)
            image = provider.provide_image(None)
            pixel_data = image.pixel_data
            shape = pixel_data.shape[:2]
            labels = [pixel_data[:, :, i] for i in range(pixel_data.shape[2])]
        else:
            labels = None
        #
        # Load the guide image
        #
        guide_image = load_image(guidename)
        if np.min(guide_image) != np.max(guide_image):
            guide_image = (guide_image - np.min(guide_image)) / (
                np.max(guide_image) - np.min(guide_image))
        if labels is None:
            shape = guide_image.shape[:2]
            labels = [np.zeros(shape, int)]
        with EditObjectsDialog(guide_image, labels, self.allow_overlap,
                               self.object_name.value) as dialog_box:
            result = dialog_box.ShowModal()
            if result != wx.OK:
                return
            labels = dialog_box.labels
        n_frames = len(labels)
        with wx.FileDialog(None,
                           style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as dlg:

            dlg.Path = fullname
            dlg.Wildcard = ("Object image file (*.tif,*.tiff)|*.tif;*.tiff|"
                            "Ilastik project file (*.ilp)|*.ilp")
            result = dlg.ShowModal()
            fullname = dlg.Path
            if result == wx.ID_OK:
                if fullname.endswith(".ilp"):
                    self.save_into_ilp(fullname, labels, guidename)
                else:
                    from bioformats.formatwriter import write_image
                    from bioformats.omexml import PT_UINT16

                    if os.path.exists(fullname):
                        os.unlink(fullname)
                    for i, l in enumerate(labels):
                        write_image(fullname,
                                    l,
                                    PT_UINT16,
                                    t=i,
                                    size_t=len(labels))
Ejemplo n.º 42
0
def load_img(path, series, z_max):
    """gets all z-stacks in an image"""
    all_z_in_image = [
        bioformats.load_image(path, series=series, z=z) for z in range(z_max)
    ]
    return (all_z_in_image)
Ejemplo n.º 43
0
 def test_01_08_get_height(self):
     file_name = os.path.join(
             self.root_dir, "ExampleSBSImages", "Channel1-01-A-01.tif")
     ip = I.load_imageplus(file_name)
     target = load_image(file_name)
     self.assertEqual(ip.getHeight(), target.shape[0])
    def run_as_data_tool(self):
        from cellprofiler.gui.editobjectsdlg import EditObjectsDialog
        import wx
        from wx.lib.filebrowsebutton import FileBrowseButton
        from cellprofiler.modules.namesandtypes import ObjectsImageProvider
        from bioformats import load_image
        
        with wx.Dialog(None) as dlg:
            dlg.Title = "Choose files for editing"
            dlg.Sizer = wx.BoxSizer(wx.VERTICAL)
            box = wx.StaticBox(dlg, -1, "Choose or create new objects file")
            sub_sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
            dlg.Sizer.Add(sub_sizer, 0, wx.EXPAND | wx.ALL, 5)
            new_or_existing_rb = wx.RadioBox(dlg, style=wx.RA_VERTICAL,
                                             choices = ("New", "Existing"))
            sub_sizer.Add(new_or_existing_rb, 0, wx.EXPAND)
            objects_file_fbb = FileBrowseButton(
                dlg, size=(300, -1),
                fileMask="Objects file (*.tif, *.tiff, *.png, *.bmp, *.jpg)|*.tif;*.tiff;*.png;*.bmp;*.jpg",
                dialogTitle="Select objects file",
                labelText="Objects file:")
            objects_file_fbb.Enable(False)
            sub_sizer.AddSpacer(5)
            sub_sizer.Add(objects_file_fbb, 0, wx.ALIGN_TOP | wx.ALIGN_RIGHT)
            def on_radiobox(event):
                objects_file_fbb.Enable(new_or_existing_rb.GetSelection() == 1)
            new_or_existing_rb.Bind(wx.EVT_RADIOBOX, on_radiobox)
            
            image_file_fbb = FileBrowseButton(
                dlg, size=(300, -1),
                fileMask="Objects file (*.tif, *.tiff, *.png, *.bmp, *.jpg)|*.tif;*.tiff;*.png;*.bmp;*.jpg",
                dialogTitle="Select guide image file",
                labelText="Guide image:")
            dlg.Sizer.Add(image_file_fbb, 0, wx.EXPAND | wx.ALL, 5)
            
            allow_overlap_checkbox = wx.CheckBox(dlg, -1, "Allow objects to overlap")
            allow_overlap_checkbox.Value = True
            dlg.Sizer.Add(allow_overlap_checkbox, 0, wx.EXPAND | wx.ALL, 5)
            
            buttons = wx.StdDialogButtonSizer()
            dlg.Sizer.Add(buttons, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
            buttons.Add(wx.Button(dlg, wx.ID_OK))
            buttons.Add(wx.Button(dlg, wx.ID_CANCEL))
            buttons.Realize()
            dlg.Fit()
            result = dlg.ShowModal()
            if result != wx.ID_OK:
                return
            self.allow_overlap.value = allow_overlap_checkbox.Value
            fullname = objects_file_fbb.GetValue()
            guidename = image_file_fbb.GetValue()

        if new_or_existing_rb.GetSelection() == 1:
            provider = ObjectsImageProvider(
                "InputObjects",
                pathname2url(fullname),
                None, None)
            image = provider.provide_image(None)
            pixel_data = image.pixel_data
            shape = pixel_data.shape[:2]
            labels = [pixel_data[:, :, i] for i in range(pixel_data.shape[2])]
        else:
            labels = None
        #
        # Load the guide image
        #
        guide_image = load_image(guidename)
        if np.min(guide_image) != np.max(guide_image):
            guide_image = ((guide_image - np.min(guide_image)) / 
                           (np.max(guide_image)  - np.min(guide_image)))
        if labels is None:
            shape = guide_image.shape[:2]
            labels = [np.zeros(shape, int)]
        with EditObjectsDialog(
            guide_image, labels,
            self.allow_overlap, self.object_name.value) as dialog_box:
            result = dialog_box.ShowModal()
            if result != wx.OK:
                return
            labels = dialog_box.labels
        n_frames = len(labels)
        with wx.FileDialog(None,
                           style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as dlg:
        
            dlg.Path = fullname
            dlg.Wildcard = ("Object image file (*.tif,*.tiff)|*.tif;*.tiff|"
                            "Ilastik project file (*.ilp)|*.ilp")
            result = dlg.ShowModal()
            fullname = dlg.Path
            if result == wx.ID_OK:
                if fullname.endswith(".ilp"):
                    self.save_into_ilp(fullname, labels, guidename)
                else:
                    from bioformats.formatwriter import write_image
                    from bioformats.omexml import PT_UINT16
                    if os.path.exists(fullname):
                        os.unlink(fullname)
                    for i, l in enumerate(labels):
                        write_image(fullname, l, PT_UINT16,
                                    t = i, size_t = len(labels))
def test_file_not_found():
    # Regression test of issue #6
    path = os.path.join(os.path.dirname(__file__), 'resources', 'Channel5-01-A-01.tif')
    with pytest.raises(IOError):
        bioformats.load_image(path)
Ejemplo n.º 46
0
#!/usr/bin/env python

import os
import javabridge
import bioformats
from bioformats import log4j
import sys

javabridge.start_vm(class_path=bioformats.JARS,
                    run_headless=True)
try:
    log4j.basic_config()
    if len(sys.argv) < 2:
        image_path = os.path.join(os.path.dirname(bioformats.__file__), 'tests', 
                                  'Channel1-01-A-01.tif')
    else:
        image_path = sys.argv[1]
    image, scale = bioformats.load_image(image_path, rescale=False,
                                         wants_max_intensity=True)
    try:
        import pylab
        
        pylab.imshow(image)
        pylab.gca().set_title(image_path)
        pylab.show()
    except:
        print image.shape
finally:
    javabridge.kill_vm()