def gfp_analysis(imp, file_name, output_folder): """perform analysis based on gfp intensity thresholding""" cal = imp.getCalibration() channel_imps = ChannelSplitter.split(imp) gfp_imp = channel_imps[0] gfp_imp.setTitle("GFP") threshold_imp = Duplicator().run(gfp_imp) threshold_imp.setTitle("GFP_threshold_imp") ecad_imp = channel_imps[1] ecad_imp.setTitle("E-cadherin") nuc_imp = channel_imps[2] IJ.run(threshold_imp, "Make Binary", "method=Otsu background=Dark calculate") IJ.run(threshold_imp, "Fill Holes", "") erode_count = 2 for _ in range(erode_count): IJ.run(threshold_imp, "Erode", "") threshold_imp = keep_blobs_bigger_than(threshold_imp, min_size_pix=1000) threshold_imp = my_kill_borders(threshold_imp) rois = generate_cell_rois(threshold_imp) out_stats = generate_cell_shape_results(rois, gfp_imp, cal, file_name) print("Number of cells identified = {}".format(len(out_stats))) threshold_imp.changes = False threshold_imp.close() # save output save_qc_image( imp, rois, "{}_plus_overlay.tiff".format( os.path.join(output_folder, os.path.splitext(file_name)[0]))) save_cell_rois(rois, output_folder, os.path.splitext(file_name)[0]) imp.changes = False imp.close() save_output_csv(out_stats, output_folder) return out_stats
def preprocess(filePath, fileName, fileID): global radius global circularity global size global lowerThreshold global upperThreshold global bytesInMB curr = IJ.openImage(filePath + '/' + fileName) c1, c2, c3 = ChannelSplitter.split(curr) # type: c1.show() c2.show() IJ.log("before blur: " + str(IJ.currentMemory()/bytesInMB) + " MB") IJ.run(c1,"Gaussian Blur...","sigma=%i" %radius) IJ.log("after blur: " + str(IJ.currentMemory()/bytesInMB) + " MB" + "\n") IJ.setThreshold(c1, lowerThreshold, upperThreshold) #IJ.run("Set Measurements...", "mean center redirect=C2-GT_%s-Stitch.tif decimal=1" %fileID) #IJ.run("Set Measurements...", "mean center redirect=C2-GT_A4-Stitch.tif decimal=1") IJ.run("Set Measurements...", "mean center redirect=C2-GT_%s-Stitch.tif decimal=1" %fileID) # there is a space after "redirect =" # produces 1980 cells but totally wrong measurements, record them next time when continued manually IJ.run(c1, "Analyze Particles...", "size=50.00-Infinity circularity=0.70-1.00 show=Nothing display exclude include") # I suspect that IJ.run(c1, "Analyze Particles...", "size=%s-Infinity circularity=%s-1.00 show=Nothing display exclude include" %(size, circularity)) works c1.changes = False c1.close() c2.close() return c3
def pre_process_images(image_input, timepoints): #correct drift IJ.run( image_input, "Properties...", "channels=2 slices=1 frames=" + str(timepoints) + " unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000" ) corrected_img = run_3d_drift_correct(image_input) #split channels red_corrected_img, phase_corrected_img = ChannelSplitter.split( corrected_img) #get image dimensions, set ROI remove part of flouresncent ring x_size = ImagePlus.getDimensions(red_corrected_img)[0] y_size = ImagePlus.getDimensions(red_corrected_img)[1] x_start = 0 y_start = 0 red_corrected_img.setRoi(OvalRoi(x_start, y_start, x_size, y_size)) IJ.run(red_corrected_img, "Make Inverse", "") IJ.setForegroundColor(0, 0, 0) IJ.run(red_corrected_img, "Fill", "stack") red_corrected_img.killRoi() #correcting background IJ.run( red_corrected_img, "Properties...", "channels=1 slices=" + str(timepoints) + " frames=1 unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000" ) #red_corrected_background_img = apply_rollingball(red_corrected_img, 7.0, False, False,False, False, False) testset = basic.BaSiCSettings() testset.imp = red_corrected_img testset.myShadingEstimationChoice = "Estimate shading profiles" testset.myShadingModelChoice = "Estimate both flat-field and dark-field" testset.myParameterChoice = "Manual" testset.lambda_flat = 2.0 testset.lambda_dark = 2.0 testset.myDriftChoice = "Replace with zero" testset.myCorrectionChoice = "Compute shading and correct images" test = basic.BaSiC(testset) test.run() red_corrected_background_img = test.getCorrectedImage() #change properties back and perform bleach correction IJ.run( red_corrected_background_img, "Properties...", "channels=1 slices=1 frames=" + str(timepoints) + " unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000" ) red_corrected_background_img_dup = red_corrected_background_img.duplicate() corrected_bleach = BleachCorrection_MH(red_corrected_background_img) corrected_bleach.doCorrection() return (red_corrected_background_img_dup, red_corrected_background_img)
def splitchannel(imp, chindex): nch = imp.getNChannels() print('Number of Channels: ' + str(nch)) if chindex > nch: # if nch > 1: print('Fallback : Using Channel 1') chindex = 1 imps = ChannelSplitter.split(imp) imp = imps[chindex - 1] if chindex <= nch: imps = ChannelSplitter.split(imp) imp = imps[chindex - 1] return imp
def get_analysis_ch(imp, analysis_ch): ''' Returns an ImagePlus of the channel index specified in analysis_ch ''' from ij.plugin import ChannelSplitter analysis_imp = ChannelSplitter.split(imp)[analysis_ch-1] return analysis_imp
def measure(cell): print "Opening", cell.getPpcdImageFilePath() imp = Opener().openImage(cell.getPpcdImageFilePath()) # open preprocessed Image imps = ChannelSplitter.split(imp) a = ATA() a.setSilent(True) a.segAndMeasure(imps[0], imps[1]) results = a.getLinkedArray() print results
def manual_analysis(imp, file_name, output_folder, gfp_channel_number=1, dapi_channel_number=3, red_channel_number=2, important_channel=1): """perform analysis based on manually drawn cells""" try: cal = imp.getCalibration() channel_imps = ChannelSplitter.split(imp) intensity_channel_imp = channel_imps[important_channel - 1] nuc_imp = channel_imps[dapi_channel_number - 1] nuclei_locations, full_nuclei_imp, _ = get_nuclei_locations( nuc_imp, cal, distance_threshold_um=10, size_threshold_um2=100) full_nuclei_imp.hide() rois = perform_manual_qc(imp, [], important_channel=important_channel) no_nuclei_centroids = [ get_no_nuclei_in_cell(roi, nuclei_locations) for roi in rois ] no_enclosed_nuclei = [ get_no_nuclei_fully_enclosed(roi, full_nuclei_imp) for roi in rois ] full_nuclei_imp.changes = False full_nuclei_imp.close() out_stats = generate_cell_shape_results( rois, intensity_channel_imp, cal, file_name, no_nuclei_centroids=no_nuclei_centroids, no_enclosed_nuclei=no_enclosed_nuclei) if gfp_channel_number is None: for idx, cell_shape_result in enumerate(out_stats): cell_shape_result.cell_gfp_I_mean = 0 cell_shape_result.cell_gfp_I_sd = 0 out_stats[idx] = cell_shape_result print("Number of cells identified = {}".format(len(out_stats))) for ch in range(imp.getNChannels()): imp.setC(ch + 1) IJ.run(imp, "Enhance Contrast", "saturated={}".format(0.35)) # save output save_qc_image( imp, rois, "{}_plus_overlay.tiff".format( os.path.join(output_folder, os.path.splitext(file_name)[0]))) save_cell_rois(rois, output_folder, os.path.splitext(file_name)[0]) imp.changes = False imp.close() save_output_csv(out_stats, output_folder) except Exception as e: print("Ran into a problem analysing {}: {}. Skipping to next cell...". format(file_name, e.message)) out_stats = [] return out_stats
def splitchannel(imp, chindex): nch = imp.getNChannels() print('Number of Channels: ' + str(nch)) # extract the channel if there are more than one if nch > 1: imps = ChannelSplitter.split(imp) imp = imps[chindex - 1] return imp
def run(): srcDir = DirectoryChooser("Chose Source Dir").getDirectory() if srcDir is None: IJ.log("Choose Dir Canceled!") return outDir = DirectoryChooser("Chose >Output< Dir").getDirectory() if outDir is None: IJ.log("Output to same dir as source.") ourtDir = srcDir refImageId = getRefIdDialog() if refImageId is None: IJ.log("Select Reference Image Canceled!") return for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Skip non-ND2 files if not filename.endswith(".nd2"): continue inpath = os.path.join(root, filename) # outfn = "reg_" + os.path.splitext(filename)[0] + ".tif" # outpath = os.path.join(outDir, outfn) # if os.path.exists(outpath): # print "Skipped, already exists: ", outfn # continue IJ.log("Registering\n" + filename) imp = regBf(fn=inpath, refId=refImageId) if imp is None: IJ.log("Skipped, wrong with registration:\n" + filename) continue else: # fs = FileSaver(imp) # fs.saveAsTiffStack(outpath) # IJ.saveAsTiff(imp, outpath) # print "Registered and saved to ", outfn splittedimps = ChannelSplitter.split(imp) for i, simp in enumerate(splittedimps): outfn = "reg_" + os.path.splitext( filename)[0] + "_C_" + str(i) + ".tif" outpath = os.path.join(outDir, outfn) if os.path.exists(outpath): IJ.log("Skipped saving, file already exists:\n" + outfn) continue IJ.saveAsTiff(simp, outpath) IJ.log("Registered and saved to\n" + outfn) IJ.log("done!")
def run(): srcDir = DirectoryChooser("Chose Source Dir").getDirectory() if srcDir is None: IJ.log("Choose Dir Canceled!") return outDir = DirectoryChooser("Chose >Output< Dir").getDirectory() if outDir is None: IJ.log("Output to same dir as source.") ourtDir = srcDir refImageId = getRefIdDialog() if refImageId is None: IJ.log("Select Reference Image Canceled!") return for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Skip non-ND2 files if not filename.endswith(".nd2"): continue inpath = os.path.join(root, filename) # outfn = "reg_" + os.path.splitext(filename)[0] + ".tif" # outpath = os.path.join(outDir, outfn) # if os.path.exists(outpath): # print "Skipped, already exists: ", outfn # continue IJ.log("Registering\n" + filename) imp = regBf(fn=inpath, refId=refImageId) if imp is None: IJ.log("Skipped, wrong with registration:\n" + filename) continue else: # fs = FileSaver(imp) # fs.saveAsTiffStack(outpath) # IJ.saveAsTiff(imp, outpath) # print "Registered and saved to ", outfn splittedimps = ChannelSplitter.split(imp) for i, simp in enumerate(splittedimps): outfn = "reg_" + os.path.splitext(filename)[0] + "_C_" + str(i) + ".tif" outpath = os.path.join(outDir, outfn) if os.path.exists(outpath): IJ.log("Skipped saving, file already exists:\n" + outfn) continue IJ.saveAsTiff(simp, outpath) IJ.log("Registered and saved to\n" + outfn) IJ.log("done!")
def main(): files = [] for filt in img_extensions.split(";"): if len(filt.strip()) > 0: files += glob.glob(os.path.join(str(input_dir), filt.strip())) else: files += glob.glob(os.path.join(str(input_dir), "*.*")) break if len(files) == 0: IJ.showMessage("No files found in '{}'\nfor extensions '{}'".format( str(input_dir), img_extensions)) else: for fn in files: try: imp = BF.openImagePlus(fn)[0] except: IJ.showMessage( "Could not open file '{}' (skipping).\nUse extension filter to filter non-image files..." .format(str(fn))) continue img = IJF.wrap(imp) cali = imp.getCalibration().copy() if pixel_width > 0: cali.pixelWidth = pixel_width cali.pixelHeight = pixel_width cali.setUnit("micron") if frame_interval > 0: cali.frameInterval = frame_interval cali.setTimeUnit("sec.") imp_out = smooth_temporal_gradient(ops, img, sigma_xy, sigma_t, frame_start, frame_end, normalize_output) imp_out.setCalibration(cali) channels = ChannelSplitter.split(imp_out) fn_basename = os.path.splitext(fn)[0] IJ.save(channels[0], "{}_shrinkage.tiff".format(fn_basename)) IJ.save(channels[1], "{}_growth.tiff".format(fn_basename)) print("{} processed".format(fn_basename)) IJ.showMessage( "Growth/shrinkage extraction of {} inputs finsihed.".format( len(files)))
def split_image(file_): print "Processing: %s" %(basename(file_)) #load with loci (allows also to load *.czi) images = BF.openImagePlus(file_) image = images[0] #split channels chSp = ChannelSplitter() title = splitext(image.title)[0] imageC = chSp.split(image) print "Number of channels: ", len(imageC) for iCh in range(0, len(imageC)): imageStack = imageC[iCh].getImageStack() for iSlice in range(0,imageC[0].getNSlices()): #print iSlice impOut = ImagePlus("outImg", imageStack.getProcessor(iSlice+1)) ntitle = to_wellbased_nameing_scheme(title, iCh+1, iSlice+1) IJ.log("Image: %s -> %s " %(title, ntitle)) IJ.saveAs(impOut, "Tiff", join(outdir, ntitle) )
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)) # Put your processing commands here! imps = ChannelSplitter.split(imp) impG = imps[1] # Saving the image saveDir = currentDir.replace(srcDir, dstDir) if keepDirectories else dstDir if not os.path.exists(saveDir): os.makedirs(saveDir) print "Saving to", saveDir savefilename = "Green_" + fileName IJ.saveAs(impG, "Tiff", os.path.join(saveDir, savefilename))
def preprocess(cell): print cell.getRawImageFilePath() imp = Opener().openImage(cell.getRawImageFilePath()) # open raw Image #if imp.getBitDepth() != 8: # converting to 8 bit if # ImageConverter(imp).convertToGray8() roi = imp.roi imps = CS.split(imp) p = Preprocessor() for aimp in imps: p.setImp(aimp) p.run() if roi != None: aimp.setRoi(roi) for n in range(1, aimp.getImageStackSize()+1): aimp.getImageStack().getProcessor(n).fillOutside(roi) aimp.killRoi() final = StackMerge.mergeChannels(imps, False) final.copyScale(imp) # copyscale from .copyscale return final
def shading_correction(infile, threshold): # Create artificial shading for stiching collection optimisation default_options = "stack_order=XYCZT color_mode=Grayscale view=Hyperstack" IJ.run("Bio-Formats Importer", default_options + " open=[" + infile + "]") imp = IJ.getImage() cal = imp.getCalibration() current = ChannelSplitter.split(imp) for c in xrange(0, len(current)): results = [] for i in xrange(0, imp.getWidth()): roi = Line(0, i, imp.getWidth(), i) current[c].show() current[c].setRoi(roi) temp = IJ.run(current[c], "Reslice [/]...", "output=0.054 slice_count=1 rotate avoid") temp = IJ.getImage() ip = temp.getProcessor().convertToShort(True) pixels = ip.getPixels() w = ip.getWidth() h = ip.getHeight() row = [] for j in xrange(len(pixels)): row.append(pixels[j]) if j % w == w - 1: results.append(int(percentile(sorted(row), threshold))) row = [] reslice_names = "Reslice of C" + str(c + 1) + "-" + imp.getTitle() reslice_names = re.sub(".ids", "", reslice_names) IJ.selectWindow(reslice_names) IJ.run("Close") imp2 = IJ.createImage("shading_ch" + str(c + 1), "16-bit black", imp.getHeight(), imp.getWidth(), 1) pix = imp2.getProcessor().getPixels() for i in range(len(pix)): pix[i] = results[i] imp2.show() name = 'ch' + str(c + 1) + imp.getTitle() IJ.run(imp2, "Bio-Formats Exporter", "save=" + os.path.join(folder10, name)) IJ.selectWindow("shading_ch" + str(c + 1)) IJ.run('Close') IJ.selectWindow("C" + str(c + 1) + "-" + imp.getTitle()) IJ.run('Close')
def split_image_plus(imp, params): """split original ImagePlus by channel, and assign an image to segment on""" split_channels = ChannelSplitter.split(imp) membrane_channel_imp = split_channels[params.membrane_channel_number - 1] segmentation_channel_imp = Duplicator().run(membrane_channel_imp) if params.use_single_channel: actin_channel = params.membrane_channel_number actin_channel_imp = Duplicator().run(membrane_channel_imp) else: if imp.getNChannels() >= 2: actin_channel = (params.membrane_channel_number + 1) % imp.getNChannels() actin_channel_imp = split_channels[actin_channel - 1] else: actin_channel = params.membrane_channel_number actin_channel_imp = Duplicator().run(membrane_channel_imp) split_channels = [ membrane_channel_imp, actin_channel_imp, segmentation_channel_imp ] return split_channels
def convertAndSaveFile(fullFilePath, convertTo8Bit=False, allowOverwrite=False): """ """ print(' convertAndSaveFile() fullFilePath:', fullFilePath) folderPath, fileName = os.path.split(fullFilePath) fileNameNoExtension = os.path.splitext(fileName)[0] saveFileNoExtension = os.path.join(folderPath, fileNameNoExtension) # # load file and build a dict of parameters like (channels, pixels, voxels) myFileInfo, imp = bSimpleFileInfo.myLoadFile(fullFilePath, doShow=True) if convertTo8Bit: # from (ImagePlus.GRAY8, ImagePlus.GRAY16, ImagePlus.GRAY32, ImagePlus.COLOR_256 or ImagePlus.COLOR_RGB) myType = imp.getType() if myType in [1,2]: ic = ImageConverter(imp) # converts channelImp in place scaleConversions = True ic.setDoScaling(scaleConversions) # scales inensities to fill 0...255 ic.convertToGray8() # # split channels channelArray = ChannelSplitter.split(imp) # returns an array of imp for channelIdx, channelImp in enumerate(channelArray): # channelImp is an imp, this will NOT have fileinfo (we just created it) #channelImp.show() saveFilePath = saveFileNoExtension + '_ch' + str(channelIdx+1) + '.tif' print(' ch:', channelIdx+1, 'saveFilePath:', saveFilePath) if not allowOverwrite and os.path.isfile(saveFilePath): print(' . not saving, file already exists', saveFilePath) else: IJ.save(channelImp, saveFilePath) return myFileInfo
def manual_analysis(imp, file_name, output_folder): """perform analysis based on manually drawn cells""" cal = imp.getCalibration() channel_imps = ChannelSplitter.split(imp) gfp_imp = channel_imps[0] IJ.setTool("freehand") proceed = False roim = RoiManager() roim.runCommand("Show all with labels") dialog = NonBlockingGenericDialog("Perform manual segmentation") dialog.setOKLabel("Proceed to next image...") dialog.addMessage("Perform manual segmentation: ") dialog.addMessage( "Draw around cells and add to the region of interest manager (Ctrl+T)") dialog.addMessage( "You can see what you've added so far if you check \"show all\" on the ROI manager" ) dialog.addMessage( "Then press \"proceed to next image\" when all cells have been added") dialog.showDialog() if dialog.wasCanceled(): raise KeyboardInterrupt("Run canceled") elif dialog.wasOKed(): rois = roim.getRoisAsArray() roim.reset() roim.close() out_stats = generate_cell_shape_results(rois, gfp_imp, cal, file_name) print("Number of cells identified = {}".format(len(out_stats))) # save output save_qc_image( imp, rois, "{}_plus_overlay.tiff".format( os.path.join(output_folder, os.path.splitext(file_name)[0]))) save_cell_rois(rois, output_folder, os.path.splitext(file_name)[0]) imp.changes = False imp.close() save_output_csv(out_stats, output_folder) return out_stats return None
def main(): # Prepare directory tree for output. indir = IJ.getDirectory("input directory") outdir = IJ.getDirectory(".csv output directory") nucdir = os.path.join(outdir, "nuclei") bacdir = os.path.join(outdir, "bacteria") rufdir = os.path.join(outdir, "ruffles") gfpdir = os.path.join(outdir, "gfp") channelsdir = os.path.join(outdir, "channels") if not os.path.isdir(nucdir): os.mkdir(nucdir) if not os.path.isdir(bacdir): os.mkdir(bacdir) if not os.path.isdir(rufdir): os.mkdir(rufdir) if not os.path.isdir(gfpdir): os.mkdir(gfpdir) if not os.path.isdir(channelsdir): os.mkdir(channelsdir) # Collect all file paths in the input directory files = readdirfiles(indir) nucResults = ResultsTable() bacResults = ResultsTable() rufResults = ResultsTable() gfpResults = ResultsTable() for file in files: if file.endswith('ome.tif') or file.endswith('ome.tiff'): imp = stackprocessor(file, nChannels=4, nSlices=7, nFrames=1) channels = ChannelSplitter.split(imp) name = imp.getTitle() IJ.log("Processing image: {}".format(name)) for c in range(len(channels)): IJ.run(channels[c], "Grays", "") IJ.run(channels[c], "Invert", "") jpgname = channels[c].getShortTitle() jpgoutfile = os.path.join(channelsdir, "{}.jpg".format(jpgname)) IJ.saveAs(channels[c].flatten(), "Jpeg", jpgoutfile) IJ.run(channels[c], "Invert", "") nuc = countobjects(channels[0], nucResults, threshMethod="Triangle", subtractBackground=True, # dilate=True, watershed=True, minSize=3.00, maxSize=100, minCirc=0.00, maxCirc=1.00) bac = countobjects(channels[1], bacResults, threshMethod="RenyiEntropy", subtractBackground=False, watershed=False, minSize=0.20, maxSize=30.00, minCirc=0.00, maxCirc=1.00) ruf = countobjects(channels[2], rufResults, threshMethod="RenyiEntropy", minSize=2.00, maxSize=30.00, minCirc=0.20, maxCirc=1.00) gfp = countobjects(channels[3], gfpResults, threshMethod="RenyiEntropy", subtractBackground=False, watershed=True, minSize=0.20, maxSize=30.00, minCirc=0.00, maxCirc=1.00) # binaries = [nuc, bac, ruf, gfp] # channels[0].show() # binaries[0].show() # binMontage = RGBStackMerge().mergeChannels(binaries, False) # binMontage.show() # chsMontage = RGBStackMerge().mergeChannels(channels, False) # binMontage = MontageMaker().makeMontage2(binMontage, # 4, # int columns # 4, # int rows # 1.00, # double scale # 1, # int first # 16, # int last # 1, # int inc # 0, # int borderWidth # False) # boolean labels) # chsMontage = MontageMaker().makeMontage2(chsMontage, # 4, # int columns # 4, # int rows # 1.00, # double scale # 1, # int first # 16, # int last # 1, # int inc # 0, # int borderWidth # False) # boolean labels) # # binMontage.show() # chsMontage.show() outfilenuc = os.path.join(nucdir, "threshold_nuc_{}".format(name)) outfilebac = os.path.join(bacdir, "threshold_bac_{}".format(name)) outfileruf = os.path.join(rufdir, "threshold_ruf_{}".format(name)) outfilegfp = os.path.join(gfpdir, "threshold_gfp_{}".format(name)) IJ.saveAs(nuc.flatten(), "Tiff", outfilenuc) IJ.saveAs(bac.flatten(), "Tiff", outfilebac) IJ.saveAs(ruf.flatten(), "Tiff", outfileruf) IJ.saveAs(gfp.flatten(), "Tiff", outfilegfp) nucResults.show("nuclei") bacResults.show("bacteria") rufResults.show("ruffles") gfpResults.show("gfp") nucout = os.path.join(outdir, "nuclei.csv") bacout = os.path.join(outdir, "bacteria.csv") rufout = os.path.join(outdir, "ruffles.csv") gfpout = os.path.join(outdir, "gfp.csv") ResultsTable.save(nucResults, nucout) ResultsTable.save(bacResults, bacout) ResultsTable.save(rufResults, rufout) ResultsTable.save(gfpResults, gfpout)
theImage = IJ.getImage() gd = GenericDialog("Options...") channelText = [("Channel " + str(ch+1)) for ch in range(theImage.getNChannels())] gd.addChoice("Amplified_channel",channelText,channelText[0]) gd.addChoice("Reference_channel",channelText,channelText[-1]) gd.addNumericField("Amplifying_ratio",1,0) gd.addCheckbox("Remove_bleedthrough",True) gd.addCheckbox("Correct_for_refraction",True) gd.showDialog() if gd.wasOKed(): amplifyChannel = gd.getNextChoiceIndex() + 1 refChannel = gd.getNextChoiceIndex() + 1 ampFactor = gd.getNextNumber() doRemoveBleedthrough = gd.getNextBoolean() doCorrectRefraction = gd.getNextBoolean() chImages = ChannelSplitter.split(theImage) ## After this step, the image to operate on is "nextStepImage" if doRemoveBleedthrough: params = ("bleeding_channel=" + str(refChannel) + " bloodied_channel=" + str(amplifyChannel) + " " + "allowable_saturation_percent=1.0 rsquare_threshold=0.50") IJ.run("Remove Bleedthrough (automatic)", params) unbledImage = WindowManager.getImage("Corrected_ch" + str(amplifyChannel)) mergingImages = [unbledImage,chImages[refChannel-1].duplicate()] nextStepImage = RGBStackMerge.mergeChannels(mergingImages,True) #nextStepImage.show() unbledImage.close() for img in mergingImages: img.close() else: mergingImages = [chImages[amplifyChannel-1].duplicate(),chImages[refChannel-1].duplicate()]
def getThresholdedMask(currIP, c, z, t, chanName, cfg, wellPath, dbgOutDesc): if (cfg.hasValue(ELMConfig.upperLeftExclusionX)): ulExclusionX = cfg.getValue(ELMConfig.upperLeftExclusionX) else: ulExclusionX = 0 if (cfg.hasValue(ELMConfig.upperLeftExclusionY)): ulExclusionY = cfg.getValue(ELMConfig.upperLeftExclusionY) else: ulExclusionY = 0 if (cfg.hasValue(ELMConfig.lowerRightExclusionX)): lrExclusionX = cfg.getValue(ELMConfig.lowerRightExclusionX) else: lrExclusionX = currIP.getWidth() if (cfg.hasValue(ELMConfig.lowerRightExclusionY)): lrExclusionY = cfg.getValue(ELMConfig.lowerRightExclusionY) else: lrExclusionY = currIP.getHeight() imgType = currIP.getType() if (chanName in cfg.getValue( ELMConfig.chansToSkip)): # Don't process skip channels currIP.close() return None elif imgType == ImagePlus.COLOR_RGB or imgType == ImagePlus.COLOR_256: if (chanName == ELMConfig.BRIGHTFIELD): toGray = ImageConverter(currIP) toGray.convertToGray8() if cfg.params[ELMConfig.imgType] == "png": darkBackground = True else: darkBackground = False elif (chanName == ELMConfig.BLUE) \ or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED) \ or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN): # chanIdx = 2 if (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED): chanIdx = 0 elif (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN): chanIdx = 1 imgChanns = ChannelSplitter.split(currIP) currIP.close() currIP = imgChanns[chanIdx] # Clear the Exclusion zone, so it doesn't mess with thresholding imgProc = currIP.getProcessor() imgProc.setColor(Color(0, 0, 0)) imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(), currIP.getHeight()) imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY) darkBackground = True elif (chanName == ELMConfig.YELLOW): # Clear the Exclusion zone, so it doesn't mess with thresholding imgProc = currIP.getProcessor() imgProc.setColor(Color(0, 0, 0)) imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(), currIP.getHeight()) imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY) # Create a new image that consists of the average of the red & green channels title = currIP.getTitle() width = currIP.getWidth() height = currIP.getHeight() newPix = ByteProcessor(width, height) for x in range(0, width): for y in range(0, height): currPix = currIP.getPixel(x, y) newPix.putPixel(x, y, (currPix[0] + currPix[1]) / 2) currIP.close() currIP = ImagePlus(title, newPix) darkBackground = True else: print "ERROR: Unrecognized channel name! Name: " + chanName currIP.close() return None elif imgType == ImagePlus.GRAY16 or imgType == ImagePlus.GRAY32 or imgType == ImagePlus.GRAY8: if (chanName == ELMConfig.BRIGHTFIELD): if cfg.params[ELMConfig.imgType] == "png": darkBackground = True else: darkBackground = False else: darkBackground = True if not imgType == ImagePlus.GRAY8: toGray = ImageConverter(currIP) toGray.convertToGray8() else: print "ERROR: Unrecognized channel name & image type! Channel: " + chanName + ", imgType: " + str( imgType) currIP.close() return None WindowManager.setTempCurrentImage(currIP) if cfg.getValue(ELMConfig.debugOutput): IJ.saveAs('png', os.path.join(wellPath, "Processing_" + dbgOutDesc + ".png")) upperThreshImg = currIP.duplicate() # If threshold value is set, use it if (cfg.hasValue(ELMConfig.imageThreshold)): thresh = cfg.getValue(ELMConfig.imageThreshold) if (darkBackground): currIP.getProcessor().setThreshold(thresh, 255, ImageProcessor.NO_LUT_UPDATE) else: currIP.getProcessor().setThreshold(0, thresh, ImageProcessor.NO_LUT_UPDATE) else: # Otherise, automatically compute threshold threshMethod = "Default" if cfg.hasValue(ELMConfig.thresholdMethod): threshMethod = cfg.getValue(ELMConfig.thresholdMethod) currIP.getProcessor().setAutoThreshold(threshMethod, darkBackground, ImageProcessor.NO_LUT_UPDATE) threshRange = currIP.getProcessor().getMaxThreshold( ) - currIP.getProcessor().getMinThreshold() #print "\t\tZ = " + str(z) + ", T = " + str(t) + ", chan " + chanName + ": Using default threshold of minThresh: " + str(currIP.getProcessor().getMinThreshold()) + ", maxThresh: " + str(currIP.getProcessor().getMaxThreshold()) if currIP.getType() != ImagePlus.GRAY8: print "\tChannel " + chanName + " is not GRAY8, instead type is %d" % currIP.getType( ) if threshRange > cfg.getValue(ELMConfig.maxThreshRange): if (cfg.hasValue(ELMConfig.defaultThreshold)): thresh = cfg.getValue(ELMConfig.defaultThreshold) print "\t\tZ = " + str(z) + ", T = " + str( t ) + ", chan " + chanName + ": Using default threshold of " + str( thresh) + ", minThresh: " + str(currIP.getProcessor( ).getMinThreshold()) + ", maxThresh: " + str( currIP.getProcessor().getMaxThreshold()) if (darkBackground): currIP.getProcessor().setThreshold( thresh, 255, ImageProcessor.NO_LUT_UPDATE) else: currIP.getProcessor().setThreshold( 0, thresh, ImageProcessor.NO_LUT_UPDATE) else: print "\t\tZ = " + str(z) + ", T = " + str( t ) + ", chan " + chanName + ": Ignored Objects due to threshold range! minThresh: " + str( currIP.getProcessor().getMinThreshold( )) + ", maxThresh: " + str( currIP.getProcessor().getMaxThreshold()) currIP.close() return None IJ.run(currIP, "Convert to Mask", "") # Clear out exclusion zones imgProc = currIP.getProcessor() imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(), currIP.getHeight()) imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY) IJ.run(currIP, "Close-", "") # Brightfield has an additional thresholding step if cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.BRIGHTFIELD: if cfg.getValue(ELMConfig.debugOutput): IJ.saveAs( 'png', os.path.join(wellPath, "OrigMask_" + dbgOutDesc + ".png")) upperThresh = 255 * 0.95 upperThreshImg.getProcessor().setThreshold( upperThresh, 255, ImageProcessor.NO_LUT_UPDATE) IJ.run(upperThreshImg, "Convert to Mask", "") IJ.run(upperThreshImg, "Close-", "") if cfg.getValue(ELMConfig.debugOutput): WindowManager.setTempCurrentImage(upperThreshImg) IJ.saveAs( 'png', os.path.join(wellPath, "UpperThreshMask_" + dbgOutDesc + ".png")) ic = ImageCalculator() compositeMask = ic.run("OR create", currIP, upperThreshImg) IJ.run(compositeMask, "Close-", "") currIP.close() currIP = compositeMask WindowManager.setTempCurrentImage(currIP) if cfg.getValue(ELMConfig.debugOutput): WindowManager.setTempCurrentImage(currIP) IJ.saveAs('png', os.path.join(wellPath, "Binary_" + dbgOutDesc + ".png")) upperThreshImg.close() return currIP
subfolders = [""] for subfolder in subfolders: #Opens each image for filename in os.listdir(inputDirectory + subfolder): imp = IJ.openImage(inputDirectory + subfolder + '/' + filename) if imp: #IJ.run(imp, "Properties...", "channels=1 slices=1 frames=1 unit=um pixel_width=0.87" "pixel_height=0.87" "voxel_depth=25400.0508001") # Splits channels channels = ChannelSplitter.split(imp); # Measures each channel #Summary contains the information for a row for the current image summary = {} summary['Directory'] = inputDirectory + subfolder summary['Filename'] = filename #Color keeps the names for each channel color = ["Red", "Green", "Blue"] for i, channel in enumerate(channels):
rm = RoiManager() rm.reset() # Process images for impfile in file_list: # open image imp = IJ.openImage(os.path.join(input_folder, impfile)) imp.show() impname = impfile.strip('.tif') imp_details = impname.split('_') stain, mutant, pos_number = imp_details print mutant, stain, pos_number imps = ChannelSplitter.split(imp) # Process cell ROIs rm = cell_processor(imp_particles=imps[3], imp_measure=imps[2], folder=folder, impname=impname, channel_name='GFP_cells') pixel_collector(rm, imps[3], 'cyto_mCherry_cells', impname, folder) pixel_collector(rm, imps[4], 'inc_mCherry_cells', impname, folder) rm.reset() ## Process nuclei image imps_thresh = ChannelSplitter.split(imp) nuclei_processor(imp_particles=imps_thresh[0], thresh_type='Otsu dark',
outDir = DirectoryChooser("Batch Splitter: Chose >Output< Dir").getDirectory() if outDir is None: print "Output to same dir as source." ourtDir = srcDir for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Skip non-TIF files if not filename.endswith(".tif"): continue inpath = os.path.join(root, filename) print "Reading ", filename imp = IJ.openImage(inpath) if imp is None: print "Skipped, wrong with reading: ", filename continue else: splittedimps = ChannelSplitter.split(imp) for i, simp in enumerate(splittedimps): outfn = os.path.splitext(filename)[0] + "_C_" + str(i) + ".tif" outpath = os.path.join(outDir, outfn) if os.path.exists(outpath): print "Skipped, already exists: ", outfn continue IJ.saveAsTiff(simp, outpath) print "Splitted and saved to ", outfn print "done."
for file in os.listdir(tiff_path): if test_counter > 1: break IJ.log(file) test_counter+=1 """ """ THIS WORKS, COMMENTED OUT FOR NOW CUZ SLOW infile = "D:/A3 Exp/sub exp/GT A3_Stitch.tif" curr_image = IJ.openImage(infile) # type: imagePlus curr_image.show() """ prolif_counter, iffy_counter, senescent_counter = 1, 1, 1 curr = IJ.openImage("D:/Stem_Cells/All_Tiff_Files/GT_A5-Stitch.tif") IJ.log(str(type(curr))) c1, c2, c3 = ChannelSplitter.split(curr) length, height = 200, 200 batch_folder = "Batch_1" #.show() #IJ.log("num channels of curr_image: " + str(curr_image.nChannels)) #curr_image.setActiveChannels("011") #IJ.log("type of curr_image:" + str(type(curr_image))) # ///How open only if not alreayd open/// IJ.log("opened\n") csv_file = open('D:/Stem_Cells/A3_Exp/sub_exp/A5.csv') csv_reader = csv.reader(csv_file) # hardcoded is fine for now
def ecad_analysis(imp, file_name, output_folder, gfp_channel_number=1, dapi_channel_number=3, red_channel_number=2, do_manual_qc=False): """perform analysis based on marker-driven watershed of junction labelling image""" cal = imp.getCalibration() channel_imps = ChannelSplitter.split(imp) ecad_imp = channel_imps[red_channel_number - 1] ecad_imp.setTitle("E-cadherin") if gfp_channel_number is not None: gfp_imp = channel_imps[gfp_channel_number - 1] gfp_imp.setTitle("GFP") else: gfp_imp = Duplicator().run(ecad_imp) gfp_imp.setTitle("GFP") threshold_imp = Duplicator().run(ecad_imp) threshold_imp.setTitle("Ecad_threshold_imp") nuc_imp = channel_imps[dapi_channel_number - 1] nuclei_locations, full_nuclei_imp, ws_seed_imp = get_nuclei_locations( nuc_imp, cal, distance_threshold_um=10, size_threshold_um2=100) full_nuclei_imp.hide() binary_cells_imp = generate_cell_masks(ws_seed_imp, ecad_imp, find_edges=True) ws_seed_imp.changes = False ws_seed_imp.close() rois = generate_cell_rois(binary_cells_imp) binary_cells_imp.changes = False binary_cells_imp.close() if do_manual_qc: print("gfp_channel_number= {}".format(gfp_channel_number)) print("red_channel_number = {}".format(red_channel_number)) manual_qc_rois = perform_manual_qc( imp, rois, important_channel=red_channel_number) if manual_qc_rois is not None: rois = manual_qc_rois no_nuclei_centroids = [ get_no_nuclei_in_cell(roi, nuclei_locations) for roi in rois ] no_enclosed_nuclei = [ get_no_nuclei_fully_enclosed(roi, full_nuclei_imp) for roi in rois ] full_nuclei_imp.changes = False full_nuclei_imp.close() out_stats = generate_cell_shape_results( rois, gfp_imp, cal, file_name, no_nuclei_centroids=no_nuclei_centroids, no_enclosed_nuclei=no_enclosed_nuclei) if gfp_channel_number is None: for idx, cell_shape_result in enumerate(out_stats): cell_shape_result.cell_gfp_I_mean = 0 cell_shape_result.cell_gfp_I_sd = 0 out_stats[idx] = cell_shape_result print("Number of cells identified = {}".format(len(out_stats))) # save output save_qc_image( imp, rois, "{}_plus_overlay.tiff".format( os.path.join(output_folder, os.path.splitext(file_name)[0]))) save_cell_rois(rois, output_folder, os.path.splitext(file_name)[0]) imp.changes = False imp.close() save_output_csv(out_stats, output_folder) return out_stats
def analyse(cwd, user, imagefolder, stats, experiments, multi, Rloc2, subfoldernames, names, statsfolderPath, cwdR): """ Main image analysis Gets user image analysis settings from the .csv file. If multiple experiments have been selected by the user (multi) each subfolder will be looped through. A nested loop will then interate through each .tif image and analyse. A .csv file will be produced for each folder analysed with the name of each image and its % neurite density and % myelination. A summary csv file will also be produced with the average % neurite density and % myelination for each subfolder. If statistical analysis has been selected (stats) then MyelinJ's Rscript will be run via the command line. If multple experiments is not selected then all of the images within the selected folder will be analysed together and no summary .csv will be produced. Independ of the analysis settings defined, a processed myelin channel image and a processed neurite channel image will be saved. The images can be any number of subdirectories (folders within folders). Parameters ---------- cwd : string Path for current working directory (location of MyelinJ folder in Fiji). user: string User name imagefolder: string Path to .tiff image folder(s) defined by user. stats: boolean Perform statistical analysing using R? experiments: 2D list of strings list of all the subfolders (experiments) that are in each experimental condition. multi: boolean Analyse multiple experiments? Rloc2: string file path to Rscript location subfoldernames: string name of each subfolder which denoates each individual experiment, if multple experiments are being analysed. names: array array of textfields for each experimental condition defined by user. User will enter the name of each experimental condition. statsfolderPath: string file path to the create statsfolder. cwdR: string file path to MyelinJstats.R """ # read settings from the user name CSV bg = False readsettings = [] imagenames = [] neuritedensity = [] myelinoverlay = [] myelinaverage2 = [] neuriteaverage2 = [] root = cwd filename = user fullpath = os.path.join(root, filename) f = open(fullpath, 'rb') readCSV = csv.reader(f) for row in readCSV: readsettings.append(row[0]) readsettings.append(row[1]) readsettings.append(row[2]) readsettings.append(row[3]) readsettings.append(row[4]) readsettings.append(row[5]) readsettings.append(row[6]) f.close() i = 0 for i in range(len(subfoldernames)): # if multiple experimental conditions has been selected each folder is treated as a # separate experiment and looped through separately otherwise all folders will be # treated as one experiment this only works for sub directories within the main folder. # Further folders will be ignored (each image can be in its own folder for example) if multi is True: # if multiple experiments are being analysed the file path is changed to the # current subfolder settings2 = os.path.join(imagefolder, subfoldernames[i]) if "Windows" in OS: settings2 = settings2 + "\\" elif "Mac" in OS: settings2 = settings2 + "/" else: settings2 = imagefolder # loop through all .tiff files in location for root, dirs, files in os.walk(settings2): for name in files: if name.endswith((".tif")): imagenames.append(os.path.join(name)) # open .tiff image, split channels and # convert to 8bit grey scale. imp = IJ.openImage(os.path.join(root, name)) g = int(readsettings[4]) r = int(readsettings[5]) imp = ChannelSplitter.split(imp) green = imp[g] red = imp[r] conv = ImageConverter(red) conv.convertToGray8() conv = ImageConverter(green) conv.convertToGray8() # thresholding to select cell bodies green2 = green.duplicate() if (readsettings[0] != "0") or (readsettings[1] != "0"): bg = True IJ.setAutoThreshold(green2, readsettings[2]) IJ.setRawThreshold(green2, int(readsettings[0]), int(readsettings[1]), None) Prefs.blackBackground = True IJ.run(green2, "Convert to Mask", "") IJ.run(green2, "Invert LUT", "") if readsettings[7] != "0": IJ.run(green2, "Make Binary", "") IJ.run( green2, "Remove Outliers...", "radius=" + readsettings[7] + " threshold=50 which=Dark") # CLAHE and background subtraction if readsettings[8] == "True": mpicbg.ij.clahe.Flat.getFastInstance().run( green, 127, 256, 3, None, False) if readsettings[9] == "True": calc = ImageCalculator() green = calc.run("Subtract create", green, red) elif readsettings[6] == "True": IJ.run(green, "Subtract Background...", "rolling=50") if readsettings[10] != "0": IJ.run(green, "Subtract...", "value=" + readsettings[10]) # run frangi vesselness pixelwidth = str(green.getCalibration().pixelWidth) IJ.run( green, "Frangi Vesselness (imglib, experimental)", "number=1 minimum=" + pixelwidth + " maximum=" + pixelwidth) green = IJ.getImage() # convert frangi vesselness image to 8bit grey scale conv = ImageConverter(green) conv.convertToGray8() IJ.run(green, "Convert to Mask", "") # remove cell bodies if bg is True: green = ImageCalculator().run("Subtract create", green, green2) # run grey scale morphology filter from MorpholibJ if readsettings[11] != "0": green = green.getProcessor() algo = BoxDiagonalOpeningQueue() algo.setConnectivity(4) result = algo.process(green, int(readsettings[11])) green = ImagePlus("result", result) IJ.run(green, "Invert LUT", "") if len(readsettings) > 14: # sparse neurite image analysis if readsettings[15] == "True": IJ.run( red, "Enhance Local Contrast (CLAHE)", "blocksize=127 histogram=256 maximum=3 mask=*None* fast_(less_accurate)" ) if readsettings[14] == "True": IJ.run(red, "Subtract Background...", "rolling=50") IJ.setAutoThreshold(red, readsettings[16]) IJ.setRawThreshold(red, int(readsettings[17]), int(readsettings[18]), None) IJ.run(red, "Convert to Mask", "") IJ.run(red, "Invert LUT", "") else: # dense neurite image analysis IJ.run( red, "Normalize Local Contrast", "block_radius_x=40 block_radius_y=40 standard_deviations=" + readsettings[12] + " center stretch") IJ.run(red, "Auto Threshold", "method=Default white") IJ.run(red, "Invert LUT", "") if readsettings[3] == "True": IJ.run(red, "Despeckle", "") IJ.saveAs(red, "Jpeg", settings2 + name + "neurites") # get number of neurite pixels # get number of neurite pixels statsneurite = red.getProcessor() statsneurite = statsneurite.getHistogram() neuritedensity.append(statsneurite[255]) IJ.saveAs(green, "Jpeg", settings2 + name + "myelinFinal") # get number of myelin pixels statsmyelin = green.getProcessor() statsmyelin = statsmyelin.getHistogram() myelinoverlay.append(statsmyelin[255]) closeallimages() # get pixel total of image whitepixels = (statsneurite[0]) blackpixels = (statsneurite[255]) totalpixels = whitepixels + blackpixels totalpixels = [totalpixels] * len(neuritedensity) # for each image calculate % myelination as number of myelin pixels # divided by the number of neurite pixels * 100 myelinoverlay = [ x1 / x2 * 100 for (x1, x2) in zip(myelinoverlay, neuritedensity) ] myelinaverage = sum(myelinoverlay) / len(myelinoverlay) myelinaverage2.append(myelinaverage) # for each image calculate % neurite density as neurite pixels divided # by the total number of pixels in the image * 100. neuritedensity = [ x1 / x2 * 100 for (x1, x2) in zip(neuritedensity, totalpixels) ] neuriteaverage = sum(neuritedensity) / len(neuritedensity) neuriteaverage2.append(neuriteaverage) name = "Image names" green = "% myelination" red = "% neurite density" imagenames = [name] + imagenames neuritedensity = [red] + neuritedensity myelinoverlay = [green] + myelinoverlay result = [] result.append(imagenames) result.append(neuritedensity) result.append(myelinoverlay) root = settings2 filename = "Results.csv" fullpath = os.path.join(root, filename) f = open(fullpath, 'wb') writer = csv.writer(f) for d in range(len(result)): row = [result[d]] writer.writerows(row) f.close() # must be reset to 0 for each iteration. y = 0 r = 0 # if statistical analysis is being performed the results .csv file # is also saved to a subfolder within the statistical analysis folder # which denotes the experimental condition the results belong to. if stats is True: # nested for loop to identify correct experimental condition # for the current subfolder being analysed. for y in range(0, len(experiments)): for r in range(0, len(experiments[0])): if experiments[y][r] == subfoldernames[i]: if "Windows" in OS: root = imagefolder + "\\statistical analysis\\" + names[ y].getText() elif "Mac" in OS: root = imagefolder + "/statistical analysis/" + names[ y].getText() filename = subfoldernames[i] + ".csv" fullpath = os.path.join(root, filename) f = open(fullpath, 'wb') writer = csv.writer(f) for e in range(len(result)): row = [result[e]] writer.writerows(row) f.close() break cwd2 = os.getcwd() for files in os.listdir(cwd2): if files.endswith(".csv"): os.remove(os.path.join(cwd2, files)) imagenames = [] myelinoverlay = [] neuritedensity = [] # create .csv summary sheet with average % neurite density # and average % myelination for each subfolder (experiment). if multi is True: name = "Folder name" imagenames = [name] + subfoldernames neuritedensity = [red] + neuriteaverage2 myelinoverlay = [green] + myelinaverage2 result = [] result.append(imagenames) result.append(neuritedensity) result.append(myelinoverlay) if "Windows" in OS: root = imagefolder + "\\" elif "Mac" in OS: root = imagefolder + "/" filename = "Result-Summary.csv" fullpath = os.path.join(root, filename) f = open(fullpath, 'wb') writer = csv.writer(f) for p in range(len(result)): row = [result[p]] writer.writerows(row) f.close() imagenames = [] myelinoverlay = [] neuritedensity = [] # Run Rscript for statistical analysis via the command line if stats is True: cmd = Rloc2 + " " + cwdR + " " + statsfolderPath Runtime.getRuntime().exec(cmd) Finished()
# pt = Plot(plottitle, "Frames", "Intensity") pt = Plot(plottitle, "Frames", "Intensity") pt.setLimits(0, pathlenMax + 1, meanMin, maxMax) pt.setColor(Color.red) pt.addPoints(jframes, jmean, pt.LINE) pt.setColor(Color.lightGray) pt.addPoints(jframes, jmax, pt.LINE) # pt.addPoints(jframes, jmean, pt.CIRCLE) # pt.draw() pt.show() GdilateIter = 2 imp = IJ.getImage() chsA = CS.split(imp) impc1 = chsA[0] impc2 = chsA[1] IJ.run("Clear Results", "") IJ.run(impc1, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") IJ.run(impc2, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") impbin, rt = segmentNuc(impc2, GdilateIter) imprim = extractRIM(impbin, GdilateIter) rt.show("Results") cxA, cyA, bxA, byA, widthA, heightA, frameA, indexA = parseResultsTable(rt) hasNextFrame = checkPresenceinNextFrame(impbin, rt, cxA, cyA, frameA) nextFrame = linkNucelus(cxA, cyA, frameA, hasNextFrame) """ for i in nextFrame: print i, 'slice', frameA[i], 'to ', nextFrame[i]
def gfp_analysis(imp, file_name, output_folder, gfp_channel_number=1, dapi_channel_number=3, red_channel_number=2, threshold_method='Otsu', do_manual_qc=False, min_size_pix=1000): """perform analysis based on gfp intensity thresholding""" try: cal = imp.getCalibration() channel_imps = ChannelSplitter.split(imp) gfp_imp = channel_imps[gfp_channel_number - 1] gfp_imp.setTitle("GFP") threshold_imp = Duplicator().run(gfp_imp) threshold_imp.setTitle("GFP_threshold_imp") ecad_imp = channel_imps[red_channel_number - 1] ecad_imp.setTitle("E-cadherin") nuc_imp = channel_imps[dapi_channel_number - 1] nuclei_locations, full_nuclei_imp, ws_seeds_imp = get_nuclei_locations( nuc_imp, cal, distance_threshold_um=10, size_threshold_um2=100) ws_seeds_imp.changes = False ws_seeds_imp.close() full_nuclei_imp.hide() IJ.run(threshold_imp, "Make Binary", "method={} background=Dark calculate".format(threshold_method)) IJ.run(threshold_imp, "Fill Holes", "") erode_count = 2 for _ in range(erode_count): IJ.run(threshold_imp, "Erode", "") for _ in range(erode_count): IJ.run(threshold_imp, "Dilate", "") threshold_imp = keep_blobs_bigger_than(threshold_imp, min_size_pix) threshold_imp = my_kill_borders(threshold_imp) rois = generate_cell_rois(threshold_imp) threshold_imp.changes = False threshold_imp.close() rois = filter_cells_by_relative_nuclear_area( rois, full_nuclei_imp, relative_nuclear_area_threshold=0.75) if do_manual_qc: rois = perform_manual_qc(imp, rois, important_channel=gfp_channel_number) no_nuclei_centroids = [ get_no_nuclei_in_cell(roi, nuclei_locations) for roi in rois ] no_enclosed_nuclei = [ get_no_nuclei_fully_enclosed(roi, full_nuclei_imp) for roi in rois ] full_nuclei_imp.changes = False full_nuclei_imp.close() out_stats = generate_cell_shape_results( rois, gfp_imp, cal, file_name, no_nuclei_centroids=no_nuclei_centroids, no_enclosed_nuclei=no_enclosed_nuclei) print("Number of cells identified = {}".format(len(out_stats))) # save output save_qc_image( imp, rois, "{}_plus_overlay.tiff".format( os.path.join(output_folder, os.path.splitext(file_name)[0]))) save_cell_rois(rois, output_folder, os.path.splitext(file_name)[0]) imp.changes = False imp.close() save_output_csv(out_stats, output_folder) except Exception as e: print("Ran into a problem analysing {}: {}. Skipping to next cell...". format(file_name, e.message)) out_stats = [] pass return out_stats
activeImage.copyScale(calibImage) calib = calibImage.getCalibration() calibImage.close() activeImage.updateAndRepaintWindow() else: calib = activeImage.getCalibration() ## Runs interface that allows to correct for bleedthrough and refraction if activeImage is not None: gd = NonBlockingGenericDialog("Select channel to operate on...") gd.addChoice("Select_channel:",["Channel "+str(i) for i in range(1,activeImage.getNChannels()+1)],"Channel 1") gd.addChoice("Bleeding_channel:",["None"] + ["Channel "+str(i) for i in range(1,activeImage.getNChannels()+1)],"None") gd.addChoice("Refraction_reference_channel:",["None"] + ["Channel "+str(i) for i in range(1,activeImage.getNChannels()+1)],"None") gd.showDialog() if (gd.wasOKed()): channelImages = ChannelSplitter.split(activeImage) channel = gd.getNextChoiceIndex()+1 bleedingC = gd.getNextChoiceIndex() refractRefC = gd.getNextChoiceIndex() if (bleedingC > 0): params = ("bleeding_channel=" + str(bleedingC) + " bloodied_channel=" + str(channel) + " " + "allowable_saturation_percent=1.0 rsquare_threshold=0.50") IJ.run("Remove Bleedthrough (automatic)", params) dataImage = WindowManager.getImage("Corrected_ch" + str(channel)) if (refractRefC > 0): refractCImage = channelImages[refractRefC-1].duplicate() refractCImage.show() IJ.run("Merge Channels...", "c1=" + dataImage.getTitle() + " c2=" + refractCImage.getTitle() + " create ignore") mergedImage = WindowManager.getImage("Composite") params = ("reference_channel=2 application_channel=1 automatic_operation generate_log " + "max_slice=43 surface_slice=87")
def main(imp,options): from ij.plugin import ChannelSplitter from ij.gui import Roi,PointRoi, PolygonRoi, Overlay, Line from java.awt import Color from ij import WindowManager from ij.measure import ResultsTable from ij.text import TextWindow active_z=imp.getZ() imps = ChannelSplitter.split(imp) imp.setZ(active_z) roi_int = imp.getRoi() comp_imp=Zproj(imps[options["comp_ch"]], "SUM", active_z, options["z_range"]) comp_imp=mode_subtract(comp_imp,roi_int) loci_imp=Zproj(imps[options["loci_ch"]], "SUM", imp.getZ(), options["z_range"]) loci_imp=mode_subtract(loci_imp,roi_int) #Finding the boundaries of compartment and loci comp_roi=thresh(sum_prj=comp_imp,thresh=options["comp_T"],roi=roi_int,method="boundary") print "ok" if (options["loci_method"]== "locus center"): loci_roi=thresh(sum_prj=loci_imp, thresh=options["loci_T"], roi=roi_int, method="point") elif options["loci_method"]== "locus boundary": loci_roi=thresh(sum_prj=loci_imp, thresh=options["loci_T"], roi=roi_int, method="boundary") if options["loci_method"]== "locus center": dist,xc,yc,xl,yl=get_center_edge_dist(imp,comp_roi, loci_roi) elif options["loci_method"]== "locus boundary": dist,xc,yc,xl,yl=get_closest_points(imp,comp_roi,loci_roi) rt_exist = WindowManager.getWindow("Loci distance to compartment") if rt_exist==None or not isinstance(rt_exist, TextWindow): table= ResultsTable() else: table = rt_exist.getTextPanel().getOrCreateResultsTable() table.incrementCounter() table.addValue("Label", imp.title) table.addValue("Distance(micron)", dist) if options['measure_feret']: feret_roi,loci_feret,loci_area= feret(sum_prj=loci_imp,thresh=options["loci_T"], roi=roi_int,pixel_size=imp.getCalibration().pixelWidth) table.addValue("Loci feret", loci_feret) table.addValue("Loci area", loci_area) table.show("Loci distance to compartment") ## Adding loci overlay ov=imp.getOverlay() if ov==None: ov=Overlay() line = Line(xc,yc, xl,yl) line.setStrokeWidth(0.2) line.setStrokeColor(Color.PINK) ov.add(line) if options["loci_method"]== "locus center": ov.add(PointRoi(loci_roi["x"],loci_roi["y"])) elif options["loci_method"]== "locus boundary": ov.add(loci_roi) if options['measure_feret']: ov.add(feret_roi) ov.add(comp_roi) imp.setOverlay(ov)
def getGrayScaleImage(currIP, c, chanName, cfg): if (cfg.hasValue(ELMConfig.upperLeftExclusionX)): ulExclusionX = cfg.getValue(ELMConfig.upperLeftExclusionX) else: ulExclusionX = 0 if (cfg.hasValue(ELMConfig.upperLeftExclusionY)): ulExclusionY = cfg.getValue(ELMConfig.upperLeftExclusionY) else: ulExclusionY = 0 if (cfg.hasValue(ELMConfig.lowerRightExclusionX)): lrExclusionX = cfg.getValue(ELMConfig.lowerRightExclusionX) else: lrExclusionX = currIP.getWidth() if (cfg.hasValue(ELMConfig.lowerRightExclusionY)): lrExclusionY = cfg.getValue(ELMConfig.lowerRightExclusionY) else: lrExclusionY = currIP.getHeight() imgType = currIP.getType() if (chanName in cfg.getValue( ELMConfig.chansToSkip)): # Don't process skip channels currIP.close() return None elif imgType == ImagePlus.COLOR_RGB or imgType == ImagePlus.COLOR_256: if (chanName == ELMConfig.BRIGHTFIELD): toGray = ImageConverter(currIP) toGray.convertToGray8() elif (chanName == ELMConfig.BLUE) \ or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED) \ or (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN): # chanIdx = 2 if (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.RED): chanIdx = 0 elif (cfg.getValue(ELMConfig.chanLabel)[c] == ELMConfig.GREEN): chanIdx = 1 imgChanns = ChannelSplitter.split(currIP) currIP.close() currIP = imgChanns[chanIdx] # Clear the Exclusion zone, so it doesn't mess with thresholding imgProc = currIP.getProcessor() imgProc.setColor(Color(0, 0, 0)) imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(), currIP.getHeight()) imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY) elif (chanName == ELMConfig.YELLOW): # Clear the Exclusion zone, so it doesn't mess with thresholding imgProc = currIP.getProcessor() imgProc.setColor(Color(0, 0, 0)) imgProc.fillRect(lrExclusionX, lrExclusionY, currIP.getWidth(), currIP.getHeight()) imgProc.fillRect(0, 0, ulExclusionX, ulExclusionY) # Create a new image that consists of the average of the red & green channels title = currIP.getTitle() width = currIP.getWidth() height = currIP.getHeight() newPix = ByteProcessor(width, height) for x in range(0, width): for y in range(0, height): currPix = currIP.getPixel(x, y) newPix.putPixel(x, y, (currPix[0] + currPix[1]) / 2) currIP.close() currIP = ImagePlus(title, newPix) else: print "ERROR: Unrecognized channel name! Name: " + chanName currIP.close() return None elif imgType == ImagePlus.GRAY16 or imgType == ImagePlus.GRAY32 or imgType == ImagePlus.GRAY8: if not imgType == ImagePlus.GRAY8: toGray = ImageConverter(currIP) toGray.convertToGray8() else: print "ERROR: Unrecognized channel name & image type! Channel: " + chanName + ", imgType: " + str( imgType) currIP.close() return None return currIP
def run(): zk = ZeissKeys() msg = Message() timestart = time.clock() channel = 1 #size in um2 minArea = 20 maxArea = 200 maxMetaArea = 70 minMetaAR = 1.8 method = "Triangle" print "Enter run" detectionNucleus = [minArea, maxArea] detectionMetaphase = [minArea, maxMetaArea] filepath = "" try: filepath = getArgument() image = IJ.openImage(filepath) #arguments provided by runMacro except NameError: try: filepath = newImagePath #argument provided by the macroRunner except NameError: #no file name specified errMsg = "Fiji error segmentNuclei.py: no filepath has been passed to the macro" exitWithError(errMsg) od = OpenDialog("Choose image file", None) if od.getFileName() == None: return filepath = os.path.join(od.getDirectory(), od.getFileName()) # A roimanager is recquired roim = RoiManager.getInstance() if roim == None: roim = RoiManager() #test a last time if roim == None: print 'Fiji error segmentNuclei.py: no RoiManager!' exitWithError('Fiji error segmentNuclei.py: no RoiManager!') try: IJ.run("Close all forced") IJ.run("Clear Results") IJ.log("\\Clear") image = IJ.openImage(filepath) IJ.log("File Path " + filepath) try: image.hide() except: image = IJ.getImage() image.hide() image.show() if image is None: exitWithError("Fiji failed to open image") return 0 #convert um2 to pixels pixelSize = image.getCalibration().pixelWidth detectionNucleus = [area/pixelSize/pixelSize for area in detectionNucleus] detectionMetaphase = [area/pixelSize/pixelSize for area in detectionMetaphase] detectionMetaphase.append(minMetaAR) title = image.getTitle() imageC = None #split colors if needed if image.getNChannels() > 1: chSp = ChannelSplitter() imageC = chSp.split(image) imageSeg = imageC[channel-1].duplicate() else: imageSeg = image.duplicate() imageSeg.setTitle("SEG_"+title) sp = segment_Particles() imageSeg = sp.preprocessImage(imageSeg, "MAX", "C1", 2, 2) imageSeg = sp.segmentParticles(imageSeg, method, detectionNucleus[0], detectionNucleus[1], 2, 2) roim = RoiManager.getInstance() if roim == None: print 'Fiji error segmentNuclei.py: no RoiManager!' exitWithError('Fiji error segmentNuclei.py: no RoiManager!') #compute central object if roim.getCount() > 0: centPart, msg.position = centerParticle(imageSeg, roim) msg.position = msg.position + (focusParticle(image, roim, centPart),) writePositionToRegistry(msg.position) else: IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_NOTHING+"] windows=REG_SZ") return 0 #create output image if imageC is None: impOut = createOutputImg(image, roim, centPart, 0) else: impOut = createOutputImg(imageC[channel-1], roim, centPart, 0) impOut.show() #save outut image #saveOutputImg(impOut, filepath, 'Analyzed') #check for roi properties to identofy metaphase metaphase = isSpecialParticle(image, roim, centPart,detectionNucleus, detectionMetaphase,pixelSize, msg.position[2]) if os.path.basename(filepath).startswith('TR1_') or '_TR1_' in os.path.basename(filepath): metaphase = 0 if metaphase: IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_TRIGGER1+"] windows=REG_SZ") else: IJ.run("Read Write Windows Registry", "action=write location=[HKCU\\"+zk.regkey+"] key="+zk.subkey_codemic+" value=["+msg.CODE_FOCUS+"] windows=REG_SZ") IJ.log("time focus " + str(time.clock() - timestart)) IJ.run("Collect Garbage") #IJ.run("Close all forced") #IJ.run("Clear Results") except BaseException, err:
raise IOError("Input Exception: Directory does not contain any preprocessed images.") if not pth.exists(saveFolder): # check if directory for analysis-files is present makedirs(saveFolder) for image in moFileList: # get rid of 0! print "starting with cell " + image.group() + " " + "("+ str(moFileList.index(image)) + "/" + str(len(moFileList)) + ")" imp = Opener().openImage(inputDir + image.group()) # open Image # read calibration for later calculation of distances in um. calibration = imp.getCalibration() pxWidth = calibration.pixelWidth print "px depth", calibration.pixelDepth timeInterval = round(calibration.frameInterval) #start measurement splitCh = CS.split(imp) # split channels #try: ATA().segAndMeasure(splitCh[0], splitCh[1]) # perform segmentation and measurement #else: go to next element in moFileList # move image to "segProblem" folder # continue WindowManager.getImage("binProjMerged").close() WindowManager.getImage("DUP_C1-"+image.group()).close() WindowManager.getImage("DUP_C2-"+image.group()).close() # read the measurements from results tables. distance_lines = WindowManager.getFrame("Statistics_Distance").getTextPanel().getText().split("\n") ch0_dots = tableToDots(WindowManager.getFrame("Statistics_Ch0").getTextPanel().getText().split("\n"), 0) ch1_dots = tableToDots(WindowManager.getFrame("Statistics_Ch1").getTextPanel().getText().split("\n"), 1)
from ij.measure import ResultsTable from ij.measure import Measurements from ij.plugin.filter import Analyzer ## Main body of script theImage = IJ.getImage() gd = NonBlockingGenericDialog("Pick parameters...") gd.addChoice("Analysis_channel",["Channel "+str(i+1) for i in range(theImage.getNChannels())],"Channel 1") gd.addNumericField("Pick_threshold",50,0) gd.addCheckbox("Apply_min",True) gd.showDialog() if (gd.wasOKed()): analysisChannel = gd.getNextChoiceIndex() + 1 intensityThreshold = gd.getNextNumber() doMin = gd.getNextBoolean() splitImage = ChannelSplitter.split(theImage) dataImage = splitImage[analysisChannel-1].duplicate() if doMin: IJ.run(dataImage,"Minimum...", "radius=2 stack") goRun = True rt = ResultsTable() while goRun: wfud = WaitForUserDialog("Pick freehand ROI, then hit OK to analyze") wfud.show() roi = theImage.getRoi() if roi is None: goRun = False else: dataImage.setRoi(roi) subImage = dataImage.duplicate() dataIp = dataImage.getProcessor()
tubimg = ImagePlus("img", tubimg) result[index] = tubimg # vessel detection training dc = DirectoryChooser("Choose a folder") folder = dc.getDirectory() pos = IJ.openImage(folder + "\\vessels_positive.tif") posroi = pos.getRoi() neg = IJ.openImage(folder + "\\vessels_negative.tif") negroi = neg.getRoi() pos.close() IJ.run("Select None", "") channels = ChannelSplitter.split(neg) neg.close() image = channels[3] channels = channels[0:3] proc = image.getProcessor() directional_op = ImagePlus("directional_op", proc) IJ.run(directional_op, "Directional Filtering", "type=Max operation=Opening line=30 direction=32") directional_op = WindowManager.getImage("directional_op-directional") tubes = range(5, 130, 12) img_source = ImagePlus("image", proc) src = clij2.push(img_source)
def splitChannels(orgimp): imps = ChannelSplitter.split(orgimp) return imps[1], imps[2]
def track(): imp = IJ.getImage() nChannels = imp.getNChannels() # Get the number of channels orgtitle = imp.getTitle() IJ.run("Subtract Background...", "rolling=50 sliding stack") IJ.run("Enhance Contrast...", "saturated=0.3") IJ.run("Multiply...", "value=10 stack") IJ.run("Subtract Background...", "rolling=50 sliding stack") IJ.run("Set Scale...", "distance=0") channels = ChannelSplitter.split(imp) imp_GFP = channels[0] imp_RFP = channels[1] IJ.selectWindow(orgtitle) IJ.run("Close") ic = ImageCalculator() imp_merge = ic.run("Add create stack", imp_GFP, imp_RFP) imp_merge.setTitle("add_channels") imp_merge.show() imp_RFP.show() imp_GFP.show() imp5 = ImagePlus() IJ.run(imp5, "Merge Channels...", "c1=[" + imp_merge.title + "] c2=" + imp_GFP.title + ' c3=' + imp_RFP.title + " create") print("c1=[" + imp_merge.title + "] c2=" + imp_GFP.title + ' c3=' + imp_RFP.title + " create") imp5.show() imp5 = IJ.getImage() nChannels = imp5.getNChannels() # Setup settings for TrackMate settings = Settings() settings.setFrom(imp5) # Spot analyzer: we want the multi-C intensity analyzer. settings.addSpotAnalyzerFactory(SpotMultiChannelIntensityAnalyzerFactory()) # Spot detector. settings.detectorFactory = LogDetectorFactory() settings.detectorSettings = settings.detectorFactory.getDefaultSettings() settings.detectorSettings['TARGET_CHANNEL'] = 1 settings.detectorSettings['RADIUS'] = 24.0 settings.detectorSettings['THRESHOLD'] = 0.0 # Spot tracker. # Configure tracker - We don't want to allow merges or splits settings.trackerFactory = SparseLAPTrackerFactory() settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap() # almost good enough settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = False settings.trackerSettings['ALLOW_TRACK_MERGING'] = False settings.trackerSettings['LINKING_MAX_DISTANCE'] = 8.0 settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE'] = 8.0 settings.trackerSettings['MAX_FRAME_GAP'] = 1 # Configure track filters settings.addTrackAnalyzer(TrackDurationAnalyzer()) settings.addTrackAnalyzer(TrackSpotQualityFeatureAnalyzer()) filter1 = FeatureFilter('TRACK_DURATION', 20, True) settings.addTrackFilter(filter1) # Run TrackMate and store data into Model. model = Model() trackmate = TrackMate(model, settings) ok = trackmate.checkInput() if not ok: sys.exit(str(trackmate.getErrorMessage())) ok = trackmate.process() if not ok: sys.exit(str(trackmate.getErrorMessage())) selectionModel = SelectionModel(model) displayer = HyperStackDisplayer(model, selectionModel, imp5) displayer.render() displayer.refresh() IJ.log('TrackMate completed successfully.') IJ.log('Found %d spots in %d tracks.' % (model.getSpots().getNSpots(True) , model.getTrackModel().nTracks(True))) # Print results in the console. headerStr = '%10s %10s %10s %10s %10s %10s' % ('Spot_ID', 'Track_ID', 'Frame', 'X', 'Y', 'Z') rowStr = '%10d %10d %10d %10.1f %10.1f %10.1f' for i in range( nChannels ): headerStr += (' %10s' % ( 'C' + str(i+1) ) ) rowStr += ( ' %10.1f' ) #open a file to save results myfile = open('/home/rickettsia/Desktop/data/Clamydial_Image_Analysis/EMS_BMECBMELVA_20X_01122019/data/'+orgtitle.split('.')[0]+'.csv', 'wb') wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerow(['Spot_ID', 'Track_ID', 'Frame', 'X', 'Y', 'Z', 'Channel_1', 'Channel_2']) IJ.log('\n') IJ.log(headerStr) tm = model.getTrackModel() trackIDs = tm.trackIDs(True) for trackID in trackIDs: spots = tm.trackSpots(trackID) # Let's sort them by frame. ls = ArrayList(spots) for spot in ls: values = [spot.ID(), trackID, spot.getFeature('FRAME'), \ spot.getFeature('POSITION_X'), spot.getFeature('POSITION_Y'), spot.getFeature('POSITION_Z')] for i in range(nChannels): values.append(spot.getFeature('MEAN_INTENSITY%02d' % (i+1))) IJ.log(rowStr % tuple(values)) l1 = (values[0], values[1], values[2], values[3], values[4], values[5], values[7], values[8]) wr.writerow(l1) myfile.close() IJ.selectWindow("Merged") IJ.run("Close")
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)
# activate series (same as checkbox in GUI) opts.setSeriesOn(i,True) # point import process reader to this series reader.setSeries(i) # read and process all images in series imps = impReader.openImagePlus() # deactivate series for next round (otherwise will re-analyze everything) opts.setSeriesOn(i, False) # run analysis on active series for all images in stack for imp in imps: channels = splitter.split(imp) for c in channels: title = c.getTitle() c = sliceCrop(c, front, back) # int array [width, height, nChannels, nSlices, nFrames] Dim = c.getDimensions() prev = 0 if len(channels) > 1: #if two channels, care about nSlices d_idx = 3 else: #if only one channel, care about nFrames d_idx = 4
def run(imagefile): # Opening the image log.log(LogLevel.INFO, 'Opening Image: ' + imagefile) # open image file and get a specific series imp, MetaInfo = ImportTools.openfile(imagefile) log.log(LogLevel.INFO, 'File Extension : ' + MetaInfo['Extension']) if 'ResolutionCount' in MetaInfo: log.log(LogLevel.INFO, 'Resolution Count : ' + str(MetaInfo['ResolutionCount'])) if 'SeriesCount' in MetaInfo: log.log(LogLevel.INFO, 'SeriesCount : ' + str(MetaInfo['SeriesCount'])) if 'SizeC' in MetaInfo: log.log(LogLevel.INFO, 'Channel Count : ' + str(MetaInfo['SizeC'])) # do the processing log.log(LogLevel.INFO, 'Start Processing ...') if EXTRACT_CHANNEL: # get the correct channel if MetaInfo['SizeC'] > 1: log.log(LogLevel.INFO, 'Extract Channel : ' + str(CHINDEX)) imps = ChannelSplitter.split(imp) imp = imps[CHINDEX - 1] # correct background using rolling ball if CORRECT_BACKGROUND: log.log(LogLevel.INFO, 'Rolling Ball Background subtraction...') imp = FilterTools.apply_rollingball(imp, radius=RB_RADIUS, createBackground=CREATEBACKGROUND, lightBackground=LIGHTBACKGROUND, useParaboloid=USEPARABOLOID, doPresmooth=DOPRESMOOTH, correctCorners=CORRECTCORNERS) if FILTERDIM == '2D': if RANKFILTER != 'NONE': # apply filter log.log(LogLevel.INFO, 'Apply 2D Filter : ' + RANKFILTER) imp = FilterTools.apply_filter(imp, radius=RADIUS, filtertype=RANKFILTER) if FILTERDIM == '3D': if FILTER3D != 'NONE': # apply filter log.log(LogLevel.INFO, 'Apply 3D Filter : ' + FILTER3D) imp = FilterTools.apply_filter3d(imp, radiusx=RADIUSX, radiusy=RADIUSY, radiusz=RADIUSZ, filtertype=FILTER3D) if THRESHOLD != 'NONE': # apply threshold log.log(LogLevel.INFO, 'Apply Threshold : ' + THRESHOLD) log.log(LogLevel.INFO, 'Correction Factor : ' + str(CORRFACTOR)) imp = ThresholdTools.apply_threshold(imp, method=THRESHOLD, background_threshold='dark', stackopt=TH_STACKOPT, corrf=CORRFACTOR) # imp_t = imp.duplicate() # imp_t.show("Threshold") if FILL_HOLES: # 3D fill holes log.log(LogLevel.INFO, '3D Fill Holes ...') imp = Reconstruction3D.fillHoles(imp.getImageStack()) if not FILL_HOLES: imp = imp.getImageStack() if WATERSHED: # run watershed on stack weights = ChamferWeights3D.BORGEFORS.getFloatWeights() normalize = True dynamic = 2 connectivity = LABEL_CONNECT log.log(LogLevel.INFO, 'Run Watershed to separate particles ...') #dist = BinaryImages.distanceMap(imp.getImageStack(), weights, normalize) dist = BinaryImages.distanceMap(imp, weights, normalize) Images3D.invert(dist) #imp = ExtendedMinimaWatershed.extendedMinimaWatershed(dist, imp.getImageStack(), dynamic, connectivity, 32, False ) imp = ExtendedMinimaWatershed.extendedMinimaWatershed( dist, imp, dynamic, connectivity, 32, False) # extend borders log.log(LogLevel.INFO, 'Border Extension ...') # create BorderManager and add Zeros in all dimensions bmType = BorderManager3D.Type.fromLabel("BLACK") bm = bmType.createBorderManager(imp) #bm = bmType.createBorderManager(imp.getStack()) BorderExt = ExtendBordersPlugin() # extend border by always exb #imp = BorderExt.process(imp.getStack(), EXB, EXB, EXB, EXB, EXB, EXB, bm) imp = BorderExt.process(imp, EXB, EXB, EXB, EXB, EXB, EXB, bm) # convert back to ImgPlus pastack = ImagePlus('Particles', imp) # check for pixel in 3d by size log.log(LogLevel.INFO, 'Filtering VoxelSize - Minimum : ' + str(MINVOXSIZE)) pastack = BinaryImages.volumeOpening(pastack.getStack(), MINVOXSIZE) imp = ImagePlus('Particles Filtered', pastack) pastack = BinaryImages.componentsLabeling(imp, LABEL_CONNECT, LABEL_BITDEPTH) # get the labels labels = LabelImages.findAllLabels(pastack) log.log(LogLevel.INFO, 'Labels Filtered : ' + str(len(labels))) # run 3D particle analysis log.log(LogLevel.INFO, '3D Particle Analysis ...') PA3d = ParticleAnalysis3DPlugin() results = PA3d.process(pastack) # colorize the labels if LABEL_COLORIZE: log.log(LogLevel.INFO, 'Colorize Lables ...') #maxLabel = 255 maxLabel = len(labels) bgColor = Color.BLACK shuffleLut = True lutName = CommonLabelMaps.GOLDEN_ANGLE.getLabel() # Create a new LUT from info in dialog lut = CommonLabelMaps.fromLabel(lutName).computeLut( maxLabel, shuffleLut) # Create a new RGB image from index image and LUT options pastack_rgb = LabelImages.labelToRgb(pastack, lut, bgColor) # convert to rgb color IJ.run(pastack_rgb, "RGB Color", "slices") if LABEL_COLORIZE: return pastack_rgb, results, labels elif not LABEL_COLORIZE: return pastack, results, labels
for fileName in listdir(path): if regEx.match(fileName): # if matches RE, add to list moFileList.append(regEx.match(fileName)) if moFileList == []: IJ.showMessage("Input Exception", "No unprocessed images found in the directory you selected.") raise IOError("No unpocessed TIFFs found in this folder.") for image in moFileList: print "Processing cell " + image.group() + " (" + str(moFileList.index(image)+1) + "/" + str(len(moFileList)) + ")" IJ.log("Processing cell " + image.group() + " (" + str(moFileList.index(image)+1) + "/" + str(len(moFileList)) + ")") imp = Opener().openImage(path + image.group()) # open Image #if imp.getBitDepth() != 8: # converting to 8 bit if # ImageConverter(imp).convertToGray8() roi = imp.roi imps = CS.split(imp) ppc = PPC() for aimp in imps: ppc.setImp(aimp) ppc.run() if roi != None: aimp.setRoi(roi) for n in range(1, aimp.getImageStackSize()+1): aimp.getImageStack().getProcessor(n).fillOutside(roi) aimp.killRoi() final = StackMerge.mergeChannels(imps, False) final.copyScale(imp) # copyscale from .copyscale if not pth.exists(saveFolder): makedirs(saveFolder) fileName = G_saveFilePrefix + image.group('prefix') IJ.saveAs(final, ".tiff", pth.join(saveFolder, fileName) ) # saveAs(ImagePlus imp, java.lang.String format, java.lang.String path)
testTile = WindowManager.getImage(windowName) numTotalChannels = testTile.getNChannels() labels = ["" for x in range(numTotalChannels)] defaultValues = [False for x in range(numTotalChannels)] for i in range(1,numTotalChannels+1): labels[i-1] = "Channel" + str(i) defaultValues[i-1] = False ## Allows user to choose which channels to analyze gd = NonBlockingGenericDialog("Select channel...") gd.addCheckboxGroup(numTotalChannels,1,labels,defaultValues) gd.showDialog() runOnChannel = [False for x in range(numTotalChannels)] for i in range(numTotalChannels): runOnChannel[i] = gd.getNextBoolean() ## Runs the 3D object counter on all the tiles and saves the results to disk IJ.run("3D OC Options", "volume surface nb_of_obj._voxels nb_of_surf._voxels integrated_density mean_gray_value std_dev_gray_value median_gray_value minimum_gray_value maximum_gray_value centroid mean_distance_to_surface std_dev_distance_to_surface median_distance_to_surface centre_of_mass bounding_box dots_size=5 font_size=10 show_numbers white_numbers store_results_within_a_table_named_after_the_image_(macro_friendly) redirect_to=none"); channelImage = ChannelSplitter.split(testTile) testTile.close() for i in range(numTotalChannels): if (runOnChannel[i]): channelImage[i].show() IJ.run(channelImage[i], "3D Objects Counter", "threshold=42 slice=47 min.=300 max.=24903680 statistics") IJ.saveAs("Results", "/Volumes/DUNCAN/2015/03_12_15 ERT2 Confetti DSS earlier trace/A5/9396-abluminal.lsm_tiles/objects/C" + str(i+1) + "-tile_45.csv") channelImage[i].close() resultsWindows = WindowManager.getAllNonImageWindows() for i in range(len(resultsWindows)): resultsWindows[i].dispose()
print tileList except: IJ.log("Problem parsing your tile subset!") parsingFailed = True else: tileList = range(1,nTiles+1) ## Applies corrections to individual tiles, then runs the object counter if not parsingFailed: for tile in tileList: params = ("open=["+ parentLSMFilePath + "_tiles/tile_" + str(tile) + ".ome.tif] " + "color_mode=Default view=Hyperstack stack_order=XYCZT") IJ.run("Bio-Formats Importer", params) theImage = WindowManager.getImage("tile_" + str(tile) + ".ome.tif") calibration = theImage.getCalibration() channelImages = ChannelSplitter.split(theImage) if (bleedingChannel > 0): params = ("bleeding_channel=" + str(bleedingChannel) + " bloodied_channel=" + str(analysisChannel) + " " + "allowable_saturation_percent=1.0 rsquare_threshold=0.50") IJ.run("Remove Bleedthrough (automatic)", params) dataImage = WindowManager.getImage("Corrected_ch" + str(analysisChannel)) if (refChannel > 0): refractCImage = channelImages[refChannel-1].duplicate() refractCImage.show() IJ.run("Merge Channels...", "c1=" + dataImage.getTitle() + " c2=" + refractCImage.getTitle() + " create ignore") mergedImage = WindowManager.getImage("Composite") params = ("reference_channel=2 application_channel=1 automatic_operation generate_log " + "max_slice=43 surface_slice=87") IJ.run(mergedImage,"Refractive Signal Loss Correction",params) dataImage = WindowManager.getImage("App Corrected") mergedImage.close()
# transformed EM to 8 bit EM = IJ.openImage(os.path.join(transformation_output, "EM.tif")) IJ.run(EM, "8-bit", "") # overwrite EM stack with transformed EM image fs = FileSaver(EM) fs.saveAsTiff(saveEMfilepath) # open EM image as ImagePlus for merging channel EM = ImagePlus(saveEMfilepath) # split rLM image in different channels saverLMpath = os.path.join(transformation_output, "rLM.tif") rLM = IJ.openImage(saverLMpath) R, G, B = ChannelSplitter.split(rLM) # Merge channels overlay = RGBStackMerge.mergeChannels( [None, None, B, EM, None, None, None], True) # Change R,G, B if the chromatin channel is a different one. # If you want a different color for the chromatin in the overlay image, change the position of the letter R,G,B, # e.g. [B, None, None, EM, None, None, None] for displaying chromatin in the red channel. RGBStackConverter.convertToRGB(overlay) # save overlay saveoverlaypath = os.path.join(workdir, "overlay_EM_Chromatin.tif") fs = FileSaver(overlay) fs.saveAsTiff(saveoverlaypath) print("(----- )overlay EM and rLM image done")