def setscale(imp, scaleX=1.0, scaleY=1.0, scaleZ=1.0, unit="micron"): # check if scaleZ has a valid value to call modify the scaling if scaleZ is None: scaleZ = 1.0 # create new Calibration object newCal = Calibration() # set the new paramters newCal.pixelWidth = scaleX newCal.pixelHeight = scaleY newCal.pixelDepth = scaleZ # set the correct unit fro the scaling newCal.setXUnit(unit) newCal.setYUnit(unit) newCal.setZUnit(unit) # apply the new calibration imp.setCalibration(newCal) return imp
def prepare_image_stacks(image_dir): """ For each stack directory in image_dir, load the image sequence as a stack and spatially calibrate the stack. Returns: images (list): The list containing the calibrated image stacks. Args: image_dir (str): The directory containing the image stack directories. """ images = [] for stack_dir in os.listdir(image_dir): stack_dir_full_path = str(image_dir) + '/' + stack_dir imp = FolderOpener.open(stack_dir_full_path) cal = Calibration() cal.setUnit('um') cal.pixelWidth = 0.3296485 cal.pixelHeight = 0.3296485 cal.pixelDepth = 0.998834955 imp.setCalibration(cal) imp.setTitle( stack_dir) # name the image after its directory, e.g. OP_1 images.append(imp) return images
def setproperties(imp, scaleX=1.0, scaleY=1.0, scaleZ=1.0, unit="micron", sizeC=1, sizeZ=1, sizeT=1): """Set properties of image in Fiji :param imp: Image :type imp: ImgPlus :param scaleX: scaleX, defaults to 1.0 :type scaleX: float, optional :param scaleY: scaleY, defaults to 1.0 :type scaleY: float, optional :param scaleZ: scaleZ, defaults to 1.0 :type scaleZ: float, optional :param unit: scale unit, defaults to "micron" :type unit: str, optional :param sizeC: sizeC, defaults to 1 :type sizeC: int, optional :param sizeZ: sizeZ, defaults to 1 :type sizeZ: int, optional :param sizeT: sizeT, defaults to 1 :type sizeT: int, optional :return: Image :rtype: ImgPlus """ # check if scaleZ has a valid value to call modify the properties if scaleZ is None: scaleZ = 1 # run the image properties tool IJ.run(imp, "Properties...", "channels=" + str(sizeC) + " slices=" + str(sizeZ) + " frames=" + str(sizeT) + " unit=" + unit + " pixel_width=" + str(scaleX) + " pixel_height=" + str(scaleY) + " voxel_depth=" + str(scaleZ)) # create new Calibration object newCal = Calibration() # set the new paramters newCal.pixelWidth = scaleX newCal.pixelHeight = scaleY newCal.pixelDepth = scaleZ # set the correct unit fro the scaling newCal.setXUnit(unit) newCal.setYUnit(unit) newCal.setZUnit(unit) # apply the new calibration imp.setCalibration(newCal) return imp
def set_xyz_calibration(imp, dx, dy, dz, unit): cal = Calibration(imp) cal.setUnit(unit) cal.pixelWidth = dx cal.pixelHeight = dy cal.pixelDepth = dz imp.setCalibration(cal) return imp
def setSpatialCalibration(img, xwidth, unit="micron"): """ img is an image object from openImage() xwidth is the width of the image in units (default micron) """ if xwidth <= 0: # If spatial calibration is not given. Do not try to set it. return pixelSize = xwidth / (1.0*img.getWidth()) cal = Calibration(img) cal.pixelWidth = pixelSize cal.pixelHeight = pixelSize cal.setUnit(unit) img.setCalibration(cal) return img
def setscale(imp, scaleX=1.0, scaleY=1.0, scaleZ=1.0, unit="micron"): """Set new scaling for image. :param imp: image :type imp: ImgPlus :param scaleX: scaleX, defaults to 1.0 :type scaleX: float, optional :param scaleY: scaleY, defaults to 1.0 :type scaleY: float, optional :param scaleZ: scaleZ, defaults to 1.0 :type scaleZ: float, optional :param unit: scaling unit, defaults to "micron" :type unit: str, optional :return: image :rtype: ImgPlus """ # check if scaleZ has a valid value to call modify the scaling if scaleZ is None: scaleZ = 1.0 # create new Calibration object newCal = Calibration() # set the new paramters newCal.pixelWidth = scaleX newCal.pixelHeight = scaleY newCal.pixelDepth = scaleZ # set the correct unit fro the scaling newCal.setXUnit(unit) newCal.setYUnit(unit) newCal.setZUnit(unit) # apply the new calibratiion imp.setCalibration(newCal) return imp
def setproperties(imp, scaleX=1.0, scaleY=1.0, scaleZ=1.0, unit="micron", sizeC=1, sizeZ=1, sizeT=1): # check if scaleZ has a valid value to call modify the properties if scaleZ is None: scaleZ = 1 # run the image properties tool IJ.run(imp, "Properties...", "channels=" + str(sizeC) + " slices=" + str(sizeZ) + " frames=" + str(sizeT) + " unit=" + unit + " pixel_width=" + str(scaleX) + " pixel_height=" + str(scaleY) + " voxel_depth=" + str(scaleZ)) # create new Calibration object newCal = Calibration() # set the new paramters newCal.pixelWidth = scaleX newCal.pixelHeight = scaleY newCal.pixelDepth = scaleZ # set the correct unit fro the scaling newCal.setXUnit(unit) newCal.setYUnit(unit) newCal.setZUnit(unit) # apply the new calibration imp.setCalibration(newCal) return imp
# Get image and calibrate imps = BF.openImagePlus(input_file) imp = imps[0] imp.setDisplayMode(IJ.COLOR) imp.setC(color) # imp.setDisplayRange(0.0, 3.0) # imp.show() log_info += 'frames: ' + str(imp.getNFrames()) + '\n' log_info += 'width: ' + str(imp.getWidth()) + '\n' log_info += 'height: ' + str(imp.getHeight()) + '\n' cal = Calibration() cal.setUnit('micron') cal.pixelHeight = resolution cal.pixelWidth = resolution cal.pixelDepth = 0. cal.fps = 1 cal.frameInterval = 1 imp.setCalibration(cal) #------------------------- # Instantiate model object #------------------------- model = Model() model.setPhysicalUnits('micron', 'frames') # Set logger model.setLogger(Logger.IJ_LOGGER)
def set_calibration_obj(metadata_dict): cal = Calibration() cal.setUnit(metadata_dict["unit"]) cal.pixelWidth = 1 / metadata_dict["xpix"] cal.pixelHeight = 1 / metadata_dict["ypix"] return cal
# osx, unix filesep = '/' home_dir = '/broad/blainey_lab/David/lasagna/20150817 6 round/data/' home_dir = '/Users/feldman/Downloads/20151209/' else: # windows home_dir = 'D:\\User Folders\\David\\lasagna\\20151122_96W-G020\\' # home_dir = '\\\\neon-cifs\\blainey_lab\\David\\lasagna\\20150817 6 round\\analysis\\calibrated\\raw\\' filesep = '\\' data_dirs = ['stack'] cal = Calibration() cal.setUnit('um') cal.pixelWidth = pixel_width cal.pixelHeight = pixel_width def savename(well, data_dir): # TODO better naming convention, use Site_0? return home_dir + data_dir + '_MMStack_' + well + '.stitched.tif' def stitch_cmd_file(directory, layout_file): s = """type=[Positions from file] order=[Defined by TileConfiguration] directory=%s layout_file=%s fusion_method=[Linear Blending] regression_threshold=0.30 max/avg_displacement_threshold=2.50 absolute_displacement_threshold=3.50 computation_parameters=[Save computation time (but use more RAM)] image_output=[Fuse and display]""" return s % (directory, layout_file) for data_dir in data_dirs: print home_dir + data_dir + filesep + '*.registered.tif' files = glob(home_dir + data_dir + filesep + '*.registered.txt') files = [f.split(filesep)[-1] for f in files]
# Set dimensions n_channels = 1 n_slices = 1 # Z slices n_frames = 1 # time frames # Get current image image = IJ.getImage() # Check that we have correct dimensions stack_size = image.getImageStackSize() # raw number of images in the stack if n_channels * n_slices * n_frames == stack_size: image.setDimensions(n_channels, n_slices, n_frames) else: IJ.log('The product of channels ('+str(n_channels)+'), slices ('+str(n_slices)+')') IJ.log('and frames ('+str(n_frames)+') must equal the stack size ('+str(stack_size)+').') # Set calibration pixel_width = 1 pixel_height = 1 pixel_depth = 1 space_unit = 'µm' frame_interval = 1 time_unit = 's' calibration = Calibration() # new empty calibration calibration.pixelWidth = pixel_width calibration.pixelHeight = pixel_height calibration.pixelDepth = pixel_depth calibration.frameInterval = frame_interval calibration.setUnit(space_unit) calibration.setTimeUnit(time_unit) image.setCalibration(calibration) image.repaintWindow()
def process(srcDir, dstDir, currentDir, fileName, keepDirectories): print "Processing:" # Opening the image print "Open image file", fileName imp = IJ.openImage(os.path.join(currentDir, fileName)) #Here we make sure the calibration are correct units = "pixel" TimeUnit = "unit" newCal = Calibration() newCal.pixelWidth = 1 newCal.pixelHeight = 1 newCal.frameInterval = 1 newCal.setXUnit(units) newCal.setYUnit(units) newCal.setTimeUnit(TimeUnit) imp.setCalibration(newCal) cal = imp.getCalibration() dims = imp.getDimensions() # default order: XYCZT if (dims[4] == 1): imp.setDimensions(1, 1, dims[3]) # Start the tracking model = Model() #Read the image calibration model.setPhysicalUnits(cal.getUnit(), cal.getTimeUnit()) # Send all messages to ImageJ log window. model.setLogger(Logger.IJ_LOGGER) settings = Settings() settings.setFrom(imp) # Configure detector - We use the Strings for the keys # Configure detector - We use the Strings for the keys settings.detectorFactory = DownsampleLogDetectorFactory() settings.detectorSettings = { DetectorKeys.KEY_RADIUS: 2., DetectorKeys.KEY_DOWNSAMPLE_FACTOR: 2, DetectorKeys.KEY_THRESHOLD: 1., } print(settings.detectorSettings) # Configure spot filters - Classical filter on quality filter1 = FeatureFilter('QUALITY', 0, True) settings.addSpotFilter(filter1) # Configure tracker - We want to allow merges and fusions settings.trackerFactory = SparseLAPTrackerFactory() settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap( ) # almost good enough settings.trackerSettings['LINKING_MAX_DISTANCE'] = LINKING_MAX_DISTANCE settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = ALLOW_TRACK_SPLITTING settings.trackerSettings['SPLITTING_MAX_DISTANCE'] = SPLITTING_MAX_DISTANCE settings.trackerSettings['ALLOW_TRACK_MERGING'] = ALLOW_TRACK_MERGING settings.trackerSettings['MERGING_MAX_DISTANCE'] = MERGING_MAX_DISTANCE settings.trackerSettings[ 'GAP_CLOSING_MAX_DISTANCE'] = GAP_CLOSING_MAX_DISTANCE settings.trackerSettings['MAX_FRAME_GAP'] = MAX_FRAME_GAP # Configure track analyzers - Later on we want to filter out tracks # based on their displacement, so we need to state that we want # track displacement to be calculated. By default, out of the GUI, # not features are calculated. # The displacement feature is provided by the TrackDurationAnalyzer. settings.addTrackAnalyzer(TrackDurationAnalyzer()) settings.addTrackAnalyzer(TrackSpeedStatisticsAnalyzer()) filter2 = FeatureFilter('TRACK_DISPLACEMENT', 10, True) settings.addTrackFilter(filter2) #------------------- # Instantiate plugin #------------------- trackmate = TrackMate(model, settings) #-------- # Process #-------- ok = trackmate.checkInput() if not ok: sys.exit(str(trackmate.getErrorMessage())) ok = trackmate.process() if not ok: sys.exit(str(trackmate.getErrorMessage())) #---------------- # Display results #---------------- if showtracks: model.getLogger().log('Found ' + str(model.getTrackModel().nTracks(True)) + ' tracks.') selectionModel = SelectionModel(model) displayer = HyperStackDisplayer(model, selectionModel, imp) displayer.render() displayer.refresh() # The feature model, that stores edge and track features. fm = model.getFeatureModel() with open(dstDir + fileName + 'tracks_properties.csv', "w") as file: writer1 = csv.writer(file) writer1.writerow([ "track #", "TRACK_MEAN_SPEED (micrometer.secs)", "TRACK_MAX_SPEED (micrometer.secs)", "NUMBER_SPLITS", "TRACK_DURATION (secs)", "TRACK_DISPLACEMENT (micrometer)" ]) with open(dstDir + fileName + 'spots_properties.csv', "w") as trackfile: writer2 = csv.writer(trackfile) #writer2.writerow(["spot ID","POSITION_X","POSITION_Y","Track ID", "FRAME"]) writer2.writerow( ["Tracking ID", "Timepoint", "Time (secs)", "X pos", "Y pos"]) for id in model.getTrackModel().trackIDs(True): # Fetch the track feature from the feature model. v = (fm.getTrackFeature(id, 'TRACK_MEAN_SPEED') * Pixel_calibration) / Time_interval ms = (fm.getTrackFeature(id, 'TRACK_MAX_SPEED') * Pixel_calibration) / Time_interval s = fm.getTrackFeature(id, 'NUMBER_SPLITS') d = fm.getTrackFeature(id, 'TRACK_DURATION') * Time_interval e = fm.getTrackFeature( id, 'TRACK_DISPLACEMENT') * Pixel_calibration model.getLogger().log('') model.getLogger().log('Track ' + str(id) + ': mean velocity = ' + str(v) + ' ' + model.getSpaceUnits() + '/' + model.getTimeUnits()) track = model.getTrackModel().trackSpots(id) writer1.writerow( [str(id), str(v), str(ms), str(s), str(d), str(e)]) for spot in track: sid = spot.ID() x = spot.getFeature('POSITION_X') y = spot.getFeature('POSITION_Y') z = spot.getFeature('TRACK_ID') t = spot.getFeature('FRAME') time = int(t) * int(Time_interval) writer2.writerow( [str(id), str(t), str(time), str(x), str(y)])
def make_calibration(magnification): cal = Calibration() cal.setUnit('um') cal.pixelWidth = args.magnification cal.pixelHeight = cal.pixelWidth return cal
def setCalibration(self, imp): calibration = Calibration() calibration.pixelWidth = self.pixelWidth calibration.pixelHeight = self.pixelHeight imp.setCalibration(calibration)
def setCalibration(self, imp): calibration=Calibration() calibration.pixelWidth=self.pixelWidth calibration.pixelHeight=self.pixelHeight imp.setCalibration(calibration)
template = None #or make_template('B1', '10X_c2-SBS-2_2') data_dirs = ['test'] # usually xyzct, except on bad days when it's xyczt(default) # order = 'xyzct' order = 'xyczt(default)' rows = 'ABH' columns = [str(x) for x in range(1, 13)] wells = [row + column for row in rows for column in columns] wells = ['A1'] cal = Calibration() cal.setUnit('um') cal.pixelWidth = pixel_width cal.pixelHeight = pixel_width def savename(well, data_dir): # TODO better naming convention, use Site_0? return home_dir + data_dir + '_MMStack_' + well + '.stitched.tif' def tile_config_name(well, data_dir): return def macro_dir(s): """Wrap directory string so ImageJ macro accepts it as parameter. """ return '[%s]' % (s.replace('\\', '\\\\'))
def setScale(self, distCm, distPixel): cal = Calibration() cal.setUnit("cm") cal.pixelWidth = distCm / distPixel cal.pixelHeight = distCm / distPixel ImagePlus().setGlobalCalibration(cal)
n_channels = 1 n_slices = 1 # Z slices n_frames = 1 # time frames # Get current image image = IJ.getImage() # Check that we have correct dimensions stack_size = image.getImageStackSize() # raw number of images in the stack if n_channels * n_slices * n_frames == stack_size: image.setDimensions(n_channels, n_slices, n_frames) else: IJ.log('The product of channels (' + str(n_channels) + '), slices (' + str(n_slices) + ')') IJ.log('and frames (' + str(n_frames) + ') must equal the stack size (' + str(stack_size) + ').') # Set calibration pixel_width = 1 pixel_height = 1 pixel_depth = 1 space_unit = 'µm' frame_interval = 1 time_unit = 's' calibration = Calibration() # new empty calibration calibration.pixelWidth = pixel_width calibration.pixelHeight = pixel_height calibration.pixelDepth = pixel_depth calibration.frameInterval = frame_interval calibration.setUnit(space_unit) calibration.setTimeUnit(time_unit) image.setCalibration(calibration) image.repaintWindow()
filters.setup("median", frame) filters.rank(processor, filter_window, filters.MEDIAN) # Perform gamma correction processor.gamma(gamma) frame = ImagePlus("Frame " + str(frame_i), processor) # Rolling ball background subtraction processor = frame.getProcessor() bg_subtractor = BackgroundSubtracter() bg_subtractor.setup("", frame) bg_subtractor.rollingBallBackground(processor, rolling_ball_size/pixel_size, False, False, False, False, True) frame = ImagePlus("Frame " + str(frame_i), processor) # Calibrate pixels calibration = Calibration() calibration.setUnit("pixel") calibration.pixelWidth = pixel_size calibration.pixelHeight = pixel_size calibration.pixelDepth = 1.0 frame.setCalibration(calibration) # Save to output dir file_name = output_dir + "/" + str(frame_i).zfill(4) + ".tif" FileSaver(frame).saveAsTiff(file_name) frame_i = frame_i + 1