def openjpg(imagefile, metainfo, method='IJ', series=0): if method == 'IJ': # using IJ static method imp = IJ.openImage(imagefile) if method == 'Opener': # Using Opener class imp = Opener().openImage(imagefile) if method == 'BF': # using BioFormats library imps = BF.openImagePlus(imagefile) # read image data using the specified pyramid level imp, slices, width, height, pylevel = ImageTools.getImageSeries(imps, series=series) metainfo['Output Slices'] = slices metainfo['Output SizeX'] = width metainfo['Output SizeY'] = height return imp, metainfo
def convert32to16(fullFilePath): #overwrite the file!!! if not os.path.isfile(fullFilePath): bPrintLog( '\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n', 0) return 0 elif not fullFilePath.endswith('tif'): msg = fullFilePath + " is not a deconvoluted tif file" bPrintLog(msg, 2) else: bPrintLog( time.strftime("%H:%M:%S") + ' starting runOneFile()for overwrite: ' + fullFilePath, 1) #open and overwrite the deconvoluted file as 16 bit imp = Opener().openImage(fullFilePath) #deconvoluted file if imp.getBitDepth() == 32: imp.show() msgStr = "Converting 32 to 16-bit..." bPrintLog(msgStr, 3) IJ.run("16-bit") msgStr = "Overwriting 32-bit with 16-bit File in" + fullFilePath bPrintLog(msgStr, 3) IJ.run(imp, "Save", "") #save as replace without asking imp.close()
def resizeAndSave(filePaths, l): while l.get() < min(len(filePaths), currentWrittenLayer + nTilesAtATime + 1) : k = l.getAndIncrement() if k < min(len(filePaths), currentWrittenLayer + nTilesAtATime): filePath = filePaths[k] imageName = os.path.basename(filePath) resizedImageName = os.path.splitext(imageName)[0] + '_resized_' + factorString + os.path.splitext(imageName)[1] imageFolderName = os.path.basename(os.path.dirname(filePath)) resizedFilePath = fc.cleanLinuxPath(os.path.join(downSampledEMFolder, imageFolderName, resizedImageName)) im = Opener().openImage(filePath) IJ.log('Am I going to process the image: im.height = ' + str(im.height) + ' - tileHeight = ' + str(tileHeight) + ' tile number ' + str(k)) if im.height == tileHeight: # crop a few lines at the top only if it has not already been done (sometimes the pipeline gets rerun) im = fc.crop(im,cropRoi) im = fc.normLocalContrast(im, normLocalContrastSize, normLocalContrastSize, 3, True, True) # IJ.run(im, 'Replace value', 'pattern=0 replacement=1') # only for final waferOverview FileSaver(im).saveAsTiff(filePath) if not os.path.isfile(resizedFilePath): im = fc.resize(im, scaleFactor) FileSaver(im).saveAsTiff(resizedFilePath) IJ.log('Image resized to ' + resizedFilePath) im.close()
def combinestacks(directory, height=5): """Combine all tiff stacks in a directory to a panel. Args: directory: Path to a directory containing a collection of .tiff files. height: The height of the panel (integer). Defaults to 5. The width is spaces automatically. Returns: A combined stack of the input images. """ IJ.log("\nCombining stacks...") files = [ f for f in sorted(os.listdir(directory)) if os.path.isfile(os.path.join(directory, f)) ] IJ.log("Number of files: {}".format(len(files))) groups = chunks(files, height) horiz = [] for group in groups: h = [Opener().openImage(directory, imfile) for imfile in group] h = _horcombine(h) # h.show() horiz.append(h) montage = _vercombine(horiz) montage.show()
def import_multiple_rois(roi_files): rois = [f.getPath() for f in roi_files if f.exists() and f.getName().lower().endswith("roi")] opener = Opener() rm = RoiManager.getRoiManager() if not rm.getInstance(): rm.reset() [rm.addRoi(opener.openRoi(r)) for r in rois]
def get_enhance_bounds(chf_fpaths, low_theshold, high_threshold): # initialize the pixels array pix = [] # open 100 images max (time consuming) if len(chf_fpaths) > 100: chf_fpaths = random.sample(chf_fpaths, 100) # create a for loop here counter = 1 for image_path in chf_fpaths: # open the image print "Getting pixels in Image " + image_path print str(counter) + " / " + str(len(chf_fpaths)) counter += 1 imp_orig = Opener().openImage(image_path) # get the pixel values image_pix = list(imp_orig.getProcessor().getPixels()) imp_orig.close() imp_orig.flush() # select randomly 10% of the pixels (maybe memory issues) image_pix_sel = random.sample(image_pix, int(len(image_pix) * 0.1)) pix = pix + image_pix_sel # get the percentile values to threshold IJ.log('Quantifying pixel values for contrast enhancement...') low_pix = percentile(pix, low_theshold) high_pix = percentile(pix, high_threshold) return low_pix, high_pix
def normalized_roi_length(roi_path, pixel_scaling, normalization_fn=None): ''' Returns the scaled measure of the input roi performing the normalization function if provided. ''' opener = Opener() roi = opener.openRoi(roi_path) scaled_measure = roi.getLength() / pixel_scaling if callable(normalization_fn): return normalization_fn(scaled_measure) return measure
def file_opener(current_title, extension): for filename in os.listdir(dest): i = 0 if filename.endswith(file_type): pass if filename != current_title: pass if not filename.startswith(extension) and i == 0: O = Opener() path = os.path.join(dest, filename) O.open(path) i += 1 break
def main(): indir = IJ.getDirectory("input directory") outdir = IJ.getDirectory("output directory") files = sorted(os.listdir(indir)) IJ.log("files: {}".format(files)) montages = [] for imfile in files: IJ.log("File: {}/{}".format(files.index(imfile)+1, len(files))) if imfile.endswith(".tif"): imp = Opener().openImage(indir, imfile) montage = makemontage(imp, hsize=6, vsize=6, increment=2) _saveimage(montage, outdir)
def main(): indir = IJ.getDirectory("input directory") outdir = IJ.getDirectory("output directory") files = sorted(os.listdir(indir)) # IJ.log("files: {}".format(files)) # montages = [] for imfile in files: IJ.log("File: {}/{}".format(files.index(imfile) + 1, len(files))) if imfile.endswith(".tif"): imp = Opener().openImage(indir, imfile) channels = ChannelSplitter().split(imp) name = outdir + imfile + "_t001_c001.tif" IJ.run(channels[0], "Image Sequence... ", "format=TIFF save={}".format(name))
def main(): # Get the wanted input and output directories. indir = IJ.getDirectory("input directory") outdir = IJ.getDirectory("output directory") # Collect all files in the import directory and sort on file name. files = sorted(os.listdir(indir)) # Loop through all input files. montages = [] for imfile in files: # Some optional feedback if you're impatient. IJ.log("File: {}/{}".format(files.index(imfile) + 1, len(files))) # Make montage of every .tiff file and save as .tiff in the output directory. if imfile.endswith(".tif"): imp = Opener().openImage(indir, imfile) montage = makemontage(imp, hsize=6, vsize=6, increment=2) saveimage(montage, outdir)
def FindThreholds(mainpath, listOfImages, quantArray): #initialize the pixels array pix = [] #create a for loop here for image in listOfImages: #open the image IJ.log('Getting pixels in Image ' + image) imp_orig = Opener().openImage(mainpath + image) imp_GB = blurImage(imp_orig) imp_orig.close() imp_GB.hide() #get the pixel values pix = getPixelValues(imp_GB, pix) imp_GB.close() #get the percentile values to threshold IJ.log('Quantifying thresholds...') percs = [] for q in quantArray: percs.append(percentile(pix, q)) return percs
def batch_profile_from_threshold(batch_parameters): ''' Thresholds the desired channel using the threshold method specified and saves the roi profile in the csv_output. Rois will be set to the width in pixels specified by stroke_width. Provide a batch parameters dict to operate on images. WIP: PUT A BETTER ALGO IN PLACE TO DETERMINE THE CORRECT ROI TO USE. ''' from ij.io import Opener from IBPlib.ij.Utils.Files import buildList opener = Opener() rois_folder, csvs_folder = setup_output_folders(batch_parameters.get("output_folder")) IJ.log("Plotting profiles...") for i, img in enumerate(batch_parameters.get("analysed_images")): progress = "{0}/{1}".format(i+1, len(batch_parameters.get("analysed_images"))) IJ.log("\n# Progress: {0}\n".format(progress)) imp = imageloader(img) #title = os.path.basename(os.path.splitext(img)[0]) title = os.path.basename(img) IJ.log("\nMeasuring -> {0}".format(title)) rois_path_list = buildList(rois_folder, extension=".roi") rois = [opener.openRoi(roi) for roi in rois_path_list if roi.find(title) > 0] if not rois: IJ.log("## No rois found for {0}".format(title)) if not profile_from_threshold(imp, batch_parameters.get("analysis_ch"), rois, batch_parameters.get("stroke_width"), batch_parameters.get("th_method"), csvs_folder): IJ.log("Batch run canceled.") return IJ.log("Done ...") IJ.log("Results stored in '{0}'".format(csvs_folder))
def runOneFile(fullFilePath): global gNumChannels global gAlignBatchVersion if not os.path.isfile(fullFilePath): bPrintLog( '\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n', 0) return 0 bPrintLog( time.strftime("%H:%M:%S") + ' starting runOneFile(): ' + fullFilePath, 1) enclosingPath = os.path.dirname(fullFilePath) head, tail = os.path.split(enclosingPath) enclosingPath += '/' #make output folders destFolder = enclosingPath + tail + '_channels/' if not os.path.isdir(destFolder): os.makedirs(destFolder) destMaxFolder = destFolder + 'max/' if not os.path.isdir(destMaxFolder): os.makedirs(destMaxFolder) if gDoAlign: destAlignmentFolder = destFolder + 'alignment/' if not os.path.isdir(destAlignmentFolder): os.makedirs(destAlignmentFolder) if gSave8bit: eightBitFolder = destFolder + 'channels8/' if not os.path.isdir(eightBitFolder): os.makedirs(eightBitFolder) eightBitMaxFolder = eightBitFolder + 'max/' if not os.path.isdir(eightBitMaxFolder): os.makedirs(eightBitMaxFolder) # open image imp = Opener().openImage(fullFilePath) # get parameters of image (width, height, nChannels, nSlices, nFrames) = imp.getDimensions() bitDepth = imp.getBitDepth() infoStr = imp.getProperty("Info") #get all .tif tags if not infoStr: infoStr = '' infoStr += 'bAlignBatch_Version=' + str(gAlignBatchVersion) + '\n' infoStr += 'bAlignBatch_Time=' + time.strftime( "%Y%m%d") + '_' + time.strftime("%H%M%S") + '\n' msgStr = 'w:' + str(width) + ' h:' + str(height) + ' slices:' + str(nSlices) \ + ' channels:' + str(nChannels) + ' frames:' + str(nFrames) + ' bitDepth:' + str(bitDepth) bPrintLog(msgStr, 1) path, filename = os.path.split(fullFilePath) shortName, fileExtension = os.path.splitext(filename) # # look for num channels in ScanImage infoStr if gGetNumChanFromScanImage: for line in infoStr.split('\n'): #scanimage.SI4.channelsSave = [1;2] scanimage4 = find(line, 'scanimage.SI4.channelsSave =') == 0 #state.acq.numberOfChannelsSave=2 scanimage3 = find(line, 'state.acq.numberOfChannelsSave=') == 0 if scanimage3: #print 'line:', line equalIdx = find(line, '=') line2 = line[equalIdx + 1:] if gGetNumChanFromScanImage: gNumChannels = int(line2) bPrintLog( 'over-riding gNumChannels with: ' + str(gNumChannels), 2) if scanimage4: #print ' we have a scanimage 4 file ... now i need to exptract the number of channel' #print 'line:', line equalIdx = find(line, '=') line2 = line[equalIdx + 1:] for delim in ';[]': line2 = line2.replace(delim, ' ') if gGetNumChanFromScanImage: gNumChannels = len(line2.split()) bPrintLog( 'over-riding gNumChannels with: ' + str(gNumChannels), 2) # show imp.show() # split channels if necc. and grab the original window names if gNumChannels == 1: origImpWinStr = imp.getTitle() #use this when only one channel origImpWin = WindowManager.getWindow( origImpWinStr) #returns java.awt.Window if gNumChannels == 2: winTitle = imp.getTitle() bPrintLog('Deinterleaving 2 channels...', 1) IJ.run('Deinterleave', 'how=2 keep') #makes ' #1' and ' #2', with ' #2' frontmost origCh1WinStr = winTitle + ' #1' origCh2WinStr = winTitle + ' #2' origCh1Imp = WindowManager.getImage(origCh1WinStr) origCh2Imp = WindowManager.getImage(origCh2WinStr) origCh1File = destFolder + shortName + '_ch1.tif' origCh2File = destFolder + shortName + '_ch2.tif' # work on a copy, mostly for alignment with cropping copy = Duplicator().run(imp) #copy.copyAttributes(imp) #don't copy attributes, it copies the name (which we do not want) copy.show() # # crop (on copy) if gDoCrop: bPrintLog('making cropping rectangle (left,top,width,height) ', 1) bPrintLog( str(gCropLeft) + ' ' + str(gCropTop) + ' ' + str(gCropWidth) + ' ' + str(gCropHeight), 2) roi = Roi(gCropLeft, gCropTop, gCropWidth, gCropHeight) #left,top,width,height copy.setRoi(roi) time.sleep( 0.5 ) # otherwise, crop SOMETIMES failes. WHAT THE F**K FIJI DEVELOPERS, REALLY, WHAT THE F**K #bPrintLog('cropping', 1) IJ.run('Crop') infoStr += 'bCropping=' + str(gCropLeft) + ',' + str( gCropTop) + ',' + str(gCropWidth) + ',' + str(gCropHeight) + '\n' # # remove calibration ( on original) if gRemoveCalibration: cal = imp.getCalibration() calCoeff = cal.getCoefficients() if calCoeff: msgStr = 'Calibration is y=a+bx' + ' a=' + str( calCoeff[0]) + ' b=' + str(calCoeff[1]) bPrintLog(msgStr, 1) #remove calibration bPrintLog('\tRemoving Calibration', 2) imp.setCalibration(None) #without these, 8-bit conversion goes to all 0 !!! what the f**k !!! #bPrintLog('calling imp.resetStack() and imp.resetDisplayRange()', 2) imp.resetStack() imp.resetDisplayRange() #get and print out min/max origMin = StackStatistics(imp).min origMax = StackStatistics(imp).max msgStr = '\torig min=' + str(origMin) + ' max=' + str(origMax) bPrintLog(msgStr, 2) # 20150723, 'shift everybody over by linear calibration intercept calCoeff[0] - (magic number) if 1: # [1] was this #msgStr = 'Subtracting original min '+str(origMin) + ' from stack.' #bPrintLog(msgStr, 2) #subArgVal = 'value=%s stack' % (origMin,) #IJ.run('Subtract...', subArgVal) # [2] now this #msgStr = 'Adding calCoeff[0] '+str(calCoeff[0]) + ' from stack.' #bPrintLog(msgStr, 2) #addArgVal = 'value=%s stack' % (int(calCoeff[0]),) #IJ.run('Add...', addArgVal) # [3] subtract a magic number 2^15-2^7 = 32768 - 128 magicNumber = gLinearShift #2^15 - 128 msgStr = 'Subtracting a magic number (linear shift) ' + str( magicNumber) + ' from stack.' bPrintLog(msgStr, 2) infoStr += 'bLinearShift=' + str(gLinearShift) + '\n' subArgVal = 'value=%s stack' % (gLinearShift, ) IJ.run(imp, 'Subtract...', subArgVal) # 20150701, set any pixel <0 to 0 if 0: ip = imp.getProcessor() # returns a reference pixels = ip.getPixels() # returns a reference msgStr = '\tSet all pixels <0 to 0. This was added 20150701 ...' bPrintLog(msgStr, 2) pixels = map(lambda x: 0 if x < 0 else x, pixels) bPrintLog('\t\t... done', 2) #get and print out min/max newMin = StackStatistics(imp).min newMax = StackStatistics(imp).max msgStr = '\tnew min=' + str(newMin) + ' max=' + str(newMax) bPrintLog(msgStr, 2) #append calibration to info string infoStr += 'bCalibCoeff_a = ' + str(calCoeff[0]) + '\n' infoStr += 'bCalibCoeff_b = ' + str(calCoeff[1]) + '\n' infoStr += 'bNewMin = ' + str(newMin) + '\n' infoStr += 'bNewMax = ' + str(newMax) + '\n' # # set up if gNumChannels == 1: impWinStr = copy.getTitle() #use this when only one channel impWin = WindowManager.getWindow(impWinStr) #returns java.awt.Window if gNumChannels == 2: winTitle = copy.getTitle() bPrintLog('Deinterleaving 2 channels...', 1) IJ.run('Deinterleave', 'how=2 keep') #makes ' #1' and ' #2', with ' #2' frontmost ch1WinStr = winTitle + ' #1' ch2WinStr = winTitle + ' #2' ch1Imp = WindowManager.getImage(ch1WinStr) ch2Imp = WindowManager.getImage(ch2WinStr) ch1File = destFolder + shortName + '_ch1.tif' ch2File = destFolder + shortName + '_ch2.tif' # # alignment if gDoAlign and gNumChannels == 1 and copy.getNSlices() > 1: infoStr += 'AlignOnChannel=1' + '\n' #snap to middle slice if gAlignOnMiddleSlice: middleSlice = int( math.floor(copy.getNSlices() / 2)) #int() is necc., python is f*****g picky else: middleSlice = gAlignOnThisSlice copy.setSlice(middleSlice) transformationFile = destAlignmentFolder + shortName + '.txt' bPrintLog('MultiStackReg aligning:' + impWinStr, 1) stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' % ( impWin, transformationFile) IJ.run('MultiStackReg', stackRegParams) infoStr += 'AlignOnSlice=' + str(middleSlice) + '\n' #20150723, we just aligned on a cropped copy, apply alignment to original imp origImpTitle = imp.getTitle() stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % ( origImpTitle, transformationFile) IJ.run('MultiStackReg', stackRegParams) if gDoAlign and gNumChannels == 2 and ch1Imp.getNSlices( ) > 1 and ch2Imp.getNSlices() > 1: #apply to gAlignThisChannel alignThisWindow = '' applyAlignmentToThisWindow = '' if gAlignThisChannel == 1: infoStr += 'AlignOnChannel=1' + '\n' transformationFile = destAlignmentFolder + shortName + '_ch1.txt' alignThisWindow = ch1WinStr applyAlignmentToThisWindow = ch2WinStr else: infoStr += 'AlignOnChannel=2' + '\n' transformationFile = destAlignmentFolder + shortName + '_ch2.txt' alignThisWindow = ch2WinStr applyAlignmentToThisWindow = ch1WinStr alignThisImp = WindowManager.getImage(alignThisWindow) #snap to middle slice if gAlignOnMiddleSlice: middleSlice = int( math.floor(alignThisImp.getNSlices() / 2)) #int() is necc., python is f*****g picky else: middleSlice = gAlignOnThisSlice alignThisImp.setSlice(middleSlice) infoStr += 'bAlignOnSlice=' + str(middleSlice) + '\n' bPrintLog('MultiStackReg aligning:' + alignThisWindow, 1) stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' % ( alignThisWindow, transformationFile) IJ.run('MultiStackReg', stackRegParams) # 20150723, we just aligned on a copy, apply alignment to both channels of original # ch1 bPrintLog('MultiStackReg applying alignment to:' + origCh1WinStr, 1) stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % ( origCh1WinStr, transformationFile) IJ.run('MultiStackReg', stackRegParams) # ch2 bPrintLog('MultiStackReg applying alignment to:' + origCh2WinStr, 1) stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % ( origCh2WinStr, transformationFile) IJ.run('MultiStackReg', stackRegParams) #apply alignment to other window #bPrintLog('MultiStackReg applying alignment to:' + applyAlignmentToThisWindow, 1) #applyAlignThisImp = WindowManager.getImage(applyAlignmentToThisWindow) #stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(applyAlignmentToThisWindow,transformationFile) #IJ.run('MultiStackReg', stackRegParams) elif gDoAlign: bPrintLog('Skipping alignment, there may be only one slice?', 3) # # save if gNumChannels == 1: imp.setProperty("Info", infoStr) impFile = destFolder + shortName + '.tif' #bPrintLog('Saving:' + impFile, 1) bSaveStack(imp, impFile) #max project bSaveZProject(imp, destMaxFolder, shortName) if gNumChannels == 2: #ch1 origCh1Imp.setProperty("Info", infoStr) #bPrintLog('Saving:' + ch1File, 1) bSaveStack(origCh1Imp, ch1File) #max project bSaveZProject(origCh1Imp, destMaxFolder, shortName + '_ch1') #ch2 origCh2Imp.setProperty("Info", infoStr) #bPrintLog('Saving:' + ch2File, 1) bSaveStack(origCh2Imp, ch2File) #max project bSaveZProject(origCh2Imp, destMaxFolder, shortName + '_ch2') # # post convert to 8-bit and save if gSave8bit: if bitDepth == 16: if gNumChannels == 1: bPrintLog('Converting to 8-bit:' + impWinStr, 1) IJ.selectWindow(impWinStr) #IJ.run('resetMinAndMax()') IJ.run("8-bit") impFile = eightBitFolder + shortName + '.tif' bPrintLog('Saving 8-bit:' + impFile, 2) bSaveStack(imp, impFile) #max project bSaveZProject(imp, eightBitMaxFolder, shortName) if gNumChannels == 2: # bPrintLog('Converting to 8-bit:' + origCh1WinStr, 1) IJ.selectWindow(origCh1WinStr) IJ.run("8-bit") impFile = eightBitFolder + shortName + '_ch1.tif' bPrintLog('Saving 8-bit:' + impFile, 2) bSaveStack(origCh1Imp, impFile) #max project bSaveZProject(origCh1Imp, eightBitMaxFolder, shortName + '_ch1') # bPrintLog('Converting to 8-bit:' + origCh2WinStr, 1) IJ.selectWindow(origCh2WinStr) #IJ.run('resetMinAndMax()') IJ.run("8-bit") impFile = eightBitFolder + shortName + '_ch2.tif' bPrintLog('Saving 8-bit:' + impFile, 2) bSaveStack(origCh2Imp, impFile) #max project bSaveZProject(origCh2Imp, eightBitMaxFolder, shortName + '_ch2') # # close original window imp.changes = 0 imp.close() #copy copy.changes = 0 copy.close() # # close ch1/ch2 if gNumChannels == 2: #original origCh1Imp.changes = 0 origCh1Imp.close() origCh2Imp.changes = 0 origCh2Imp.close() #copy ch1Imp.changes = 0 ch1Imp.close() ch2Imp.changes = 0 ch2Imp.close() bPrintLog( time.strftime("%H:%M:%S") + ' finished runOneFile(): ' + fullFilePath, 1)
def main(): Interpreter.batchMode = True if (lambda_flat == 0) ^ (lambda_dark == 0): print ("ERROR: Both of lambda_flat and lambda_dark must be zero," " or both non-zero.") return lambda_estimate = "Automatic" if lambda_flat == 0 else "Manual" #import pdb; pdb.set_trace() print "Loading images..." filenames = enumerate_filenames(pattern) num_channels = len(filenames) num_images = len(filenames[0]) image = Opener().openImage(filenames[0][0]) width = image.width height = image.height image.close() # The internal initialization of the BaSiC code fails when we invoke it via # scripting, unless we explicitly set a the private 'noOfSlices' field. # Since it's private, we need to use Java reflection to access it. Basic_noOfSlices = Basic.getDeclaredField('noOfSlices') Basic_noOfSlices.setAccessible(True) basic = Basic() Basic_noOfSlices.setInt(basic, num_images) # Pre-allocate the output profile images, since we have all the dimensions. ff_image = IJ.createImage("Flat-field", width, height, num_channels, 32); df_image = IJ.createImage("Dark-field", width, height, num_channels, 32); print("\n\n") # BaSiC works on one channel at a time, so we only read the images from one # channel at a time to limit memory usage. for channel in range(num_channels): print "Processing channel %d/%d..." % (channel + 1, num_channels) print "===========================" stack = ImageStack(width, height, num_images) opener = Opener() for i, filename in enumerate(filenames[channel]): print "Loading image %d/%d" % (i + 1, num_images) image = opener.openImage(filename) stack.setProcessor(image.getProcessor(), i + 1) input_image = ImagePlus("input", stack) # BaSiC seems to require the input image is actually the ImageJ # "current" image, otherwise it prints an error and aborts. WindowManager.setTempCurrentImage(input_image) basic.exec( input_image, None, None, "Estimate shading profiles", "Estimate both flat-field and dark-field", lambda_estimate, lambda_flat, lambda_dark, "Ignore", "Compute shading only" ) input_image.close() # Copy the pixels from the BaSiC-generated profile images to the # corresponding channel of our output images. ff_channel = WindowManager.getImage("Flat-field:%s" % input_image.title) ff_image.slice = channel + 1 ff_image.getProcessor().insert(ff_channel.getProcessor(), 0, 0) ff_channel.close() df_channel = WindowManager.getImage("Dark-field:%s" % input_image.title) df_image.slice = channel + 1 df_image.getProcessor().insert(df_channel.getProcessor(), 0, 0) df_channel.close() print("\n\n") template = '%s/%s-%%s.tif' % (output_dir, experiment_name) ff_filename = template % 'ffp' IJ.saveAsTiff(ff_image, ff_filename) ff_image.close() df_filename = template % 'dfp' IJ.saveAsTiff(df_image, df_filename) df_image.close() print "Done!"
def tethered_cell(image_path, frame_number=100, frame_rate=100.0, CCW=1): """ parameter setting; frame rate (frame/sec) CCW = 1 : the motor rotation direction and the cell rotation direction on the image are same CCW = -1: the motor rotation direction and the cell rotation direction on the image are different """ opener = Opener() imp = opener.openImage(image_path) image_slice_number = imp.getNSlices() rm = RoiManager().getInstance() if image_slice_number < frame_number: # too short movie IJ.log('Number of frame of the movie is fewer than the number of frame that you selected') return False # create result directory result_path = image_path + '_tethered_cell_result' if os.path.lexists(result_path) is False: os.mkdir(result_path) #z projection; standard deviation, tethered cell shorws circle IJ.run(imp, 'Subtract Background...', 'rolling=5 light stack') IJ.run(imp, 'Median...', 'radius=2 stack') IJ.run(imp, 'Z Project...', 'stop=500 projection=[Standard Deviation]') zimp = IJ.getImage() IJ.saveAs(zimp, 'bmp', os.path.join(result_path,'STD_DEV.bmp')) # pick up tethered cell IJ.setAutoThreshold(zimp, 'MaxEntropy dark') IJ.run(zimp, 'Convert to Mask', '') IJ.run('Set Measurements...', "area centroid bounding shape feret's limit redirect=None decimal=3") IJ.run(zimp, 'Analyze Particles...', 'size=30-Infinity circularity=0.88-1.00 show=Nothing display exclude clear include') zrt = ResultsTable.getResultsTable() IJ.saveAs('Results', os.path.join(result_path,'RoiInfo.csv')) #tcX and tcY are xy coordinates of tethered cell, tcdia is outer diameter of rotating tethered cell #add ROI into stack image for i in range(zrt.getCounter()): tcX = zrt.getValue('X', i) tcY = zrt.getValue('Y', i) tcdia = zrt.getValue('Feret', i) rm.add(imp, OvalRoi(tcX - tcdia/2.0, tcY - tcdia/2.0, tcdia + 1, tcdia + 1), i) #calculate rotation speed by ellipse fitting IJ.setAutoThreshold(imp, 'Li') for roi_number in range(rm.getCount()): t = [] XM = [] YM = [] theta = [] rotation_speed = [] area = [] imp.setRoi(rm.getRoi(roi_number)) cropped_imp = Duplicator().run(imp) IJ.run('Set Measurements...', 'area mean center fit limit redirect=None decimal=3') rm.select(roi_number) rt = rm.multiMeasure(imp) # check cell is present while analysis. Don't a cell gose anywhare? for i in range(frame_number): area.append(rt.getValue('Area1', i)) if 0 in area: continue for i in range(frame_number): t.append((1/frame_rate)*i) XM.append(rt.getValue('XM1', i)) YM.append(rt.getValue('YM1', i)) theta.append(rt.getValue('Angle1', i)/180.0*math.pi) # convert to radian if i == 0: rotation_speed.append(0) else: # phase treatment, theta should be -pi ~ pi temp_rotation_speed = [theta[i] - theta[i-1], theta[i] - theta[i-1] + math.pi, theta[i] - theta[i-1] - math.pi, theta[i] - theta[i-1] + 2*math.pi, theta[i] - theta[i-1] - 2*math.pi] temp_rotation_speed = sorted(temp_rotation_speed, key = lambda x :abs(x) )[0] rotation_speed.append(CCW*temp_rotation_speed/(2.0*math.pi)*frame_rate) # write csv # earch columns indicate 1:index, 2:time(sec), 3:X-coordinate of center of mass(pixel), 4:Y-coordinate of center of mass (pixel), 5:Angle(Radian), 6:Rotation Speed(Hz) with open(os.path.join(result_path,'Roi' + str(roi_number) + '.csv'), 'w') as f: writer = csv.writer(f) writer.writerow(['Index', 'time(s)', 'X', 'Y', 'Angle(rad)', 'Rotation Speed(Hz)']) for i in range(len(t)): writer.writerow([i, t[i], XM[i], YM[i], theta[i], rotation_speed[i]]) # plot x-y, t-x, t-y, t-rotation speed, save plot as bmp plotRotation(roi_number, result_path, t, XM, YM, rotation_speed) IJ.saveAs(cropped_imp, 'tiff', os.path.join(result_path,'Roi' + str(roi_number) + '.tiff')) rt.reset() # get analysis date and time dt = datetime.datetime.today() dtstr = dt.strftime('%Y-%m-%d %H:%M:%S') # wtite analysis setting with open(os.path.join(result_path,'analysis_setting.csv'), 'w') as f: writer = csv.writer(f) writer.writerow(['Analysis Date','frame number','frame rate','CCW direction', 'Method','Auto threshold', 'Subtruct Background', 'Median filter']) writer.writerow([dtstr, frame_number, frame_rate, CCW, 'Ellipse', 'Li', '5.0', '2']) # save roi if rm.getCount() != 0: rm.runCommand('Save', os.path.join(result_path, 'Roi.zip')) zimp.close() imp.close() rm.close() zrt.reset()
def main(): # Prepare directory tree for output. indir = IJ.getDirectory("input directory") outdir = IJ.getDirectory(".csv output directory") c1dir = os.path.join(outdir, "Channel1") c2dir = os.path.join(outdir, "Channel2") c3dir = os.path.join(outdir, "Channel3") c4dir = os.path.join(outdir, "Channel4") channelsdir = os.path.join(outdir, "Channels") if not os.path.isdir(c1dir): os.mkdir(c1dir) if not os.path.isdir(c2dir): os.mkdir(c2dir) if not os.path.isdir(c3dir): os.mkdir(c3dir) if not os.path.isdir(c4dir): os.mkdir(c4dir) if not os.path.isdir(channelsdir): os.mkdir(channelsdir) # Collect all file paths in the input directory files = readdirfiles(indir) # Initialize the results tables. c1Results = ResultsTable() c2Results = ResultsTable() c3Results = ResultsTable() c4Results = ResultsTable() for file in files: IJ.log("File: {}/{}".format(files.index(file) + 1, len(files))) if file.endswith('.tif'): # Open .tiff file as ImagePlus. imp = Opener().openImage(file) imp = ZProjector.run(imp, "max") # imp = stackprocessor(file, # nChannels=4, # nSlices=7, # nFrames=1) channels = ChannelSplitter.split(imp) name = imp.getTitle() # For every channel, save the inverted channel in grayscale as .jpg. for channel in channels: IJ.run(channel, "Grays", "") IJ.run(channel, "Invert", "") jpgname = channel.getShortTitle() jpgoutfile = os.path.join(channelsdir, "{}.jpg".format(jpgname)) IJ.saveAs(channel.flatten(), "Jpeg", jpgoutfile) IJ.run(channel, "Invert", "") # OPTIONAL - Perform any other operations (e.g. crossexcitation compensation tasks) before object count. c2name = channels[2].getTitle() cal = channels[2].getCalibration() channels[2] = ImagePlus( c2name, ImageCalculator().run("divide create 32-bit", channels[2], channels[3]).getProcessor( ) # This removes AF647 bleed-through ) channels[2].setCalibration(cal) # Settings for channel1 threshold. c1 = countobjects(channels[0], c1Results, threshMethod="Triangle", subtractBackground=True, watershed=True, minSize=0.00, maxSize=100, minCirc=0.00, maxCirc=1.00) # Settings for channel2 threshold. c2 = countobjects(channels[1], c2Results, threshMethod="RenyiEntropy", subtractBackground=True, watershed=False, minSize=0.00, maxSize=30.00, minCirc=0.00, maxCirc=1.00) # Settings for channel3 threshold. c3 = countobjects(channels[2], c3Results, threshMethod="RenyiEntropy", subtractBackground=True, watershed=False, minSize=0.00, maxSize=30.00, minCirc=0.00, maxCirc=1.00) # Settings for channel4 threshold. c4 = countobjects(channels[3], c4Results, threshMethod="RenyiEntropy", subtractBackground=True, watershed=False, minSize=0.20, maxSize=100.00, minCirc=0.00, maxCirc=1.00) # Format filenames for thresholded .tiff files. outfileC1 = os.path.join(c1dir, "threshold_c1_{}".format(name)) outfileC2 = os.path.join(c2dir, "threshold_c2_{}".format(name)) outfileC3 = os.path.join(c3dir, "threshold_c3_{}".format(name)) outfileC4 = os.path.join(c4dir, "threshold_c4_{}".format(name)) # Save thresholded .tiff files. IJ.saveAs(c1.flatten(), "Tiff", outfileC1) IJ.saveAs(c2.flatten(), "Tiff", outfileC2) IJ.saveAs(c3.flatten(), "Tiff", outfileC3) IJ.saveAs(c4.flatten(), "Tiff", outfileC4) # Show results tables. # c1Results.show("channel1") # c2Results.show("channel2") # c3Results.show("channel3") # c4Results.show("channel4") # Prepare results table filenames. c1out = os.path.join(outdir, "channel1.csv") c2out = os.path.join(outdir, "channel2.csv") c3out = os.path.join(outdir, "channel3.csv") c4out = os.path.join(outdir, "channel4.csv") # Save results tables. ResultsTable.save(c1Results, c1out) ResultsTable.save(c2Results, c2out) ResultsTable.save(c3Results, c3out) ResultsTable.save(c4Results, c4out)
def runOneFile(fullFilePath): global gFileType global fileIndex if not os.path.isfile(fullFilePath): bPrintLog( '\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n', 0) return 0 bPrintLog( time.strftime("%H:%M:%S") + ' starting runOneFile(): ' + fullFilePath, 1) bPrintLog('inputfile is:' + fullFilePath, 1) enclosingPath = os.path.dirname(fullFilePath) head, tail = os.path.split( enclosingPath) #tail is name of enclosing folder enclosingPath += '/' # make output folders destFolder = enclosingPath + tail + '_short/' if not os.path.isdir(destFolder): os.makedirs(destFolder) # open if gFileType == 'tif': # open .tif image imp = Opener().openImage(fullFilePath) else: # open .lsm cmdStr = 'open=%s autoscale color_mode=Default view=Hyperstack stack_order=XYCZT' % ( fullFilePath, ) IJ.run('Bio-Formats Importer', cmdStr) lsmpath, lsmfilename = os.path.split(fullFilePath) lsWindow = lsmfilename imp = WindowManager.getImage(lsWindow) # get parameters of image (width, height, nChannels, nSlices, nFrames) = imp.getDimensions() bitDepth = imp.getBitDepth() infoStr = imp.getProperty("Info") #get all .tif tags #print 'original infoStr:', infoStr if not infoStr: infoStr = '' infoStr += 'ShortenNames_Version=' + str(gShortenVersion) + '\n' infoStr += 'ShortenNames_Time=' + time.strftime( "%Y%m%d") + '_' + time.strftime("%H%M%S") + '\n' msgStr = 'w:' + str(width) + ' h:' + str(height) + ' slices:' + str(nSlices) \ + ' channels:' + str(nChannels) + ' frames:' + str(nFrames) + ' bitDepth:' + str(bitDepth) bPrintLog(msgStr, 1) path, filename = os.path.split(fullFilePath) shortName, fileExtension = os.path.splitext(filename) #output file name outFile = destFolder + tail + '_' + str(fileIndex) + '.tif' fileIndex += 1 bPrintLog('output file is:' + outFile, 1) # put original name in header infoStr += 'ShortenNames_OriginalFile=' + fullFilePath + '\n' # put scanimage header back in imp.setProperty("Info", infoStr) #save bSaveStack(imp, outFile) # # close original window imp.changes = 0 imp.close()
straight_length, distance_from_stem_apical, angle, convexfull_area) col_name = [ "file_path", "exec_times", "roi_id", "types", "curve_length", "straight_length", "distance_from_stem_apical", "angle", "convexfull_area" ] csv_path = os.path.join(get_file_info()[0], get_file_info()[1] + "_analyze.csv") # ファイルに内容がある場合は何もせず, 内容がないときだけカラムを書き込む with open(csv_path, "a") as f1: with open(csv_path, "r") as f2: s = f2.read() if s == "": with open(csv_path, "w") as f3: writer = csv.writer(f3) writer.writerow(col_name) # 上書きモードで値を書き込む with open(csv_path, "a") as f: writer = csv.writer(f) writer.writerows(for_csv_row) # saveしたあとにoverlayに書き込んで線を青色に変える。 save_roi_set(imp=IJ.getImage()) # table上に表示する op = Opener() op.openTable(csv_path)
def main(): Interpreter.batchMode = True if (lambda_flat == 0) ^ (lambda_dark == 0): print ("ERROR: Both of lambda_flat and lambda_dark must be zero," " or both non-zero.") return lambda_estimate = "Automatic" if lambda_flat == 0 else "Manual" print "Loading images..." filenames = enumerate_filenames(pattern) if len(filenames) == 0: return # This is the number of channels inferred from the filenames. The number # of channels in an individual image file will be determined below. num_channels = len(filenames) num_images = len(filenames[0]) image = Opener().openImage(filenames[0][0]) if image.getNDimensions() > 3: print "ERROR: Can't handle images with more than 3 dimensions." (width, height, channels, slices, frames) = image.getDimensions() # The third dimension could be any of these three, but the other two are # guaranteed to be equal to 1 since we know NDimensions is <= 3. image_channels = max((channels, slices, frames)) image.close() if num_channels > 1 and image_channels > 1: print ( "ERROR: Can only handle single-channel images with {channel} in" " the pattern, or multi-channel images without {channel}. The" " filename patterns imply %d channels and the images themselves" " have %d channels." % (num_channels, image_channels) ) return if image_channels == 1: multi_channel = False else: print ( "Detected multi-channel image files with %d channels" % image_channels ) multi_channel = True num_channels = image_channels # Clone the filename list across all channels. We will handle reading # the individual image planes for each channel below. filenames = filenames * num_channels # The internal initialization of the BaSiC code fails when we invoke it via # scripting, unless we explicitly set a the private 'noOfSlices' field. # Since it's private, we need to use Java reflection to access it. Basic_noOfSlices = Basic.getDeclaredField('noOfSlices') Basic_noOfSlices.setAccessible(True) basic = Basic() Basic_noOfSlices.setInt(basic, num_images) # Pre-allocate the output profile images, since we have all the dimensions. ff_image = IJ.createImage("Flat-field", width, height, num_channels, 32); df_image = IJ.createImage("Dark-field", width, height, num_channels, 32); print("\n\n") # BaSiC works on one channel at a time, so we only read the images from one # channel at a time to limit memory usage. for channel in range(num_channels): print "Processing channel %d/%d..." % (channel + 1, num_channels) print "===========================" stack = ImageStack(width, height, num_images) opener = Opener() for i, filename in enumerate(filenames[channel]): print "Loading image %d/%d" % (i + 1, num_images) # For multi-channel images the channel determines the plane to read. args = [channel + 1] if multi_channel else [] image = opener.openImage(filename, *args) stack.setProcessor(image.getProcessor(), i + 1) input_image = ImagePlus("input", stack) # BaSiC seems to require the input image is actually the ImageJ # "current" image, otherwise it prints an error and aborts. WindowManager.setTempCurrentImage(input_image) basic.exec( input_image, None, None, "Estimate shading profiles", "Estimate both flat-field and dark-field", lambda_estimate, lambda_flat, lambda_dark, "Ignore", "Compute shading only" ) input_image.close() # Copy the pixels from the BaSiC-generated profile images to the # corresponding channel of our output images. ff_channel = WindowManager.getImage("Flat-field:%s" % input_image.title) ff_image.slice = channel + 1 ff_image.getProcessor().insert(ff_channel.getProcessor(), 0, 0) ff_channel.close() df_channel = WindowManager.getImage("Dark-field:%s" % input_image.title) df_image.slice = channel + 1 df_image.getProcessor().insert(df_channel.getProcessor(), 0, 0) df_channel.close() print("\n\n") template = '%s/%s-%%s.tif' % (output_dir, experiment_name) ff_filename = template % 'ffp' IJ.saveAsTiff(ff_image, ff_filename) ff_image.close() df_filename = template % 'dfp' IJ.saveAsTiff(df_image, df_filename) df_image.close() print "Done!"
str(MouseID) + " contains " + str(number_of_channels_in_mouse) + " distinct channels") # run the function for each of the channels for channel in range(1, (number_of_channels_in_mouse + 1)): channel_files = getChannelFiles(MouseIDFiles, channel) # get the full path chf_fpaths = [path.join(In_dir, x) for x in channel_files] # get the minimum and maximum pixel value min_pixval, max_pixval = get_enhance_bounds( chf_fpaths, low_theshold, high_threshold) IJ.log("Found pixel bounds " + str(min_pixval) + " and " + str(max_pixval) + " for channel " + str(channel)) counter = 1 for chfile in chf_fpaths: # open file ch_img = Opener().openImage(chfile) ch_tit = ch_img.getTitle() # adjust contrast ch_img.getProcessor().setMinAndMax(min_pixval, max_pixval) # convert to 8-bit (which also applies the contrast) ImageConverter(ch_img).convertToGray8() # save IJ.saveAsTiff(ch_img, path.join(Out_dir, ch_tit)) # close and flush ch_img.close() ch_img.flush() print("Image " + str(counter) + " of " + str(len(chf_fpaths)) + " processed") counter += 1 IJ.log('Mouse ' + MouseID + ' processed')
"analyzeCmStack": analyzeCmStack, "rowNo": rowNo, "colNo": colNo, "nucMinSize": nucMinSize, "cmMinSize": cmMinSize, "allFileNames": allFileNames} with open("savedSettings.json", "w+") as f: json.dump(jsonStoreDict, f) reList = [] for fileName in allFileNames: match = re.match(formatString, fileName) if match is None: continue matchDict = match.groupdict() matchDict['fileName'] = match.string reList.append(matchDict) opener = Opener() bs = BackgroundSubtracter() for outerPairs, group in getCombos(reList, groupBy).iteritems(): print(group) nucIp, cmIp = openStitched(group, rowNo, colNo) if stitched else openUnstitched(group) if nucIp is None or cmIp is None: continue nucStack, cmStack = nucIp.getStack(), cmIp.getStack() nucIpMedian = calcMedian(nucIp) IJ.run(nucIp, "Subtract...", "value=" + str(nucIpMedian) + " stack") nucIpForMeasure = nucIp.duplicate() nucMaskIp = generateNucleusMask(nucIp, nucMethod, analyzeNucStack, nucMinSize) cmIp, cmMaskIp = generateCardiomyocyteMask(cmIp, cmMethod, analyzeCmStack, cmMinSize, brightfield) nucMaskIp.show() nucIpForMeasure.show() rm = RoiManager.getRoiManager() rm.runCommand("Associate", "true")
def __init__(self, filepath): """ Load an image or stack from filepath. Args: filepath (str): Full path to an image file. Can be .tif, .lsm, .czi, etc """ if not os.path.isfile(filepath): bPrintLog('ERROR: bImp() did not find file: ' + filepath,0) return 0 self.filepath = filepath folderpath, filename = os.path.split(filepath) self.filename = filename self.enclosingPath = folderpath self.enclosingfolder = os.path.split(folderpath)[1] self.dateStr = '' self.timeStr = '' self.imp = None tmpBaseName, extension = os.path.splitext(filename) isZeiss = extension in ['.czi', '.lsm'] self.islsm = extension == '.lsm' self.isczi = extension == '.czi' istif = extension == '.tif' if istif: # scanimage3 comes in with dimensions: [512, 512, 1, 52, 1]) = [width, height, numChannels, numSlices, numFrames] self.imp = Opener().openImage(filepath) self.imp.show() elif isZeiss: #open lsm using LOCI Bio-Formats options = ImporterOptions() #options.setColorMode(ImporterOptions.COLOR_MODE_GRAYSCALE) options.setId(filepath) imps = BF.openImagePlus(options) for imp in imps: self.imp = imp #WindowManager.getImage(self.windowname) imp.show() if not self.imp: bPrintLog('ERROR: bImp() was not able to open file: '+ filepath,0) self.windowname = filename #self.imp = WindowManager.getImage(self.windowname) # numChannels is not correct for scanimage, corrected in readTiffHeader() (width, height, numChannels, numSlices, numFrames) = self.imp.getDimensions() self.width = width # pixelsPerLine self.height = height # linesPerFrame self.numChannels = numChannels self.numSlices = numSlices self.numFrames = numFrames self.infoStr = self.imp.getProperty("Info") #get all tags self.voxelx = 1 self.voxely = 1 self.voxelz = 1 #self.numChannels = 1 #self.bitsPerPixel = 8 self.zoom = 1 self.motorx = None self.motory = None self.motorz = None self.scanImageVersion = '' self.msPerLine = None self.dwellTime = None # read file headers (date, time, voxel size) if isZeiss: self.readZeissHeader(self.infoStr) elif istif: self.readTiffHeader(self.infoStr) self.updateInfoStr() self.channelWindows = [] self.channelImp = [] if self.numChannels == 1: self.channelWindows.append(self.windowname) self.channelImp.append(self.imp) else: self.deinterleave()
#find the threshold values using the quantiles percentiles = [98.5, 99.5, 99.9] thresholds = FindThreholds(In_dir, MouseIDcFos, percentiles) IJ.log('Thresholds for percentiles ' + str(percentiles) + ' selected to ' + str(thresholds)) #threshold and save images for each threshold value for i, threshold in enumerate(thresholds): # create directory Perc_Out_dir = Out_dir + "percentile_" + str(percentiles[i]) + "/" if not os.path.exists(Perc_Out_dir): os.makedirs(Perc_Out_dir) IJ.log('Processing ' + MouseID + ' for percentile ' + str(percentiles[i])) for image in MouseIDcFos: #open image imp_orig = Opener().openImage(In_dir + image) #gaussian blur imp_GB = blurImage(imp_orig) imp_orig.close() #threshold imp_GB.getProcessor().threshold(threshold) #save newname = image.split('.')[0] + '_GPT_' + str( percentiles[i]) + '.tif' IJ.saveAsTiff(imp_GB, Perc_Out_dir + newname) imp_GB.close() IJ.log('Mouse ' + MouseID + ' processed') print "DONE, find your results in " + Out_dir