def extend_image(image): IJ.run(image, "Select All", "") IJ.run(image, "Copy", "") width = image.getWidth() height = int(image.getHeight() + extend) image_new = IJ.createImage(imp.getTitle(), "32-bit black", width, height, 1) image_new.setRoi(0, 0, image.getWidth(), image.getHeight()) IJ.run(image_new, "Paste", "") IJ.run(image_new, "Enhance Contrast", "saturated=0.35") IJ.run(image_new, "Select None", "") cal = Calibration(image) cal.pixelWidth = dispersion cal.xOrigin = offset image_new.setCalibration(cal) return image_new
def measure_rm(img_path, roi_path): imp = IJ.openImage(img_path) img_dir = imp.getOriginalFileInfo().directory img_file = imp.getOriginalFileInfo().fileName ip = imp.getProcessor() cal = Calibration(imp) rm = RoiManager() rm = RoiManager.getInstance() rm.runCommand("Open", roi_path) roi_array = rm.getRoisAsArray() moptions = Measurements.MEAN | Measurements.AREA for roi in roi_array: roi_name = roi.getName() ip.setRoi(roi) stat = ImageStatistics.getStatistics(ip, moptions, cal) IJ.log(img_dir + "\t" + img_file + "\t" + roi_name + "\t" + str(stat.pixelCount) + "\t" + str(stat.pixelCount * stat.umean) + "\t" + str(stat.umean)) rm.runCommand("delete")
def run(): helpText = "This program will batch convert any tif image to 8-bit greyscale, " + \ "and empty calibration infomation.\n\n" + \ ">> Press OK to Select a directory of TIFF images." MessageDialog(IJ.getInstance(), "Empty Calibration Guide", helpText) srcDir = DirectoryChooser("Chose Source Dir").getDirectory() if srcDir is None: IJ.log("Choose Dir Canceled!") return for root, directories, filenames in os.walk(srcDir): for filename in filenames: if not filename.endswith(".tif"): continue imgPath = os.path.join(root, filename) outPath = os.path.join(root, "decal-" + filename) imp = IJ.openImage(imgPath) imp.setCalibration(Calibration()) ic = ImageConverter(imp) ic.convertToGray8() IJ.saveAsTiff(imp, outPath) print "removed calibration and saved to ", os.path.basename( outPath)
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 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 getMedians(imPlus): medians = [] stk = imPlus.getStack() for i in range(stk.getSize()): img_stats = ImageStatistics.getStatistics(stk.getProcessor(i + 1), Measurements.MEDIAN, Calibration()) medians.append(img_stats.median) print('GOT MEDIANS') return medians
def get_convexfull_area(self, i, imp=IJ.getImage()): convexfull = self.roi_array[i].getFloatConvexHull() convexfull_roi = PolygonRoi(convexfull, Roi.POLYGON) imp.setRoi(convexfull_roi) moptions = Measurements.MEAN | Measurements.INTEGRATED_DENSITY | Measurements.AREA ip = imp.getProcessor() cal = Calibration(imp) stat = ImageStatistics.getStatistics(ip, moptions, cal) convexfull_are = stat.area return convexfull_are
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
nuclei_singleton = False if True: # 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'
def setScale(self, distCm, distPixel): cal = Calibration() cal.setUnit("cm") cal.pixelWidth = distCm / distPixel cal.pixelHeight = distCm / distPixel ImagePlus().setGlobalCalibration(cal)
# first well stitched. to use a specific file as template, stitch it separately and # call template=make_template(well, data_dir) here. use_template = True 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):
from ij.measure import Calibration, Measurements imp = IJ.getImage() img_dir = imp.getOriginalFileInfo().directory img_file = imp.getOriginalFileInfo().fileName if img_dir and img_file: pass else: img_dir = "None" img_file = imp.getTitle() ip = imp.getProcessor() cal = Calibration(imp) rm = RoiManager.getInstance() roi_list = rm.getRoisAsArray() # ビット論理和を取ることで設定したい値を変えられる moptions = Measurements.MEAN | Measurements.AREA IJ.log("\\Clear") IJ.log("Directory" + "\t" + "File" + "\t" + "Roi_id" + "\t" + "Object" + "\t" + "Area" + "\t" + "Integrated_density" + "\t" + "Mean_intensity") for roi in roi_list: roi_name = roi.getName()
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 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 setCalibration(self, imp): calibration = Calibration() calibration.pixelWidth = self.pixelWidth calibration.pixelHeight = self.pixelHeight imp.setCalibration(calibration)
def main(imp, startRad, stepSize, saveLoc, maskName, cellName, tcsVal): # Create a parser object based on our thresholded cell mask image parser = ImageParser2D(imp) # Set the span of our measurement radii to 0 - i.e. get a meaasurement at every pixel away # from the centre of the cell parser.setRadiiSpan(0, ImageParser2D.MEAN) # Set our position in the parser (just to be safe) parser.setPosition(1, 1, 1) # channel, frame, Z-slice # Center: the x,y,z coordinates of center of analysis # Set this from a ROI currently placed on the image parser.setCenterFromROI() # Sampling distances: start radius (sr), end radius (er), and step size (ss). # A step size of zero would mean 'continuos sampling'. Note that end radius # could also be set programmatically, e.g., from a ROI parser.setRadii(startRad, stepSize, parser.maxPossibleRadius()) # (sr, er, ss) # Set our hemi shells to 'none' i.e. we're taking measurements from both hemispheres # of our image parser.setHemiShells('none') # (...) # Parse the image. This may take a while depending on image size parser.parse() if not parser.successful(): log.error(imp.getTitle() + " could not be parsed!!!") return # We can e.g., access the 'Sholl mask', a synthetic image in which foreground # pixels have been assigned the no. of intersections # Save this image maskImage = parser.getMask() maskLoc = saveLoc + "Sholl Mask " + cellName + ".tif" IJ.save(maskImage, maskLoc) # Now we can access the Sholl profile: profile = parser.getProfile() if profile.isEmpty(): log.error( "All intersection counts were zero! Invalid threshold range!?") return # Remove zeros here as otherwise this messes with polynomial fitting functions profile.trimZeroCounts() # Calculate the best fit polynomial lStats = LinearProfileStats(profile) #plot = ShollPlot(lStats) #plot.show() # Fit out polynomial #plot.rebuild() # Calculate stats from our area normalised semi-log and log-log profiles (128 is semi-log and 256 is log-log) nStatsSemiLog = NormalizedProfileStats(profile, ShollStats.AREA, 128) nStatsLogLog = NormalizedProfileStats(profile, ShollStats.AREA, 256) # Do some checks here to make sure we're specifying semi log and log log correctly checkCorrectMethodFlag( NormalizedProfileStats(profile, ShollStats.AREA).getMethodFlag('Semi-log'), 128) checkCorrectMethodFlag( NormalizedProfileStats(profile, ShollStats.AREA).getMethodFlag('Log-log'), 256) # Get our image calibration and use it to extract the critical values and radii cal = Calibration(imp) # Get our mask metrics maskMetrics = populateMaskMetrics(maskName, tcsVal, lStats, nStatsSemiLog, nStatsLogLog, cal) # Get metrics based on the 10th-90th precentile of our semi log and log log data maskPercMetrics = populatePercentageMaskMetrics(nStatsSemiLog, nStatsLogLog) # Update our maskMetrics dictionary with our percentage metrics maskMetrics.update(maskPercMetrics) # Save our mask metrics saveMaskMetrics(saveLoc, cellName, maskMetrics) # Save our sholl plots saveShollPlots(nStatsSemiLog, saveLoc + "Sholl SL " + cellName + ".tif") saveShollPlots(nStatsLogLog, saveLoc + "Sholl LL " + cellName + ".tif") # Get the best fitting polynomial degree between 1 and 30 bestDegree = lStats.findBestFit( 1, # lowest degree 30, # highest degree 0.7, # lowest value for adjusted RSquared 0.05) # the two-sample K-S p-value used to discard 'unsuitable fits' # If we actually found a best fit: if bestDegree != -1: # Fit our polynomial, save a plot of our best fit, update our mask metrics with fit metrics lStats.fitPolynomial(bestDegree) saveShollPlots(lStats, saveLoc + "Sholl Fit " + cellName + ".tif") maskMetrics = addPolyFitToMaskMetrics(lStats, cal, maskMetrics, bestDegree) # Save our updated mask metrics saveMaskMetrics(saveLoc, cellName, maskMetrics)
for sub_dir in sub_dirs: search = home_dir + sub_dir + filesep + '*.tif' print search files = glob(search) files = [f for f in files if any(well + '-' in f for well in wells)] max_dir = home_dir + 'MAX' + filesep + sub_dir + filesep if not os.path.isdir(max_dir): os.makedirs(max_dir) print files for f in files: print f imp = IJ.openImage(f) imp.show() if imp.getNSlices() == 12: IJ.run( "Stack to Hyperstack...", "order=xyzct channels=%d slices=%d frames=1 display=Color" % (channels, slices)) IJ.run("Z Project...", "projection=[Max Intensity]") imp.close() imp = IJ.getImage() cal = Calibration() imp.setCalibration(cal) print 'title', imp.title # ij.io.FileSaver(imp).saveAsTiff() ij.io.FileSaver(imp).saveAsTiffStack(max_dir + imp.title) imp.close() IJ.run("Close All")
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
# 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 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
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
gap_closing_max_distance) + '\n' log_info += 'track_start: ' + str(track_start) + '\n' # 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')
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 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 setCalibration(self, imp): calibration=Calibration() calibration.pixelWidth=self.pixelWidth calibration.pixelHeight=self.pixelHeight imp.setCalibration(calibration)
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 make_calibration(magnification): cal = Calibration() cal.setUnit('um') cal.pixelWidth = args.magnification cal.pixelHeight = cal.pixelWidth return cal