def rotationNcropping(folder_in, folder_out): """ Function to rotate a set of 3D images such a a way the struts of the scaffold the scaffols are alligned with x and y directions """ for filename in os.listdir(folder_in): imp = IJ.openImage(os.path.join(folder_in, filename)) IJ.run( imp, "TransformJ Rotate", "z-angle=9 y-angle=-6 x-angle=0.0 interpolation=Linear background=0.0" ) imp = IJ.getImage() stack = imp.getImageStack() stackcropped = stack.crop(130, 64, 77, 1356, 1296, 1540) imp = ImagePlus("2", stackcropped) output = "nrrd=[" + folder_out + filename + "]" IJ.run(imp, "Nrrd ... ", output) imp.close() imp = None stack = None stackcropped = None gc.collect() time.sleep(15) gc.collect() IJ.run("Collect Garbage", "") IJ.run("Collect Garbage", "") IJ.getImage().close()
def preview_Z(imp,numRep,prePickZ): #duplicate another copy without changing original IJ.run(imp,"Duplicate...", "title=zMaxTemp duplicate range=1-%d" %imp.getNSlices()) zMaxTemp=IJ.getImage() IJ.run(zMaxTemp,"8-bit", "") nSlice_real=zMaxTemp.getNSlices()/numRep #transvert dimension from t along Z to Z along t IJ.run(zMaxTemp,"Stack to Hyperstack...", "order=xytzc channels=1 slices="+str(nSlice_real)+" frames="+str(numRep)+" display=Color") IJ.run(zMaxTemp, "Hyperstack to Stack", "") if prePickZ == 0: #first Z project would be first slice IJ.run(zMaxTemp,"Duplicate...", "title=Max_z duplicate range=1-1" ) zMax=IJ.getImage() else: IJ.run(zMaxTemp, "Z Project...", "start=1 stop="+str(prePickZ)+" projection=[Max Intensity]") zMax=IJ.getImage() zMax.getWindow().setLocation(0,580) #set zoom IJ.run(zMax,"Set... ", "zoom=" + str(mZoom/2) +" x=0 y=0") zMax.setTitle("Max_Z") #close input stack without saving zMaxTemp.changes=0 zMaxTemp.close() return zMax
def split_channels_red(imp): #Create red channel original_red = ChannelSplitter.getChannel(imp, 1) original_red_IP = ImagePlus(filename, original_red) fs = FileSaver(original_red_IP) folder = "/Users/gceleste/Desktop/test/channels" filepath = folder + "/" + "{}_redchannel.tif".format(filename) fs.saveAsTiff(filepath) #Open red channel image. red = IJ.open(filepath) #red_IP = ImagePlus(filename, red) IJ.run( "3D Objects Counter", "threshold=130 slice=1 min.=50 max.=1447680 exclude_objects_on_edges objects summary" ) #Save red object map. red_map = IJ.getImage() fs = FileSaver(red_map) folder = "/Users/gceleste/Desktop/test/object maps" filepath = folder + "/" + "{}_objectmap(red).jpg".format(filename) fs.saveAsJpeg(filepath) #Close red channel images. red_map.close() red = IJ.getImage() red.close()
def split_channels_blue(imp): #Create blue channel original_blue = ChannelSplitter.getChannel(imp, 3) original_blue_IP = ImagePlus(filename, original_blue) fs = FileSaver(original_blue_IP) folder = "/Users/gceleste/Desktop/test/channels" filepath = folder + "/" + "{}_bluechannel.tif".format(filename) fs.saveAsTiff(filepath) #Open blue channel image. blue = IJ.open(filepath) #blue_IP = ImagePlus(filename, blue) IJ.run( "3D Objects Counter", "threshold=100 slice=1 min.=50 max.=1447680 exclude_objects_on_edges objects summary" ) #Save blue object map blue_map = IJ.getImage() fs = FileSaver(blue_map) folder = "/Users/gceleste/Desktop/test/object maps" filepath = folder + "/" + "{}_objectmap(blue).jpg".format(filename) fs.saveAsJpeg(filepath) #Close blue channel image. blue_map.close() blue = IJ.getImage() blue.close()
def getOptions(dest): ###function that allows the user to choose their next course of action### # colorscale() gd = NonBlockingGenericDialog("Continue?") gd.setCancelLabel("Quit") gd.enableYesNoCancel("Remain on Image", "Open Next") gd.showDialog() if gd.wasCanceled(): # quits imp = IJ.getImage() current_title = imp.getTitle() imp.close() renamer(dest, current_title, extension) exit() elif gd.wasOKed(): # remains on image count_options = 0 return else: # opens the next image in a directory. count_options = 1 imp = IJ.getImage() current_title = imp.getTitle() imp.close() renamer(dest, current_title, extension) file_opener(current_title, extension) imp = IJ.getImage() imp.setDisplayMode(IJ.GRAYSCALE) colorscale() imp = IJ.getImage() win = imp.getWindow() win.maximize() win.setLocation(int(xpos_def), int(ypos_def)) getOptions(dest)
def modulation_contrast(raw_image_title, sir_image_title, do_map): IJ.selectWindow(raw_image_title) IJ.run("Modulation Contrast", "angles=3 phases=5 z_window_half-width=1") output_images = [] if do_map: IJ.run( "Modulation Contrast Map", "calculate_mcnr_from_raw_data=" + raw_image_title + " camera_bit_depth=16 or,_specify_mcnr_stack=" + raw_image_title.rsplit('.', 1)[0] + "_MCN reconstructed_data_stack=" + sir_image_title) IJ.selectWindow(sir_image_title.rsplit('.', 1)[0] + '_MCM') mcm_imp = IJ.getImage() output_images.append(mcm_imp) IJ.selectWindow(raw_image_title.rsplit('.', 1)[0] + '_MCN') mcn_imp = IJ.getImage() IJ.setMinAndMax(0, 255) IJ.run("8-bit") output_images.append(mcn_imp) statistics = {} statistics.update(parse_log('average feature MCNR = ')) statistics.update(parse_log('estimated Wiener filter optimum = ')) return output_images, statistics
def extract_structures(imp, folder, ost_ch, vasc_ch): n = imp.getNFrames() name = imp.getTitle() if struct_exp: imp2 = extract_channel(imp,1,n,ost_ch) imp2.show() IJ.run("Re-order Hyperstack ...", "channels=[Channels (c)] slices=[Frames (t)] frames=[Slices (z)]"); IJ.run("Z Project...", "start=1 stop="+str(n)+" projection=[Median] all"); imp2 = IJ.getImage() IJ.run(imp2,"Auto Threshold", "method=Moments white stack use_stack_histogram"); IJ.run(imp2,"Invert", "stack"); IJ.run("Exact Euclidean Distance Transform (3D)"); imp2 = IJ.getImage() FileSaver(ImagePlus("export",imp2.getStack())).saveAsTiffStack(folder+exp_name+"_osteoblasts.tif") imp2.close() if vasc_exp: imp2 = extract_channel(imp,1,n,vasc_ch) imp2.show() IJ.run("Re-order Hyperstack ...", "channels=[Channels (c)] slices=[Frames (t)] frames=[Slices (z)]"); IJ.run("Z Project...", "start=1 stop="+str(n)+" projection=[Median] all"); imp2 = IJ.getImage() IJ.run(imp2,"Auto Threshold", "method=Moments white stack use_stack_histogram"); IJ.run(imp2,"Invert", "stack"); IJ.run("Exact Signed Euclidean Distance Transform (3D)"); imp2 = IJ.getImage() FileSaver(ImagePlus("export",imp2.getStack())).saveAsTiffStack(folder+exp_name+"_vasculature.tif") imp2.close()
def save_all(srcDir, dstDir, filename, localfile, keepDirectories, imageID): saveDir = currentDir.replace(srcDir, dstDir) if keepDirectories else dstDir if not os.path.exists(saveDir): os.makedirs(saveDir) print "Saving to", saveDir IJ.selectWindow("Results for PA ") IJ.saveAs("Text", ""+saveDir+"\\"+localfile+".xls") IJ.selectWindow(imageID); imp=IJ.getImage() IJ.run("Duplicate...", "duplicate channels="+str(y)+"") #brightfield channel IJ.run("Z Project...", "projection=[Sum Slices]") rm= RoiManager(True) rm.runCommand("Show All without labels") rm.runCommand("Set Color", "red") rm.runCommand("Set Line Width", str(4)) imp=IJ.getImage() IJ.saveAs(imp,"Tiff", ""+saveDir+"\\"+localfile+"_OV.tif") rm.runCommand("Show None") IJ.saveAs(imp,"Tiff", ""+saveDir+"\\"+localfile+".tif") IJ.selectWindow("IMAGE") imp=IJ.getImage() IJ.saveAs(imp, "Tiff", os.path.join(saveDir, filename)) ROInumber = rm.getCount() if(ROInumber>0): RoiManager("Delete")
def run(): leftdir = '/Users/rando/Downloads/NLM-MontgomeryCXRSet/MontgomerySet/ManualMask/leftMask/' rightdir = '/Users/rando/Downloads/NLM-MontgomeryCXRSet/MontgomerySet/ManualMask/rightMask/' savedir = '/Users/rando/Downloads/NLM-MontgomeryCXRSet/MontgomerySet/ManualMask/BinaryMask/' Raw_path = os.path.join(leftdir, '*png') X = glob.glob(Raw_path) axes = 'YX' for fname in X: print(fname) IJ.open(fname); imp = IJ.getImage() width = imp.width height = imp.height title_left = imp.getTitle(); print(title_left) Name = os.path.basename(os.path.splitext(fname)[0]) RightName = rightdir + title_left IJ.open(RightName) imp_right = IJ.getImage() title_right = imp_right.getTitle() print(title_right) imp_res = ImageCalculator.run(imp, imp_right, "add create 8-bit"); title = imp_res.getTitle() IJ.saveAs(imp_res, '.tif', savedir + Name); imp.close(); imp_right.close(); imp_res.close();
def editInImJ(folderF, fileDirF): listOfFiles = sorted(os.listdir(fileDirF + "\\" + folder)) mid_slice = len(listOfFiles) / 2 imp = IJ.run( "Image Sequence...", "open=[" + fileDirF + "\\" + folderF + "\\" + listOfFiles[0] + "] number=1 starting=" + str(mid_slice) + " sort") print(mid_slice) imp = IJ.getImage() stats = imp.getStatistics() IJ.run(imp, "Histogram", "") imp = IJ.getImage() IJ.run( imp, "Save", "save=[" + fileDirF + "\\Histogram_of_" + listOfFiles[mid_slice] + "]") GS = 0 print(stats.histogram[0:]) fil = open( fileDirF + "\\" + listOfFiles[mid_slice][:-5] + '_histogram.csv', 'w') print(fileDirF + "\\" + listOfFiles[mid_slice][:-5] + '_histogram.csv') for i in stats.histogram[0:]: fil.write(str(GS) + ', ' + str(i) + '\n') GS += 1 fil.close() IJ.run("Close") IJ.run("Close")
def analyze(imagefile, outdir, size=10000): """Opens a file and creates masks.""" masks = [] image = IJ.openImage(imagefile) imagetitle = image.getTitle().split(".")[0] # close existing Summary window rtframe = WindowManager.getFrame("Summary") if rtframe is not None: rtframe.close() # segmentation IJ.setAutoThreshold(image, "Default dark"); IJ.run(image, "Options...", "iterations=1 count=1 do=Nothing"); #IJ.run(mask, "Convert to Mask", ""); IJ.run(image, "Analyze Particles...", "size=0-"+str(size)+" show=Masks summarize"); masks.append(IJ.getImage()) IJ.run(image, "Analyze Particles...", "size="+str(size)+"-infinity show=Masks summarize"); masks.append(IJ.getImage()) # get ResultsTable object and save it rt = WindowManager.getFrame("Summary").getTextPanel().getResultsTable() rtfile = path.join(outdir, str(size)+"Summary_" + imagetitle + ".csv") rt.save(rtfile) # create multi-color merged mask mergedmask = RGBStackMerge.mergeChannels(masks, False) for m in masks: m.close() mergedmask.setTitle(imagetitle + "-mask.tif") outputfile = path.join(outdir, mergedmask.getTitle()) IJ.saveAs(mergedmask, "TIFF", outputfile)
def run(): global ext, exp, saturated, outputFolder, srcFile IJ1.batchMode = True srcDir = srcFile images, channels = createFileAndChannelsDictionaries(srcDir, exp) outDir = os.path.join(srcDir, outputFolder) if not os.path.exists(outDir): os.makedirs(outDir) numberOfImages = len(images) counter = 1 IJ.log("\\Clear") IJ.log("Convert images from Opera to Hyperstacks...") for image, filename in images.iteritems(): IJ.log("\\Update1:Processing image " + str(counter) + "/" + str(numberOfImages)) nrOfChannels = channels[image] success = openAsHyperstack(filename, image, nrOfChannels) if (success): adjustDisplay(nrOfChannels, saturated) IJ.saveAsTiff(IJ.getImage(), os.path.join(outDir, image + ".tiff")) IJ.getImage().close() counter = counter + 1 IJ.log("Finished !") IJ1.batchMode = False
def ReturnColorThresholdedPicture(PICPATH, L_min, L_max, a_min, a_max, b_min, b_max): imp = IJ.openImage(PICPATH) imp.show() ImageTitle = imp.getTitle() LabThresold_List = [[L_min, L_max], [a_min, a_max], [b_min, b_max]] Filt_List = ["pass", "pass", "pass"] ColorThresholder.RGBtoLab() IJ.run(imp, "RGB Stack", "") IJ.run("Stack to Images", "") IJ.selectWindow("Red") IJ.run('Rename...', 'title=0') #title=hoge =(equal)の間にスペースを入れてならない。 imp0 = IJ.getImage() IJ.selectWindow("Green") IJ.run('Rename...', 'title=1') imp1 = IJ.getImage() IJ.selectWindow("Blue") IJ.run('Rename...', 'title=2') imp2 = IJ.getImage() for i in range(3): WindowTitle = str(i) MinValue = float(LabThresold_List[i][0]) MaxValue = float(LabThresold_List[i][1]) IJ.selectWindow(WindowTitle) IJ.setThreshold(MinValue, MaxValue) IJ.run(IJ.getImage(), "Convert to Mask", "") if Filt_List[i] == "stop": ImageProcessor.invert() #コメントアウトした、imgculcは動かなくなくなった,謎 #imp3 = ImageCalculator.run(imp0, imp1, "and create") #imp4 = ImageCalculator.run(imp3,imp2, "and create") imp3 = ImageCalculator().run("and create", imp0, imp1) imp4 = ImageCalculator().run("and create", imp3, imp2) imp3.show() imp4.show() ResultTitle = imp4.getTitle() IJ.selectWindow(ResultTitle) imp4.setTitle(ImageTitle) #Saveした時点で画像の情報が失われる. imp.close() imp0.close() imp1.close() imp2.close() imp3.close() return imp4
def drawMinima(self): IJ.run("Remove Overlay", "") self.calculateSubtreeMinima() overlay = Overlay() for child in self.children: for spot in child.minima: roi = OvalRoi(spot.x - spot.radius, spot.y - spot.radius, 2 * spot.radius, 2 * spot.radius) overlay.add(roi) IJ.getImage().setOverlay(overlay)
def drawMinima(minima): rt = ResultsTable.getResultsTable() X = rt.getColumn(ResultsTable.X_CENTROID) Y = rt.getColumn(ResultsTable.Y_CENTROID) D = rt.getColumn(ResultsTable.FERET) overlay = Overlay() for minimum in minima: index = minima[minimum] r = float(D[index]) / 2 roi = OvalRoi(float(X[index])-r, float(Y[index])-r, float(D[index]), float(D[index])) overlay.add(roi) IJ.getImage().setOverlay(overlay)
def make_MAX(cString): # max projection print "Running MAX projection..." IJ.run("Z Project...", "projection=[Max Intensity] all") # renaming imp = IJ.getImage() # gets the resulting image imp.setTitle("MAX_C" + cString + "-" + scanName + "_raw") imp = IJ.getImage() # gets the resulting image windowName = imp.getTitle() # gets title print "Saving MAX..." IJ.saveAsTiff(imp, os.path.join(scanFolder, windowName))
def saveProfile(nch, top, bottom, staining, genotype, staining_dir, image_name, cd=min_cd, cd_no=0, all_slices=False): if all_slices == True: temp_imp = IJ.getImage() top = temp_imp.NSlices bottom = 1 for j in range(bottom, top + 1): imp1 = IJ.getImage() imp1.setC(nch) imp1.setZ(j) pp1 = ProfilePlot(imp1) s = "profile" + str(j) exec(s + " = pp1.getProfile()") file_name = image_name[:( image_name.rfind('.tif'))] + "_" + staining + ".csv" file_save = staining_dir + file_name if cd == 1: with open(file_save, "w") as text_file: text_file.write("cd,cd_type,x,value") # text_file.close() with open(file_save, "a") as text_file: for j in range(len(eval("profile" + str(top)))): # print([profile1[j], profile2[j] ], max([profile1[j], profile2[j] ])) x = list() for k in range(bottom, top + 1): x.append(eval("profile" + str(k) + "[j]")) #print(x) if intensity_to_process == "max": text_file.write("\n" + str(cd) + "," + str(cd_no) + "," + str(j) + "," + str(max(x))) #print(len(x)) else: #print(int(len(x))) total = 0 for element in x: total = total + eval(element) text_file.write("\n" + str(cd) + "," + str(cd_no) + "," + str(j) + "," + str(total / len(x)))
def fourier_plots(image_title): IJ.selectWindow(image_title) IJ.run("Fourier Plots", "applyWinFunc=True") IJ.selectWindow(image_title.rsplit('.', 1)[0] + '_FTL') ftl_imp = IJ.getImage() # IJ.run("To ROI Manager") # TODO: add ROIs to fourier plots IJ.selectWindow(image_title.rsplit('.', 1)[0] + '_FTR') # TODO: convert to RGB ftr_imp = IJ.getImage() return [ftl_imp, ftr_imp]
def run_tracking(path): batch = 200 tail = 20 file_list = sorted(os.listdir(path)) num = len(file_list) / batch + 1 print num num_batch = batch start_index = 1 for i in range(num): if (i > 0): num_batch = batch + tail start_index = i * batch + 1 - tail order = "open=" + path +" "+ "number=" + str(num_batch) + " "+ \ "starting="+ str(start_index) + " "+ \ "increment=1 scale=100 file=tif" IJ.run("Image Sequence...", order) imp = IJ.getImage() tile_name = imp.getTitle()+'_' + str(start_index)+'-'+\ str(start_index+num_batch-1) imp.setTitle(tile_name) slices = imp.getNSlices() # swap z and t IJ.run("Properties...", "channels=1 slices=1 frames=" \ + str(slices)+" " +\ " pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000") filename = 'exportModel_' + str(start_index)+'-'+\ str(start_index+num_batch-1) + '.xml' track_single_batch(path, filename) print("%d / %d " % (i + 1, num))
def findSeptum(root, show, pos, n=4): from ij import IJ corrImg = IJ.openImage(root + "/%s_SegAnalysis/%s/CorrelationImage.tif" % (bf_prefix, pos)) IJ.run(corrImg, "8-bit", "") #estimate_width extend_line # these parameters can be added also cmd = "line_width=10 high_contrast=250 low_contrast=50 show_junction_points show_ids add_to_manager make_binary method_for_overlap_resolution=NONE sigma=3 lower_threshold=0 upper_threshold=1.36 minimum_line_length=30 maximum=60" if show: cmd += " displayresults" IJ.run(corrImg, "Ridge Detection", cmd) binarylineImg = IJ.getImage() IJ.run(binarylineImg, "Invert", "") binaryImg = IJ.openImage(root + "/%s_SegAnalysis/%s/BinaryImage.tif" % (bf_prefix, pos)) binaryImg.show() IJ.run("Add Image...", "x=0 y=0 opacity=100 zero") binaryImg.hide() binarylineImg.hide() imp2 = binaryImg.flatten() IJ.run(imp2, "8-bit", "") for i in range(n): IJ.run(imp2, "Erode", "") for j in range(n): IJ.run(imp2, "Dilate", "") IJ.saveAsTiff( imp2, d.getPath() + "/%s_SegAnalysis/%s/BinaryImage_with_sep.tif" % (bf_prefix, pos))
def __dia(self, event): IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") #IJ.run("Properties...", "channels=1 slices=1 frames=20 unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000 frame=[1 sec] origin=0,0"); self.__impD = IJ.getImage() self.__isD = self.__impD.getImageStack() self.__display.text = "DIA="+self.__impD.getTitle() self.__initDIA = True
def __init__(self): swing.JFrame.__init__(self, title="Stack Cells") self.__impD = IJ.getImage() self.setDefaultCloseOperation(swing.JFrame.DISPOSE_ON_CLOSE) self.__n=0 self.__widthl = "11" self.__iplist = [] self.__init = False self.__initDIA = False self.__initFLUO = False self.__skip = False self.__avg = True self.__mosa = True self.__maxfinder = True self.__appmedian = True self.__fire = True self.__align = True self.__alignC = False self.__enlarge = True self.__measures = True self.__sens = [] self.__listrois = [] self.__cellsrois = [] self.__Cutoff = 0 self.__labels = [] self.__maxraf = 100.0 self.__minraf = 0.0 self.__conEllipses = False self.__dictCells = {} self.__rm = RoiManager.getInstance() if (self.__rm==None): self.__rm = RoiManager() self.run()
def main(): # Tricky hack to get ImagePlus from IJ1 interface img = IJ.getImage() display = DefaultLegacyService().getInstance().getImageMap().lookupDisplay(img) dataset = DefaultImageDisplayService().getActiveDataset(display) imp = dataset.getImgPlus() # I don't really understand why sometime SCIFIO is not used # When it's not, we can't access to getMetadata() if not isinstance(imp, SCIFIOImgPlus): IJ.showMessage("This image has not been opened with SCIFIO") return # Get metadata metadata = imp.getMetadata() # Why the f**k this is needed ? while isinstance(metadata, AbstractMetadataWrapper): metadata = metadata.unwrap() # Check if metadata are OME or not if isinstance(metadata, Metadata): omeMeta = metadata.getOmeMeta() else: IJ.showMessage("This file does not contain OME metadata") return # Get xml string and print it with spaces indentation xml_string = DefaultOMEXMLService().getOMEXML(omeMeta.getRoot()) xml = dom.parseString(xml_string) xml_string = xml.toprettyxml(indent=" ") IJ.log(xml_string)
def __fluo(self, event): IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") IJ.run("Set Measurements...", "area mean standard modal min centroid shape integrated median skewness kurtosis stack limit display redirect=None decimal=3") self.__impF = IJ.getImage() self.__isF = self.__impF.getImageStack() self.__display.text = "FLUO="+self.__impF.getTitle() self.__initFLUO = True
def main(): #opens the image and gets its name # imp = open_test_img() # imp.show() imp = IJ.getImage() title = imp.getTitle() basename, extension = splitext(title) # does a minimum projection and makes a mask imp_min = ZProjector.run(imp, 'min') ip = imp_min.getProcessor() ip.setThreshold(1, 9999999999, 1) mask = ip.createMask() mask = ImagePlus("mask", mask) # fills in the holes in the mask IJ.run(mask, "Invert", "") IJ.run(mask, "Fill Holes", "") IJ.run(mask, "Invert", "") # converts to list and then finds the crop coordinates px = mask.getProcessor().getPixels() px = [-int(_) for _ in px] #for some reason the 1s are -1 here px = reshape(px, (imp.height, imp.width)) crop_top_left, crop_width, crop_height = find_largest_rectangle_2D(px) # crops the original image imp.setRoi(crop_top_left[0], crop_top_left[1], crop_width, crop_height) imp_cropped = imp.resize(crop_width, crop_height, "bilinear") imp_cropped.setTitle(basename + "_autocrop" + extension) imp_cropped.show()
def Objects3D(_img, impRedirect, mpar={"vmin": 2, "vmax": 100000}, _gui=False): print "Objects3D:" _img.show() impRedirect.show() options = ( "mean_gray_value centroid dots_size=5 font_size=10 show_numbers white_numbers store_results_within_a_table_named_after_the_image_(macro_friendly) redirect_to=[%s]" % impRedirect.title ) # print options print "image: " + _img.title print "redirect to: " + impRedirect.title IJ.run("3D OC Options", options) IJ.run( _img, "3D Objects Counter", "threshold=128 slice=35 min.=%s max.=%s surfaces statistics summary" % (mpar["vmin"], mpar["vmax"]), ) impObjects = IJ.getImage() IJ.run(impObjects, "16 colors", "") # somehow find the number of objects detected and set the LUT IJ.setMinAndMax(impObjects, 0, 2) impObjects.hide() _img.hide() impRedirect.hide() return (impObjects,)
def getTrackRois(resultstable): rt = resultstable nextframeA = rt.getColumn(rt.getColumnIndex('NextFrame')) sliceA = rt.getColumn(rt.getColumnIndex('Slice')) xA = rt.getColumn(rt.getColumnIndex('X')) yA = rt.getColumn(rt.getColumnIndex('Y')) imp = IJ.getImage() donecheckA = list(range(len(nextframeA))) roisA = [] for i, slicenum in enumerate(sliceA): if slicenum == 1: roix = [int(xA[i])] roiy = [int(yA[i])] ci = i print 'Start', roix, roiy count = 0 while (nextframeA[int(ci)] != -1) and (slicenum < 160) and count<160: nexti = int(nextframeA[ci]) nextslice = int(sliceA[nexti]) roix.append(int(xA[nexti])) roiy.append(int(yA[nexti])) #print '...', int(xA[nexti]), int(yA[nexti]) ci = nexti slicenum = nextslice count +=1 #print roix if len(roix) > 1: jroix = jarray.array(roix, 'f') jroiy = jarray.array(roiy, 'f') pr = PolygonRoi(jroix, jroiy , len(roix), Roi.POLYLINE) roisA.append(pr)
def get_percentile(percentile): imp = IJ.getImage() stats = imp.getRawStatistics() hist = stats.histogram() hist_x_min = stats.histMin hist_x_max = stats.histMax hist_x_range = hist_x_max - hist_x_min hist_x_values = [] for bin in range(0, stats.nBins): print("Fraction pixels with intensity in bins 0 to {}".format(bin)) integral = sum(hist[0:bin]) / sum(hist) print(integral) intensity = hist_x_range * bin / stats.nBins hist_x_values.append(intensity) print(intensity) if integral > percentile: threshold_intensity = intensity break else: pass return threshold_intensity
def run(): srcDir = DirectoryChooser("Choose!").getDirectory() if not srcDir: # user canceled dialog return for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Skip non-TIFF files if not filename.endswith(fileID): continue path = os.path.join(root, filename) print path imp = IJ.openImage(path) imp.show() if method=="contrast": IJ.run(imp,"Enhance Contrast", "saturated=0.35"); time.sleep(0.2) IJ.save(imp,path + "_auto.jpeg") imp.changes = False imp.getWindow().close() elif method=="scale": IJ.run(imp, "Scale...", "x=0.2 y=0.2 interpolation=None create title=small"); impScale = IJ.getImage() time.sleep(0.2) IJ.save(impScale,path + "_thumb.jpeg") imp.changes = False imp.getWindow().close() impScale.changes = False impScale.getWindow().close()
def main(tableName, showPlot): image = IJ.getImage(); roi = image.getRoi() if not roi: center = image.getWidth() / 2, image.getHeight() / 2 else: center = roi.getXBase(), roi.getYBase(); table = ResultsTable.getResultsTable(tableName) vectors = getVectorsFromTable(table, center) radialVelocity = calculateRadialVelocityPerTime(vectors, center) radialVelocityAndDistanceByTrack(table, center) stats = Tools.getStatistics(radialVelocity) median = calculateMedian(radialVelocity) rt = ResultsTable.getResultsTable(TABLE_NAME) if not rt: rt = ResultsTable() row = rt.getCounter() rt.setValue("label", row, tableName) rt.setValue("x", row, center[0]) rt.setValue("y", row, center[1]) rt.setValue("mean", row, stats.mean) rt.setValue("stdDev", row, stats.stdDev) rt.setValue("min", row, stats.min) rt.setValue("median", row, median) rt.setValue("max", row, stats.max) rt.show(TABLE_NAME) if showPlot: plot(radialVelocity, center)
def rgb_from_r_g_b(r, g, b, title): """ rgb_from_r_g_b(r, g, b, title) Generate an RGB image from three 8/bit per pixel gray scale images Parameters ---------- r: An ImagePlus The red channel g: An ImagePlus The green channel b: An ImagePlus The blue channel title: a string The title for the image Returns ------- impRGB: An ImagePlus The RGB image """ tiR = r.getTitle() tiG = g.getTitle() tiB = b.getTitle() strTwo = "c1=[%s] c2=[%s] c3=[%s]" % (tiR, tiG, tiB) IJ.run("Merge Channels...", strTwo) impRecon = IJ.getImage() impRecon.show() return(impRecon)
def set_roi_color_and_stroke(int_width, int_R, int_G, int_B): """ set_roi_color_and_stroke(str_color, int_R, int_G, int_B) Set the color and stroke of the current ROI Add to image with Image > Overlay > Add Selection (CMD B) Parameters ========== int_width: integer the width of the stroke, i.e. 6 int_R: integer between 0 and 255 the red component, i.e. 255 int_G integer between 0 and 255 the green component, i.e. 0 int_B integer between 0 and 255 the blue component, i.e. 0 Returns ======= None """ imp = IJ.getImage() roi = imp.getRoi() print(roi) if roi != None: roi.setStrokeWidth(int_width) roi.setStrokeColor(Color(int_R, int_G, int_B)) imp.updateAndRepaintWindow()
def resetpressed(event): self.__ranges.clear() self.__image=IJ.getImage() rm = RoiManager.getInstance() if (rm==None): rm = RoiManager() rm.runCommand("reset") self.__image.killRoi() IJ.setAutoThreshold(self.__image, "MaxEntropy") rt=ResultsTable() pa=ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER+ParticleAnalyzer.CLEAR_WORKSHEET , Measurements.AREA+Measurements.ELLIPSE+Measurements.MEAN, rt, 0.00, 10000.00, 0.00, 1.00) pa.analyze(self.__image) self.__roisArray=[] self.__roisArray=rm.getRoisAsArray() #rm.runCommand("Show All") #rm.runCommand("Select All") #rm.runCommand("Set Color", "blue") IJ.resetThreshold(self.__image) keys=self.__slidersDict.keys() for k in keys: if k.endswith("min"): self.__slidersDict[k].setValue(0) self.__slidersDict[k].repaint() else: self.__slidersDict[k].setValue(self.__slidersDict[k].getMaximum()) self.__slidersDict[k].repaint()
def findSeptum(root, show, pos, n = 4): from ij import IJ corrImg = IJ.openImage(root + "/%s_SegAnalysis/%s/CorrelationImage.tif"% (bf_prefix, pos)) IJ.run(corrImg, "8-bit", ""); #estimate_width extend_line # these parameters can be added also cmd = "line_width=10 high_contrast=250 low_contrast=50 show_junction_points show_ids add_to_manager make_binary method_for_overlap_resolution=NONE sigma=3 lower_threshold=0 upper_threshold=1.36 minimum_line_length=30 maximum=60" if show: cmd += " displayresults" IJ.run(corrImg, "Ridge Detection", cmd); binarylineImg = IJ.getImage() IJ.run(binarylineImg, "Invert", ""); binaryImg = IJ.openImage(root + "/%s_SegAnalysis/%s/BinaryImage.tif" % (bf_prefix, pos)) binaryImg.show() IJ.run("Add Image...", "x=0 y=0 opacity=100 zero"); binaryImg.hide() binarylineImg.hide() imp2 = binaryImg.flatten(); IJ.run(imp2, "8-bit", ""); for i in range(n): IJ.run(imp2, "Erode", ""); for j in range(n): IJ.run(imp2, "Dilate", ""); IJ.saveAsTiff(imp2, d.getPath() + "/%s_SegAnalysis/%s/BinaryImage_with_sep.tif" % (bf_prefix, pos));
def rmVoidCropNpreprocess(folder_in, folder_out, firstFolder, r): """Function to remove voids outside the scaffold(a cropping operation), Adding meta data, stack contrast adjust ment Reducing computational cost is one of the main purpose of this fucntion. The function is written in a way that a set of images run at a time to manage computation time. Here tiff series of a 3D image is converted to a single NRRD file""" for x in range(r): fnum = firstFolder + x print(fnum) folder = folder_in + str(fnum) + "/" output = "nrrd=[" + folder_out + str(fnum) + ".nrrd]" imp = FolderOpener.open(folder) IJ.run( imp, "Properties...", "channels=1 slices=2159 frames=1 unit=[micro meters] pixel_width=0.81 pixel_height=0.81 voxel_depth=0.81" ) stack = imp.getImageStack() stackcropped = stack.crop(404, 644, 480, 1604, 1476, 1678) imp = ImagePlus("1", stackcropped) IJ.run(imp, "Stack Contrast Adjustment", "is") imp = IJ.getImage() IJ.run(imp, "Nrrd ... ", output) imp.close() imp = None stack = None stackcropped = None gc.collect() time.sleep(15) gc.collect() IJ.run("Collect Garbage", "")
def preprocess_slices_giv_im(image_num,file_inpath,file_outpath): imp = IJ.openImage(file_inpath) file_names,rows = getLabels() stack = imp.getImageStack() stack2 = ImageStack(imp.width,imp.height) for j in range(imp.getNSlices()): if rows[j][image_num]== '0': ip = stack.getProcessor(j+1) NormalizeLocalContrast.run(ip, 341, 326, 4, True, True) imagep = ImagePlus("imp",ip) IJ.run(imagep, "Non-local Means Denoising", "sigma=15 smoothing_factor=1 slice") imagep.setRoi(2,0,336,320); IJ.run(imagep, "Level Sets", "method=[Active Contours] use_level_sets grey_value_threshold=50 distance_threshold=0.50 advection=2.20 propagation=1 curvature=1 grayscale=30 convergence=0.0025 region=inside") fimp = IJ.getImage() #fip = fimp.getProcessor() fimp = removeSmallCCs(fimp) fip = fimp.getProcessor() stack2.addSlice(fip) print("process") else: ip = stack.getProcessor(j+1) stack2.addSlice(ip) final_imp = ImagePlus("image",stack2) output = "nrrd=["+file_outpath+"]" IJ.run(final_imp, "Nrrd ... ", output)
def makeStack(stackDir, stackName = "stack"): IJ.run("Image Sequence...", "open="+stackDir+" file = (\"img_.*\") sort") imp = IJ.getImage() #IJ.run("8-bit") fs = FileSaver(imp) print "Saving stack" fs.saveAsTiff(stackDir + "/" +stackName+".tif")
def main(*R): """ Main function """ # Show intial progress bar IJ.showProgress(0, 50) IJ.showStatus("Heterogeneous Z Correction") # Retrieve the values R (with default values) from previous attempts Rstr = "[(-0.05977, 83.3, 78.73),(-0.05976, 41.65, 39.36)]" R = eval(Prefs.get("HetZCorr.R", Rstr)) # Load current image and get infos imp = IJ.getImage() stk = imp.getStack() (sx, sy, sz) = stackSize(stk) cal = imp.getCalibration() # Get unique values val = getUniqueValues(stk) # Get R from dialog R = showDialogR(R, val) # Generate optical model correction = generateModel(stk, R, val) imp.setCalibration(cal) #Show model image correction.show() correction.setSlice(sz) IJ.run(correction, "Enhance Contrast", "saturated=0.35") IJ.run(correction, "Fire", "")
def run(): imp = IJ.getImage() if imp is None: return if not imp.isHyperStack(): print "Not a hyper stack!" return if 1 == imp.getNFrames(): print "There is only one time frame!" return if 1 == imp.getNSlices(): print "To register slices of a stack, use 'Register Virtual Stack Slices'" return dc = DirectoryChooser("Choose target folder") target_folder = dc.getDirectory() if target_folder is None: return # user canceled the dialog if not validate(target_folder): return gd = GenericDialog("Options") channels = [] for ch in range(1, imp.getNChannels()+1 ): channels.append(str(ch)) gd.addChoice("channel:", channels, channels[0]) gd.showDialog() if gd.wasCanceled(): return channel = gd.getNextChoiceIndex() + 1 # zero-based vs_imp = create_registered_hyperstack(imp, target_folder, channel) vs_imp.show()
def autoProcAZtecImage(fwMicrons, wrkDir, barWid=0.1, barHt=9, barFnt=24, barCol="Black", barLoc="Lower Right"): imp = IJ.getImage() fName = imp.getShortTitle() wid = imp.getWidth() argThree = "distance=%g known=%f pixel=1 unit=um" % (wid, fwMicrons) IJ.run(imp, "Set Scale...", argThree) IJ.run(imp, "Enhance Contrast", "saturated=0.35") fs = FileSaver(imp) if path.exists(wrkDir) and path.isdir(wrkDir): print "folder exists:", wrkDir tifName = fName + ".tif" tifPath = path.join(wrkDir, tifName) print(tifPath) if fs.saveAsTiff(tifPath): print "Tif saved successfully at ", tifPath IJ.run(imp, "RGB Color", "") # dummy to get things set foo = imp.duplicate() s2 = "width=%g height=%g font=%g color=%s location=[%s] bold" % (barWid, barHt, barFnt, barCol, barLoc) IJ.run(foo, "Add Scale Bar", s2) # explicitly save preferences Prefs.savePreferences() foo.changes = False foo.close() IJ.run(imp, "Add Scale Bar", s2) fs = FileSaver(imp) pngName = fName + ".png" pngPath = path.join(wrkDir, pngName) if fs.saveAsPng(pngPath): print "png saved successfully at ", pngPath
def run(): srcDir = DirectoryChooser("Choose!").getDirectory() if not srcDir: # user canceled dialog return # Assumes all files have the same size filepaths = [] pattern = re.compile('ch1(.*)_(.*)transformed.mha') for root, directories, filenames in os.walk(srcDir): for filename in filenames: # Skip non-TIFF files match = re.search(pattern, filename) if (match == None) or (match.group(1) == None): continue print(filename) path = os.path.join(root, filename) filepaths.append(path) # Upon finding the first image, initialize the VirtualStack vs = None sorted_filepaths = sorted(filepaths) for f in sorted(filepaths): IJ.openImage(f) print(f.split('\\')[-1]) imp = IJ.getImage() if vs is None: vs = ImageStack(imp.width, imp.height) # Add a slice, relative to the srcDir vs.addSlice(f.split('\\')[-1],imp.getProcessor()) imp.hide() ImagePlus("Stack from subdirectories", vs).show()
def run(): imp = IJ.getImage() if imp is None: return if not imp.isHyperStack(): print "Not a hyper stack!" return if 1 == imp.getNFrames(): print "There is only one time frame!" return if 1 == imp.getNSlices(): print "To register slices of a stack, use 'Register Virtual Stack Slices'" return dc = DirectoryChooser("Choose target folder") target_folder = dc.getDirectory() if target_folder is None: return # user canceled the dialog if not validate(target_folder): return gd = GenericDialog("Options") channels = [] for ch in range(1, imp.getNChannels() + 1): channels.append(str(ch)) gd.addChoice("channel:", channels, channels[0]) gd.showDialog() if gd.wasCanceled(): return channel = gd.getNextChoiceIndex() + 1 # zero-based vs_imp = create_registered_hyperstack(imp, target_folder, channel) vs_imp.show()
def run(in_dir, ou_dir, extension, minimum, maximum): extension = extension.strip() extension = "*" + extension for path in glob(os.path.join(in_dir, '*.tif')): print path + ':', IJ.open(path) imp = IJ.getImage() minima = [x.strip() for x in ch_min.split(';')] maxima = [x.strip() for x in ch_max.split(';')] for c in range(0, imp.getNChannels()): imp.setC(c + 1) ip = imp.getProcessor() stats = ip.getStats() M = 2**ip.getBitDepth() if minima[c] == '-1': mi = stats.min else: mi = Double.parseDouble(minima[c]) if maxima[c] == '-1': ma = stats.max else: ma = Double.parseDouble(maxima[c]) scale = M / (ma - mi) ip.subtract(mi) ip.multiply(scale) print ' ch' + str(c) + '=[' + str(mi) + ' ... ' + str(ma) + ']', print ' ' IJ.run('Make Composite') IJ.run('RGB Color') IJ.run('Save', 'save=[' + os.path.join(ou_dir, os.path.basename(path)) + ']') IJ.run('Close All')
def import_sequence(inputdir, number=10, start=1, increment=1, scale=100, filepattern='*.', sort=True, use_virtualstack=False): args = "open=" + inputdir args += " number=" + str(number) args += " starting=" + str(start) args += " increment=" + str(increment) args += " scale=" + str(scale) args += " file=" + filepattern if sort: args += " sort" if use_virtualstack: args += " use" print "Import Sequence Arguments : ", args IJ.run("Image Sequence...", args) imp = IJ.getImage() return imp
def ThresholdMaxEntropy(imp0): """Thresholds image and returns thresholded image, merge code still quite clumsy but functional""" imp0 = IJ.getImage() impthres = imp0.duplicate() imp01 = ImagePlus("Channel1", ChannelSplitter.getChannel(imp0, 1)) imp02 = ImagePlus("Channel2", ChannelSplitter.getChannel(imp0, 2)) imp001 = imp01.duplicate() imp002 = imp02.duplicate() IJ.setAutoThreshold(imp001, "MaxEntropy dark") IJ.run(imp001, "Convert to Mask", "") IJ.run(imp001, "Divide...", "value=255") IJ.setAutoThreshold(imp002, "MaxEntropy dark") IJ.run(imp002, "Convert to Mask", "") IJ.run(imp002, "Divide...", "value=255") ic = ImageCalculator() imp0001 = ic.run("Multiply create", imp01, imp001) ic2 = ImageCalculator() imp0002 = ic2.run("Multiply create", imp02, imp002) imp0001.copy() impthres.setC(1) impthres.paste() imp0002.copy() impthres.setC(2) impthres.paste() imp01.close() imp02.close() imp001.close() imp002.close() imp0001.close() imp0002.close() return impthres
def anaParticlesWatershed(imp, strThrMeth="method=Default white", minPx=10, minCirc=0.35, labCol=Color.white, linCol=Color.green, bDebug=False, sl=0.005): """anaParticlesWatershed(imp, strThrMeth="method=Default white", minPx=10, minCirc=0.35, labCol=Color.white, linCol=Color.green, bDebug=False, sl=0.005) A wrapper function to do particle analyis from an image after a watershed transformation and draw the detected features into the overlay of the original image. Inputs: imp - the ImagePlus instance that we will process strThrMeth - a string specifying the threshold method minPx - the minimum pixels to detect minCirc - the minimum circularity to detect labCol - the color for labels in the overlay (default white) linCol - the color for line/stroke in the overlay (default green) bDebug - a flag (default False) that, if true, keeps the work image open sl - a time (default 0.005) to sleep when adding ROIs to not overload This adds the detected features to the overlay and returns the result table for processing for output. """ title = imp.getTitle() shortTitle = imp.getShortTitle() typ = imp.getType() imp.setTitle(shortTitle) imp.show() IJ.run(imp,"Duplicate...", "title=work") wrk = IJ.getImage() # if this is a 16 bit image, convert to 8 bit prior to threshold if typ == ImagePlus.GRAY16: IJ.run(wrk, "Enhance Contrast", "saturated=0.35") IJ.run(wrk, "8-bit", "") IJ.run(wrk, "Threshold", strThrMeth) IJ.run(wrk, "Watershed", "") wrk.show() strMeas = "area mean modal min center perimeter bounding fit shape feret's display redirect=%s decimal=3" % shortTitle IJ.run(wrk, "Set Measurements...", strMeas) strAna = "size=%d-Infinity circularity=%g-1.00 exclude clear include add" % (minPx, minCirc) IJ.run(wrk, "Analyze Particles...", strAna) rt = ResultsTable().getResultsTable() rm = RoiManager.getInstance() ra = rm.getRoisAsArray() # Let's draw the particles into the overlay of the original i=0 for r in ra: i += 1 rLab = "%d" % i r.setName(rLab) imp = addRoiToOverlay(imp, r, labCol=labCol, linCol=linCol) # needed to put in sleep here on cruch to let this complete and not overrun buffer time.sleep(sl) # let's put a PointRoi outside the image to get the overlays all the same color r = PointRoi(-10, -10) imp = addRoiToOverlay(imp, r, labCol=labCol, linCol=linCol) # clear the roi manager and return the results table rm.reset() rm.close() if bDebug == False: wrk.changes = False wrk.close() imp.setTitle(title) return rt
def mkMask(imp,prePick,numRep,nStacks): file_name = imp.getTitle() IJ.selectWindow(file_name) IJ.setSlice(prePick) tempFileNames=[] for pp in range(0,numRep): tempFileNames.append('temp'+str(pp)) IJ.run(imp,"Duplicate...", "title=" +tempFileNames[pp]) IJ.run("8-bit", "") cont_imgs = " ".join('image%d=%s' %(c+1,w) for c,w in enumerate(tempFileNames)) IJ.run("Concatenate...", "title=tempStack " +cont_imgs) tempStack = IJ.getImage() IJ.run(tempStack,"Make Montage...", "columns="+str(numRep/nStacks)+" rows="+str(nStacks)+" scale=1 first=1 last="+str(numRep)+" increment=1 border=1 font=12") m2_imp=IJ.getImage() m2_imp.setTitle("Mask") tempStack.close() return m2_imp
def __dia(self, event): IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel") IJ.run("Set Measurements...", "area mean standard modal min centroid shape integrated median skewness kurtosis stack limit display redirect=None decimal=3") #IJ.run("Properties...", "channels=1 slices=1 frames=20 unit=pixel pixel_width=1.0000 pixel_height=1.0000 voxel_depth=1.0000 frame=[1 sec] origin=0,0"); self.__impD = IJ.getImage() self.__isD = self.__impD.getImageStack() self.__display.text = "DIA="+self.__impD.getTitle() self.__initDIA = True
def straighten_roi_rotation(roiWindowsize = 8): """ Root straightening function that rotates ROI to follow root slope. Does not work properly. """ IJ.run("Set Measurements...", "mean standard min center redirect=None decimal=3") IJ.runMacro("//setTool(\"freeline\");") IJ.run("Line Width...", "line=80"); #numPoints = 512/roiWindowsize xvals = [] yvals = [] maxvals = [] counter = 0 maxIters = 800/roiWindowsize minIters = 10 imp = IJ.getImage().getProcessor() rm = RoiManager() if find_first_pixel(0,imp) == None or find_last_pixel(0,imp)[1] == None: return y = (find_first_pixel(0,imp)[1]+find_last_pixel(0,imp)[1])/2 roi = roiWindow_(imp, center = (roiWindowsize/2,y), width = roiWindowsize, height = 512) xvals.append(roiWindowsize/2) yvals.append(y) maxvals.append(0) roi.findTilt_() i = 0 while i < maxIters and roi.containsRoot_(): roi.advance_(roiWindowsize) IJ.run("Clear Results") IJ.run("Measure") table = RT.getResultsTable() x = RT.getValue(table, "XM", 0) y = RT.getValue(table, "YM", 0) if imp.getPixel(int(x),int(y)) != 0: xvals.append(x) yvals.append(y) maxvals.append((RT.getValue(table, "Max", 0))) #roi.advance_(roiWindowsize) print "here" roi.unrotateRoot_() IJ.run("Clear Results") IJ.run("Measure") roi.restoreCenter_(RT.getValue(table, "XM", 0), RT.getValue(table, "YM", 0)) #exit(1) sleep(.5) roi.findTilt_() i += 1 coords = "" for i in range(len(xvals)-1): coords += str(xvals[i]) + ", " + str(yvals[i]) +", " coords += str(xvals[len(xvals)-1]) + ", " + str(yvals[len(xvals)-1]) IJ.runMacro("makeLine("+coords+")") IJ.run("Straighten...", "line = 80")
def DistanceMap(_img, mpar={}, _gui=False): imp = Duplicator().run(_img) IJ.run(imp, "Exact Euclidean Distance Transform (3D)", "") imp = IJ.getImage() IJ.setMinAndMax(imp, 0, 65535) IJ.run(imp, "16-bit", "") imp.setTitle("DistanceMap") imp.hide() return (imp,)
def loadVideoSegment(fwin, start, reduction, label): ''' Load a video segment, optionally trim the unused frames in the beginning (usually the 1st segment) - fwin: name of the window of the video file (already opened) - start: starting frame number, default = 1 - reduction: sampling rate (i.e. frame reduction factor) - label: label of the loaded substack ''' WM.setCurrentWindow(WM.getWindow(fwin)) im1 = IJ.getImage() nSlices = im1.getStack().getSize() IJ.run(im1, 'Make Substack...', ' slices=' + str(start) + '-' + str(nSlices) + '-' + str(reduction)) im2 = IJ.getImage() im2.setTitle('Substack ' + label) im1.close() return im2
def run(): imp = IJ.getImage() fileName = imp.getTitle() (width, height, nChannels, nSlices, nFrames) = imp.getDimensions() msgStr = "The original dimension is (xyczt): "+ str(width) +'x'+ str(height)+'x'+ str(nChannels)+'x'+ str(nSlices)+'x'+ str(nFrames) printLog(msgStr,1) #get infor from header, SCI 3.8 file infoStr = imp.getProperty("Info") #get all .tif tags #state.acq.zoomFactor=2.5, used for ccalculate pixelsize zoomFactor = float(infoStr.split('state.acq.zoomFactor=')[1].split('\r')[0]) pixelSize = pixelSize_Linden2P*1024/(zoomFactor*width) #equition for converting pixelsize IJ.run(imp, "Set Scale...", "distance=1 known="+ str(pixelSize)+ " pixel=1 unit=um") #set resolution msgStr="zoom: " +str(zoomFactor)+ ", PixelSize: "+str(pixelSize) printLog(msgStr,1) fileType = Options() if nFrames == 1 and fileType == 'T-series': #for t series file temp = nSlices nSlices = nFrames nFrames = temp imp.setDimensions(nChannels, nSlices, nFrames) msgStr = "The new dimension for t-series is (xyczt): "+ str(width) +'x'+ str(height)+'x'+ str(nChannels)+'x'+ str(nSlices)+'x'+ str(nFrames) printLog(msgStr,1) frameRate = float(infoStr.split('state.acq.frameRate=')[1].split('\r')[0]) timeStep = 1./frameRate msgStr="timeStep: "+str(timeStep) printLog(msgStr,1) #need to add label first, otherwise the salebar will not show IJ.run(imp, "Series Labeler", "stack_type=[time series or movie] label_format=[Custom Format] custom_suffix=sec custom_format=[] label_unit=[Custom Suffix] decimal_places=2 startup=0.000000000 interval="+str(timeStep)+" every_n-th=1 first=0 last=1515 location_presets=[Upper Right] x_=67 y_=0") printLog("Time series label added",2) else: #z-stack, state.acq.zStepSize=2 zStep = float(infoStr.split('state.acq.zStepSize=')[1].split('\r')[0]) msgStr="zStep: "+ str(zStep) printLog(msgStr,1) IJ.run(imp, "Series Labeler", "stack_type=z-stack label_format=Lengths custom_suffix=um custom_format=[] label_unit=um decimal_places=2 startup=0.000000000 interval="+str(zStep)+" every_n-th=1 first=0 last=198 location_presets=[Upper Right] x_=399 y_=0") printLog("Z-stack label added",2) #add scalebar IJ.run(imp, "Scale Bar...", "width=" +str(barLeng)+ " height=4 font=14 color=White background=None location=[Lower Right] hide overlay label") #IJ.run(imp, "Scale Bar...", "width=" +str(barLeng)+ " height=4 font=8 color=White background=None location=[Lower Right] overlay label") #add time stamp msgStr = "Scale Bar (length %d) is added" %barLeng printLog(msgStr,2) destFolder = "G:\\ZY\\imaging_2p\\Videos\\" if not os.path.isdir(destFolder): os.makedirs(destFolder) saveName = fileName[:-4]+".avi" destPath = os.path.join(destFolder, saveName) IJ.run(imp, "AVI... ", "compression=Uncompressed frame=60 save="+destPath) msgStr = "File saved: "+destPath printLog(msgStr,1) imp.changes = 0 #imp.close() printLog("DONE",0)
def __selectionSettings(self) : if self.__optionImages : self.__img=IJ.getImage() self.__activeTitle=self.__img.getTitle() self.__listpaths.append(self.__pathdir+self.__img.getShortTitle()+os.path.sep+self.__time+os.path.sep) self.__rootpath = self.__listpaths[0] out=self.__selectTrackStack() else : out = self.__selectFiles() return out
def test(): imp = IJ.openImage(fname) ip = imp.getProcessor() RankFilters().rank(ip,2,RankFilters.MIN) IJ.run("Analyze Particles...", "size=500-50000 circularity=0.40-1.00 show=Masks"); imgActive = IJ.getImage() ipActive = imgActive.getProcessor().convertToFloat() imgActive.show()
def watershed_3d(imp, radius): imp.show() # one needs to display it, otherwise below function cannot find it IJ.run("3D Watershed Split", "binary=%s seeds=Automatic radius=%s" % (imp.getTitle(), radius)) imp.hide() # get the output image imp_out = IJ.getImage() imp_out.hide() # remove the EDT image, which is also displayed WindowManager.getImage("EDT").close() return imp_out
def openImp(): '''function that calls an OpenDialog and returns filePath and imp''' od = OpenDialog("Open movie", "") filePath = path.join(od.getDirectory(), od.getFileName()) if path.splitext(od.getFileName())[1] == ".tif" : #on .dv, use LOCI imp = Opener().openImage(filePath) if path.splitext(od.getFileName())[1] == ".dv": IJ.run("Bio-Formats Importer", "open=["+filePath+"] autoscale color_mode=Grayscale view=Hyperstack stack_order=XYCZT") imp = IJ.getImage() return filePath, imp
def Laplacian(_img, mpar={"scale": 2}, _gui=False): _img.show() time.sleep(0.2) IJ.run("FeatureJ Laplacian", "compute smoothing=%s" % str(mpar["scale"])) imp = IJ.getImage() IJ.run(imp, "Multiply...", "value=-1 stack") imp.setTitle("Laplacian") imp.hide() _img.hide() return (imp,)
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 preProcess_(imp): """ Noise filtering step. Removes particles other than the root after segmentation. Takes a pointer to an ImagePlus, returns pointer to new ImagePlus. """ IJ.runMacro("//setThreshold(1, 255);") IJ.runMacro("run(\"Convert to Mask\");") IJ.run("Analyze Particles...", "size=400-Infinity show=Masks") filteredImp = IJ.getImage() #imp.close() #IJ.run("Invert") IJ.run("Invert LUT") return filteredImp