def correct_drift(img1, img2, display_cc=False): ''' Returns two ImagePlus objects that are drift corrected to each other. The first image is not changed. The second image is a new image that is shifted using ImageJ's Translate. :param img1: The reference image. :param img2: The image to be shifted. :param display_cc: Activate displaying the CrossCorrelation image (default False). ''' img1_cc, img2_cc = cc.scale_to_power_of_two([img1, img2]) result = cc.perform_correlation(img1_cc, img2_cc) x_off, y_off = cc.get_shift(result) # style after maximum detection if not display_cc: result.hide() else: result.copyScale(img1) cc.style_cc(result) if x_off == 0 and y_off == 0: print('No drift has been detected.') return img1, img2 title = img2.getTitle() img2_dk = Duplicator().run(img2) img2_dk.setTitle('DK-' + title) IJ.run(img2_dk, 'Translate...', 'x=%d y=%d interpolation=None' % (-x_off, -y_off)) img2_dk.copyScale(img2) img2_dk.show() return img1, img2_dk
def threshold(imPlus, edgeThreshold=2500): mask = Duplicator().run(imPlus) mask_stk = mask.getStack() # First, we threshold based on edges IJ.setThreshold(mask, edgeThreshold, 100000, "No Update") for i in range(mask.getImageStackSize()): mask_stk.getProcessor(i + 1).findEdges() IJ.run(mask, "Make Binary", "method=Default background=Default black") # Now, we need to clean up the binary images morphologically IJ.run(mask, "Dilate", "stack") IJ.run(mask, "Fill Holes", "stack") IJ.run(mask, "Erode", "stack") IJ.run(mask, "Erode", "stack") # Finally, remove the small particles stk = ImageStack(mask.getWidth(), mask.getHeight()) p = PA(PA.SHOW_MASKS, 0, None, 200, 100000) p.setHideOutputImage(True) for i in range(mask_stk.getSize()): mask.setSliceWithoutUpdate(i + 1) p.analyze(mask) mmap = p.getOutputImage() stk.addSlice(mmap.getProcessor()) mask.setStack(stk) mask.setSliceWithoutUpdate(1) mask.setTitle(mask_title(imPlus.getTitle())) mask.show() return mask
def blurImage(ip): #duplicate imp_dup = Duplicator().run(ip) #blur it imp_dup.show() IJ.run(imp_dup, "Gaussian Blur...", "sigma=1") imp_GB = IJ.getImage() return (imp_GB)
def z_crop(imp): """trim a z stack based on interactively-defined start and end points""" WaitForUserDialog("Choose first z plane and click OK...").show() start_z = imp.getZ() WaitForUserDialog("Now choose last z plane and click OK...").show() end_z = imp.getZ() frames = imp.getNFrames() channels = imp.getNChannels() #current_channel = imp.getC(); dupimp = Duplicator().run(imp, 1, channels, start_z, end_z, 1, frames) imp.changes = False imp.close() dupimp.show() #autoset_zoom(dupimp); return dupimp, (start_z, end_z)
def z_crop(imp): """trim a z stack based on interactively-defined start and end points""" IJ.setTool("zoom") IJ.run("Brightness/Contrast...") imp.setZ(1) WaitForUserDialog("Choose first z plane and click OK...").show() start_z = imp.getZ() WaitForUserDialog("Now choose last z plane and click OK...").show() end_z = imp.getZ() frames = imp.getNFrames() channels = imp.getNChannels() imp.killRoi() dupimp = Duplicator().run(imp, 1, channels, start_z, end_z, 1, frames) imp.hide() dupimp.show() return dupimp, (start_z, end_z)
def cut(event): roi = imp.getRoi() if roi != None: newRoi = roi.clone() Dup = Duplicator().run(imp, 1, imp.getNChannels(), 1, imp.getNSlices(), 1, imp.getNFrames()) newRoi.setLocation(0,0) Dup.setRoi(newRoi) Dup.setTitle(Men.getTextField() + str(Men.getCounter())) Dup.show() #Men.setCounter() Men.addOlay(roi) imp.setOverlay(Men.getOverlay()) #setOverlay(Roi roi, java.awt.Color strokeColor, int strokeWidth, java.awt.Color fillColor) imp.getOverlay().drawLabels(True) # drawNumbers imp.deleteRoi() #make cell instance and add to position instance p.addCell(cell(p.getMainPath(), p, Men.getCounter(), Dup)) # cell(mainPath, position, ID, imp): Dup.close() Men.increaseCounter()
distMin = dist return centPart, (x, y) def isSpecialParticle(image, roim, iParticle, boundariesNuc, boundariesMito, pixelSize, z): try: image.setSlice(int(round(z))) image2 = ImagePlus("slice",image.getProcessor()) roim.select(image2, iParticle) image3 = Duplicator().run(image2); image3.show() sp = segment_Particles() image3 = sp.preprocessImage(image3, "MAX", "C1", 0, 0) image3 = sp.segmentParticles(image3, "Triangle", boundariesNuc[0], boundariesNuc[1], 0, 0) if roim.getCount() > 0: roim.select(image3, 0) stats = image3.getStatistics(Measurements.AREA + Measurements.SHAPE_DESCRIPTORS) IJ.log("Area (um2) " + str(stats.area*pixelSize*pixelSize) + "; Aspect Ratio " + str(stats.major/stats.minor)) if stats.area > boundariesMito[0] and stats.area < boundariesMito[1] and stats.major/stats.minor > boundariesMito[2]: return 1 else: return 0 except BaseException, err:
def qc_background_regions(intensity_imp, bg_rois): """allow the user to view and correct automatically-determined background regions""" imp = Duplicator().run(intensity_imp); imp.setTitle("Background region QC"); imp.show(); imp.setPosition(1); autoset_zoom(imp); imp.setRoi(bg_rois[0]); IJ.setTool("freehand"); notOK = True; while notOK: listener = UpdateRoiImageListener(bg_rois, is_area=True); imp.addImageListener(listener); dialog = NonBlockingGenericDialog("Background region quality control"); dialog.enableYesNoCancel("Continue", "Use this region for all t"); dialog.setCancelLabel("Cancel analysis"); dialog.addMessage("Please redraw background regions as necessary...") dialog.showDialog(); if dialog.wasCanceled(): raise KeyboardInterrupt("Run canceled"); elif not(dialog.wasOKed()): this_roi = imp.getRoi(); bg_rois = [this_roi for _ in listener.getRoiList()]; imp.removeImageListener(listener); else: last_roi = imp.getRoi(); qcd_bg_rois = listener.getRoiList(); if imp.getNFrames() > imp.getNSlices(): qcd_bg_rois[imp.getT() - 1] = last_roi; else: qcd_bg_rois[imp.getZ() - 1] = last_roi; notOK = False; imp.removeImageListener(listener); imp.changes = False; imp.close(); return qcd_bg_rois;
def time_crop(imp, params): """trim a time series based on interactively-defined start and end points""" start_frame = None; end_frame = None; if params.perform_time_crop: if params.time_crop_start_end is not None: start_frame = params.time_crop_start_end[0]; end_frame = params.time_crop_start_end[1]; else: MyWaitForUser("First T...", "Choose first time frame and click OK..."); start_frame = imp.getT(); MyWaitForUser("Last T...", "Now choose last time frame and click OK..."); end_frame = imp.getT(); slices = imp.getNSlices(); channels = imp.getNChannels(); if start_frame is not None: dupimp = Duplicator().run(imp, 1, channels, 1, slices, start_frame, end_frame); imp.changes = False; imp.close(); dupimp.show() autoset_zoom(dupimp); return dupimp, (start_frame, end_frame); else: return imp, (start_frame, end_frame);
class gui(JFrame): def __init__(self): # constructor #origing of coordinates self.coordx = 10 self.coordy = 10 #inintialize values self.Canvas = None #create panel (what is inside the GUI) self.panel = self.getContentPane() self.panel.setLayout(GridLayout(9, 2)) self.setTitle('Subdividing ROIs') #define buttons here: self.Dapi_files = DefaultListModel() mylist = JList(self.Dapi_files, valueChanged=self.open_dapi_image) #mylist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); mylist.setLayoutOrientation(JList.VERTICAL) mylist.setVisibleRowCount(-1) listScroller1 = JScrollPane(mylist) listScroller1.setPreferredSize(Dimension(300, 80)) self.output_files = DefaultListModel() mylist2 = JList(self.output_files) #mylist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); mylist2.setLayoutOrientation(JList.VERTICAL) mylist2.setVisibleRowCount(-1) listScroller2 = JScrollPane(mylist2) listScroller2.setPreferredSize(Dimension(300, 80)) quitButton = JButton("Quit", actionPerformed=self.quit) selectInputFolderButton = JButton("Select Input", actionPerformed=self.select_input) cubifyROIButton = JButton("Cubify ROI", actionPerformed=self.cubify_ROI) saveButton = JButton("Save ROIs", actionPerformed=self.save) summsaveButton = JButton("Save Summary", actionPerformed=self.save_summary) self.textfield1 = JTextField('500') #add buttons here self.panel.add(listScroller1) self.panel.add(listScroller2) self.panel.add(selectInputFolderButton) self.panel.add(Label("Adjust the size of the ROIs")) self.panel.add(self.textfield1) self.panel.add(cubifyROIButton) self.panel.add(saveButton) self.panel.add(summsaveButton) self.panel.add(quitButton) #self.panel.add(saveButton) #self.panel.add(Zslider) #other stuff to improve the look self.pack() # packs the frame self.setVisible(True) # shows the JFrame self.setLocation(self.coordx, self.coordy) #define functions for the buttons: def quit(self, event): #quit the gui self.dispose() IJ.run("Close All") def select_input(self, event): self.input_path = IJ.getDirectory( "Select Directory containing your data") # get the files in that directory self.input_files = listdir(self.input_path) self.input_dapi = [s for s in self.input_files if "DAPI.tif" in s] self.core_names = get_core_names(self.input_dapi) # create output directory self.output_path = path.join( path.dirname(path.dirname(self.input_path)), "Cubified_ROIs") if path.isdir(self.output_path): print "Output path already created" else: mkdir(self.output_path) print "Output path created" # get the processed data self.processed_files = listdir(self.output_path) self.out_core_names = get_core_names( get_core_names(self.processed_files) ) # needs the channel and roi to be removed # populate the lists for f in set(self.core_names): if f not in set(self.out_core_names): # skip if processed self.Dapi_files.addElement(f) for f in set(self.out_core_names ): # a set so that only unique ones are shown self.output_files.addElement(f) def open_dapi_image(self, e): sender = e.getSource() IJ.run("Close All") if not e.getValueIsAdjusting(): self.name = sender.getSelectedValue() print self.name dapi_filename = path.join(self.input_path, self.name + '_DAPI.tif') #print dapi_filename if not path.exists(dapi_filename): print "I don't find the DAPI file, which is weird as I just found it before" else: #open stack and make the reslice self.dapi_image = ImagePlus(dapi_filename) #read the image # duplicate image to play with that one, and do the real processing in the background self.imp_main = Duplicator().run(self.dapi_image) self.imp_main.setTitle(self.name) self.imp_main.show() #show image on the left #self.original_image.getWindow().setLocation(self.coordx-self.original_image.getWindow().getWidth()-10,self.coordy-10) #reposition image def cubify_ROI(self, e): self.L = int(self.textfield1.text) # get info tit = self.imp_main.getTitle() self.roi = self.imp_main.getRoi() # get corners corners = get_corners(self.roi, self.L) self.corners_cleaned = clean_corners(corners, self.roi, self.L) print 'found corners' # get the overlay self.ov = overlay_corners(self.corners_cleaned, self.L) self.ov = overlay_roi(self.roi, self.ov) # write roi name self.ov = write_roi_numbers(self.ov, self.corners_cleaned, self.L) # overlay self.imp_main.setOverlay(self.ov) self.imp_main.updateAndDraw() def save(self, e): # open the other channels d1_filename = path.join(self.input_path, self.name + '_D1.tif') d2_filename = path.join(self.input_path, self.name + '_D2.tif') self.d1_image = ImagePlus(d1_filename) #read the image print "d1 image opened" self.d2_image = ImagePlus(d2_filename) #read the image print "d2 image opened" for image in [self.dapi_image, self.d1_image, self.d2_image]: print "saving rois for image " + image.getTitle() save_rois(image, self.corners_cleaned, self.L, self.output_path) print "ROIs saved" def save_summary(self, e): IJ.selectWindow(self.name) IJ.run("Flatten") imp = IJ.getImage() # downsample # scale ENLARGING or SHRINKING the canvas dimensions scale_factor = .2 new_width = str(int(imp.getWidth() * scale_factor)) new_height = str(int(imp.getHeight() * scale_factor)) IJ.selectWindow(self.name + "-1") str_to_scale = "x=" + str(scale_factor) + " y=" + str( scale_factor ) + " width=" + new_width + " height=" + new_height + " interpolation=Bilinear average create" IJ.run("Scale...", str_to_scale) # save imp2 = IJ.getImage() #IJ.saveAs("Tiff", path.join(OUTDIR, self.name + "_summaryOfROIs")) IJ.saveAsTiff( imp2, path.join(self.output_path, self.name + "_summaryOfROIs.tif")) print "summary image saved"
######### open image using dialogue box #imp = IJ.getImage() original = IJ.openImage(getFile()) original.show() ########## Use thresholding and selection to define UFOV ################################################################################### #IJ.run("ROI Manager...", "") # not sure if I need this IJ.setRawThreshold(original, 1, 255,'') # background pixels have value 0. See IMAGE>ADJUST>THRESHOLD IJ.run(original, "Create Selection", "") # add bounding box. See EDIT>SELECTION IJ.run(original,"To Bounding Box", "") # this box defines the UFOV. See EDIT>SELECTION IJ.resetThreshold(original) # get back original now UFOV is definedthresholding UFOV = Duplicator().run(original) # duplicate the original image, only the CFOV UFOV.setTitle("UFOV") UFOV.show() CFOV_fraction = 0.75 # choose the fraction of the UFOV that defines the CFOV IJ.run(original,"Scale... ", "x="+str(CFOV_fraction)+" y="+str(CFOV_fraction)+" centered") # rescale bounding box to get CFOV CFOV = Duplicator().run(original) # duplicate the original image, only the CFOV CFOV.setTitle("CFOV") CFOV.show() ######### Nema process including Re-bin image to larger pixels ################################################################################ desired_pixel_width = getPixel() # 6.4 mm default, remember tolerance is +/-30% current_pixel_width = CFOV.getCalibration().pixelWidth #get pixel width, 1.16 mm shrink_factor = int(desired_pixel_width/current_pixel_width) # must be an integer IJ.run(CFOV, "Bin...", "x="+str(shrink_factor)+" y="+str(shrink_factor)+" bin=Sum") # run the bin plugin
def runOneFile(fullFilePath): global gFileType 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) 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 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 do_angular_projection(imp, max_r_pix=60, min_r_pix=10, generate_roi_stack=True): """perform ray-based projection of vessel wall, c.f. ICY TubeSkinner (Lancino 2018)""" Prefs.blackBackground = True print("do angular projection input imp = " + str(imp)) split_chs = ChannelSplitter().split(imp) mch_imp = split_chs[0] IJ.setAutoThreshold(mch_imp, "IsoData dark stack") egfp_imp = split_chs[1] proj_imp = Duplicator().run(egfp_imp) cl_imp = split_chs[2] if generate_roi_stack: egfp_imp_disp = Duplicator().run(egfp_imp) roi_stack = IJ.createImage("rois", egfp_imp.getWidth(), egfp_imp.getHeight(), egfp_imp.getNSlices(), 16) centres = [] projected_im_pix = [] ring_rois = [] for zidx in range(cl_imp.getNSlices()): if ((zidx + 1) % 100) == 0: print("Progress = " + str(round(100 * (float(zidx + 1) / cl_imp.getNSlices())))) projected_im_row = [] proj_imp.setZ(zidx + 1) mch_imp.setZ(zidx + 1) bp = mch_imp.createThresholdMask() bp.dilate() bp.erode() bp.erode() bp.erode() mask_imp = ImagePlus("mask", bp) IJ.run(mask_imp, "Create Selection", "") roi = mask_imp.getRoi() proj_imp.setRoi(roi) IJ.run(proj_imp, "Set...", "value=0 slice") IJ.run(proj_imp, "Make Inverse", "") roi = proj_imp.getRoi() centre = (roi.getStatistics().xCentroid, roi.getStatistics().yCentroid) centres.append(centre) ring_roi_xs = [] ring_roi_ys = [] for theta in range(360): pt1 = (centre[0] + min_r_pix * math.cos(math.radians(theta)), centre[1] + min_r_pix * math.sin(math.radians(theta))) pt2 = (centre[0] + max_r_pix * math.cos(math.radians(theta)), centre[1] + max_r_pix * math.sin(math.radians(theta))) roi = Line(pt1[0], pt1[1], pt2[0], pt2[1]) proj_imp.setRoi(roi) profile = roi.getPixels() projected_im_row.append(max(profile)) try: ring_roi_xs.append(roi.getContainedPoints()[profile.index( max(profile))].x) except IndexError: ring_roi_xs.append(pt2[0]) try: ring_roi_ys.append(roi.getContainedPoints()[profile.index( max(profile))].y) except IndexError: ring_roi_ys.append(pt2[1]) proj_imp.killRoi() ring_roi = PolygonRoi(ring_roi_xs, ring_roi_ys, Roi.FREELINE) ring_rois.append(ring_roi) if generate_roi_stack: roi_stack.setZ(zidx + 1) roi_stack.setRoi(ring_roi) IJ.run(roi_stack, "Line to Area", "") IJ.run( roi_stack, "Set...", "value=" + str(roi_stack.getProcessor().maxValue()) + " slice") #egfp_imp.setRoi(ring_roi); projected_im_pix.append(projected_im_row) # for ch in split_chs: # ch.close(); out_imp = ImagePlus( "projected", FloatProcessor([list(x) for x in zip(*projected_im_pix)])) if generate_roi_stack: roi_stack.show() egfp_imp_disp.show() # merge? else: roi_stack = None return out_imp, roi_stack, ring_rois, centres
def analyze(iDataSet, tbModel, p, output_folder): # # LOAD FILES # filepath = tbModel.getFileAPth(iDataSet, "RAW", "IMG") filename = tbModel.getFileName(iDataSet, "RAW", "IMG") print("Analyzing: "+filepath) IJ.run("Bio-Formats Importer", "open=["+filepath+"] color_mode=Default view=Hyperstack stack_order=XYCZT"); imp = IJ.getImage() # # INIT # IJ.run("Options...", "iterations=1 count=1"); # # SCALING # IJ.run(imp, "Scale...", "x="+str(p["scale"])+" y="+str(p["scale"])+" z=1.0 interpolation=Bilinear average process create"); imp = IJ.getImage() # save output file output_file = filename+"--downscale_input.tif" IJ.saveAs(IJ.getImage(), "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "INPUT","IMG") # # CONVERSION # #IJ.run(imp, "8-bit", ""); # # CROPPING # #imp.setRoi(392,386,750,762); #IJ.run(imp, "Crop", ""); # # BACKGROUND SUBTRACTION # # IJ.run(imp, "Subtract...", "value=32768 stack"); IJ.run(imp, "Z Project...", "projection=[Average Intensity]"); imp_avg = IJ.getImage() ic = ImageCalculator(); imp = ic.run("Subtract create 32-bit stack", imp, imp_avg); # # REGION SEGMENTATION # imp1 = Duplicator().run(imp, 1, imp.getImageStackSize()-1) imp2 = Duplicator().run(imp, 2, imp.getImageStackSize()) imp_diff = ic.run("Subtract create 32-bit stack", imp1, imp2); #imp_diff.show() IJ.run(imp_diff, "Z Project...", "projection=[Standard Deviation]"); imp_diff_sd = IJ.getImage() # save IJ.run(imp_diff_sd, "Gaussian Blur...", "sigma=5"); output_file = filename+"--sd.tif" IJ.saveAs(imp_diff_sd, "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "SD","IMG") IJ.run(imp_diff_sd, "Enhance Contrast", "saturated=0.35"); IJ.run(imp_diff_sd, "8-bit", ""); IJ.run(imp_diff_sd, "Properties...", "unit=p pixel_width=1 pixel_height=1 voxel_depth=1"); IJ.run(imp_diff_sd, "Auto Local Threshold", "method=Niblack radius=60 parameter_1=2 parameter_2=0 white"); rm = ROIManipulator.getEmptyRm() IJ.run(imp_diff_sd, "Analyze Particles...", "add"); # select N largest Rois diameter_roi = [] for i in range(rm.getCount()): roi = rm.getRoi(i) diameter_roi.append([roi.getFeretsDiameter(), roi]) diameter_roi = sorted(diameter_roi, reverse=True) #print diameter_roi rm.reset() for i in range(min(len(diameter_roi), p["n_rois"])): rm.addRoi(diameter_roi[i][1]) # save output_file = filename+"--rois" ROIManipulator.svRoisToFl(output_folder, output_file, rm.getRoisAsArray()) tbModel.setFileAPth(output_folder, output_file+".zip", iDataSet, "REGIONS","ROI") # # FFT in each region # IJ.run(imp, "Variance...", "radius=2 stack"); output_file = filename+"--beats.tif" IJ.saveAs(imp, "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "BEATS","IMG") n = rm.getCount() for i_roi in range(n): imp_selection = Duplicator().run(imp) rm.select(imp_selection, i_roi) IJ.run(imp_selection, "Clear Outside", "stack"); imp_selection.show() # FFT using Parallel FFTJ transformer = FloatTransformer(imp_selection.getStack()) transformer.fft() imp_fft = transformer.toImagePlus(SpectrumType.FREQUENCY_SPECTRUM) imp_fft.show() # Analyze FFt IJ.run(imp_fft, "Gaussian Blur 3D...", "x=0 y=0 z=1.5"); IJ.run(imp_fft, "Plot Z-axis Profile", ""); output_file = filename+"--Region"+str(i_roi+1)+"--fft.tif" IJ.saveAs(IJ.getImage(), "TIFF", os.path.join(output_folder, output_file)) tbModel.setFileAPth(output_folder, output_file, iDataSet, "FFT_R"+str(i_roi+1),"IMG") IJ.run(imp_fft, "Select All", ""); rm.addRoi(imp_fft.getRoi()) rm.select(rm.getCount()) rt = ResultsTable() rt = rm.multiMeasure(imp_fft); #print(rt.getColumnHeadings); x = rt.getColumn(rt.getColumnIndex("Mean1")) #rm.runCommand("delete") peak_height_pos = [] x_min = 10 for i in range(x_min,len(x)/2): before = x[i-1] center = x[i] after = x[i+1] if (center>before) and (center>after): peak_height_pos.append([float(x[i]),i]) if len(peak_height_pos)>0: peak_height_pos = sorted(peak_height_pos, reverse=True) n_max = 3 for i_max in range(min(len(peak_height_pos),n_max)): tbModel.setNumVal(round(float(len(x))/float(peak_height_pos[i_max][1]),2), iDataSet, "F"+str(i_max+1)+"_R"+str(i_roi+1)) tbModel.setNumVal(int(peak_height_pos[i_max][0]), iDataSet, "A"+str(i_max+1)+"_R"+str(i_roi+1))
reload(Utility) import CountParticles reload(CountParticles) from CountParticles import countParticles #inputDirectory='/home/bnorthan/Brian2012/Round2/RogueImageJPlugins/SpotDetection/Images/' #inputName='001-D0_cropped.tif' #dataset=data.open(inputDirectory+inputName) #display.createDisplay(dataset.getName(), dataset) inputImp=IJ.getImage() inputDataset=Utility.getDatasetByName(data, inputImp.getTitle()) truecolor1=Duplicator().run(inputImp) truecolor1.show() # get the roi that will be processed inputRoi=inputImp.getRoi().clone() inputRec = inputRoi.getBounds() x1=long(inputRec.getX()) y1=long(inputRec.getY()) x2=x1+long(inputRec.getWidth())-1 y2=y1+long(inputRec.getHeight())-1 # crop the roi interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') ) cropped=ops.crop(interval, None, inputDataset.getImgPlus() ) dataset=data.create(cropped)
########## Use thresholding and selection to define UFOV ################################################################################### #IJ.run("ROI Manager...", "") # not sure if I need this IJ.setRawThreshold( original, 1, 255, '') # background pixels have value 0. See IMAGE>ADJUST>THRESHOLD IJ.run(original, "Create Selection", "") # add bounding box. See EDIT>SELECTION IJ.run(original, "To Bounding Box", "") # this box defines the UFOV. See EDIT>SELECTION IJ.resetThreshold( original) # get back original now UFOV is definedthresholding UFOV = Duplicator().run( original) # duplicate the original image, only the CFOV UFOV.setTitle("UFOV") UFOV.show() CFOV_fraction = 0.75 # choose the fraction of the UFOV that defines the CFOV IJ.run(original, "Scale... ", "x=" + str(CFOV_fraction) + " y=" + str(CFOV_fraction) + " centered") # rescale bounding box to get CFOV CFOV = Duplicator().run( original) # duplicate the original image, only the CFOV CFOV.setTitle("CFOV") CFOV.show() ######### Nema process including Re-bin image to larger pixels ################################################################################ desired_pixel_width = getPixel( ) # 6.4 mm default, remember tolerance is +/-30% current_pixel_width = CFOV.getCalibration( ).pixelWidth #get pixel width, 1.16 mm
# ROI CREATION image_mip.show() image_mip.setRoi(image_mip.width / 2, image_mip.height / 2, regionSize, regionSize) from ij.gui import WaitForUserDialog myWait = WaitForUserDialog("Choose ROI", "Please position the ROI.. Press 'OK' when done.") myWait.show() # CROP image.setRoi(image_mip.getRoi()) from ij import IJ image = Duplicator().run(image) image.show() image_mip.close() image = ImageJFunctions.wrap(image) # def roi(mask, image): # Convert ROI from R^n to Z^n. #discreteROI = Views.raster(Masks.toRealRandomAccessible(mask)) # Apply finite bounds to the discrete ROI. boundedDiscreteROI = Views.interval(mask, image) # Create an iterable version of the finite discrete ROI. iterableROI = Regions.iterable(boundedDiscreteROI) return Regions.sample(iterableROI, image)
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(): #print (sys.version_info) # debug #print(sys.path) # debug data_root = r'C:\Users\dougk\Desktop\test' # debug output_root = r'C:\Users\dougk\Desktop\test' #debug #default_directory = r'C:\\Users\\Doug\\Desktop\\test'; #data_root, output_root = file_location_chooser(default_directory); if (data_root is None) or (output_root is None): raise IOError("File location dialogs cancelled!") timestamp = datetime.strftime(datetime.now(), "%Y-%m-%d %H.%M.%S") output_path = os.path.join(output_root, (timestamp + " output")) for file_path in filterByFileType(os.listdir(data_root), '.tif'): subfolder_name = os.path.splitext(file_path)[0] output_subfolder = os.path.join(output_path, subfolder_name) print(output_subfolder) os.makedirs(output_subfolder) imps = bf.openImagePlus(os.path.join(data_root, file_path)) imp = imps[0] imp.show() h = imp.height w = imp.width slices = imp.getNSlices() channels = imp.getNChannels() frames = imp.getNFrames() # rotation step - since using multiples of 90, TransformJ.Turn is more efficient IJ.run("Enhance Contrast", "saturated=0.35") angleZ = 1 while ((angleZ % 90) > 0): gd = GenericDialog("Rotate?") gd.addMessage( "Define rotation angle - increments of 90. Apical at top") gd.addNumericField("Rotation angle", 0, 0) gd.showDialog() angleZ = int(gd.getNextNumber()) if (angleZ > 1): IJ.run("TransformJ Turn", "z-angle=" + str(angleZ) + " y-angle=0 x-angle=0") imp.close() imp = WindowManager.getCurrentImage() imp.setTitle(file_path) # trim time series IJ.run("Enhance Contrast", "saturated=0.35") imp.setDisplayMode(IJ.COLOR) WaitForUserDialog( "Scroll to the first frame of the period of interest and click OK" ).show() start_frame = imp.getT() WaitForUserDialog( "Scroll to the last frame of the period of interest and click OK" ).show() end_frame = imp.getT() trim_imp = Duplicator().run(imp, 1, channels, 1, slices, start_frame, end_frame) imp.close() trim_imp.show() dup_imp = Duplicator().run(trim_imp) # create images to process and find bounds for dup_imps = ChannelSplitter().split(dup_imp) myo_imp = dup_imps[1] mem_imp = dup_imps[0] FileSaver(myo_imp).saveAsTiffStack( os.path.join(output_subfolder, "myosin_channel.tif")) FileSaver(mem_imp).saveAsTiffStack( os.path.join(output_subfolder, "membrane_channel.tif")) # set basal bounds myo_imp.show() ImageConverter(myo_imp).convertToGray8() frames = myo_imp.getNFrames() gb = GaussianBlur() for fridx in range(0, frames): myo_imp.setSliceWithoutUpdate(fridx + 1) ip = myo_imp.getProcessor() gb.blurGaussian(ip, 5.0, 1.0, 0.02) # assymmetrical Gaussian IJ.run(myo_imp, "Convert to Mask", "method=Otsu background=Dark calculate") IJ.run("Despeckle", "stack") title = myo_imp.getTitle() # assume that first frame is good quality image... basal_edges = find_basal_edges(myo_imp) #myo_imp.hide() mem_imp.hide() # draw some edges for checking roim = RoiManager() xs = [x for x in range(1, trim_imp.getWidth() + 1)] trim_imp.show() for fridx in range(0, myo_imp.getNFrames()): trim_imp.setPosition(2, 1, fridx + 1) IJ.run("Enhance Contrast", "saturated=0.35") roi = PolygonRoi(xs, basal_edges[fridx], Roi.POLYLINE) trim_imp.setRoi(roi) roim.addRoi(roi)
# apply a threshold to detect objects (cells, nuclei,...) IJ.setAutoThreshold(imp, "Otsu") Prefs.blackBackground = False IJ.run(imp, "Convert to Mask", "") # analyse objects and put results in table IJ.run("Set Measurements...", "area display redirect=None decimal=5") IJ.run(imp, "Analyze Particles...", "exclude add") manager = RoiManager.getRoiManager() manager.runCommand("Save", file.toString() + ".RoiSet.zip") for roi in manager.getRoisAsArray(): copy.setRoi(roi) copy.show() IJ.run(copy, "Enlarge...", "enlarge=-2") # analyse the image statistics = copy.getStatistics() print("mean: " + str(statistics.mean)) print("area:" + str(statistics.area)) # write the analysed valurs in a table table = ResultsTable.getResultsTable() table.incrementCounter() table.addValue("filename", file.toString()) table.addValue("mean_robert", statistics.mean) table.addValue("area", statistics.area) table.addValue("total instensity", statistics.mean * statistics.area)
reload(Utility) import CountParticles reload(CountParticles) from CountParticles import countParticles #inputDirectory='/home/bnorthan/Brian2012/Round2/RogueImageJPlugins/SpotDetection/Images/' #inputName='001-D0_cropped.tif' #dataset=data.open(inputDirectory+inputName) #display.createDisplay(dataset.getName(), dataset) inputImp = IJ.getImage() inputDataset = Utility.getDatasetByName(data, inputImp.getTitle()) truecolor1 = Duplicator().run(inputImp) truecolor1.show() # get the roi that will be processed inputRoi = inputImp.getRoi().clone() inputRec = inputRoi.getBounds() x1 = long(inputRec.getX()) y1 = long(inputRec.getY()) x2 = x1 + long(inputRec.getWidth()) - 1 y2 = y1 + long(inputRec.getHeight()) - 1 # crop the roi interval = FinalInterval(array([x1, y1, 0], 'l'), array([x2, y2, 2], 'l')) cropped = ops.crop(interval, None, inputDataset.getImgPlus()) dataset = data.create(cropped)
#print(centres); for ch in split_chs: ch.close() w = len(projected_im_row) h = len(projected_im_pix) ip = FloatProcessor(w, h) pix = ip.getPixels() for x in range(w): for y in range(h): pix[y * w + x] = projected_im_pix[y][x] out_imp = ImagePlus("projected", ip) out_imp.show() egfp_imp_disp.show() roi_stack.show() #egfp_imp_disp.addImageListener(UpdateRoiImageListener(ring_rois)); unwrapped_imp = IJ.createImage("twisted unwrap", 2 * out_imp.getWidth(), out_imp.getHeight(), 1, 32) unwrapped_imp.show() IJ.setTool("freeline") WaitForUserDialog("input unwrap axis").show() unwrap_poly = out_imp.getRoi().getPolygon() unwrap_poly_xs #print("unzip axis = " + str(unzip_axis)); #right_side_xs = unzip_axis; #right_side_xs.append(out_imp.getWidth()); #right_side_xs.append(out_imp.getWidth());
str(metadata['x_unit']) + " pixel_width=" + str(metadata['x_physical_size']) + " pixel_height=" + str(metadata['y_physical_size']) + " voxel_depth=" + str(metadata['z_extent'] / metadata['z_pixels'])) imp.show() imp, z_lims = z_crop(imp) use_ch = imp.getC() print(use_ch) IJ.setTool("rect") imp.hide() imp2 = ZProjector.run(imp, "max") imp2.show() imp2.setC(use_ch + 1) WaitForUserDialog("Select XY region to crop...").show() crop_roi = imp2.getRoi() imp2.close() imp.show() imp.setRoi(crop_roi) IJ.run("Crop", "") frames = imp.getNFrames() slices = imp.getNSlices() imp = Duplicator().run(imp, use_ch + 1, use_ch + 1, 1, slices, 1, frames) imp.show() # now do 3d segmentation.... #histo = StackStatistics(imp).histogram; #global_thr = AutoThresholder().getThreshold(AutoThresholder.Method.IJ_IsoData, histo) + 1; #print(global_thr); #IJ.run(imp, "3D Simple Segmentation", "low_threshold=" + str(global_thr) + " min_size=200 max_size=-1"); #segimp = WM.getImage("Seg");