def __add(self, event): if ( not self.__init) : IJ.showMessage("", "please start a new stack") return if ( not self.__initDIA) : IJ.showMessage("", "please select an image for DIA") return if ( not self.__initFLUO) : IJ.showMessage("", "please select an image for FLUO") return self.__widthl = self.__display2.getText() roi = self.__impD.getRoi() if roi == None : IJ.showMessage("", "No selection") return if roi.getType() in [6,7] : nslice = self.__impD.getCurrentSlice() self.__impF.setSlice(nslice) self.__impF.setRoi(roi) elif roi.getType() in [2,4] : nslice = self.__impD.getCurrentSlice() self.__impF.setSlice(nslice) m=Morph(self.__impF, roi) m.setMidParams(10, 2) roi=m.MidAxis if roi == None : self.__display.text = "roi fail" if not self.__skip : IJ.showMessage("", "failed roi, please draw it as polyline") return #if roi.getType() != 6 : self.__impF.setRoi(roi) else : IJ.showMessage("", "This selection is not yet allowed") return self.__impF.setRoi(roi) straightener = Straightener() new_ip = straightener.straighten(self.__impF, roi, int(self.__widthl)) self.__iplist.append(new_ip) self.__labels.append(self.__isF.getShortSliceLabel(nslice)) self.__display.text = self.__name + " cell " + str(len(self.__iplist)) +" width="+str(new_ip.getWidth())+ " height="+ str(new_ip.getHeight()) roi.setPosition(self.__impD.getCurrentSlice()) self.__rm = RoiManager.getInstance() if (self.__rm==None): self.__rm = RoiManager() self.__rm.add(self.__impD, roi, len(self.__iplist)) self.__cellsrois.append((roi, self.__impD.getCurrentSlice())) #self.__rm.runCommand("Show All") IJ.selectWindow(self.__impD.getTitle())
def maximum_line_profile(imp, roi, pixel_width): """return a line profile taking the maximum value over n pixels perpendicular to roi line""" imp.setRoi(roi) IJ.run(imp, "Interpolate", "interval=1.0 smooth adjust") if pixel_width < 1: pixel_width = 1 pixel_width = int(2 * math.ceil(float(pixel_width) / 2)) ip = Straightener().straightenLine(imp, pixel_width) # debug #from ij import ImagePlus #from ij.gui import WaitForUserDialog #debug_imp = ImagePlus("debug", ip); #debug_imp.show(); #WaitForUserDialog("debug").show(); #debug_imp.close(); width = ip.getWidth() height = ip.getHeight() max_profile = [] poly = roi.getInterpolatedPolygon(1.0, True) for idx, (x, y) in enumerate(zip(poly.xpoints, poly.ypoints)): pix = ip.getLine(idx, 0, idx, height) max_profile.append(((x, y), max(pix))) return max_profile
def straighten_vessel(imp, smooth_centres, it=1, save_output=False): """use IJ straigtening tool to deal with convoluted vessels""" print("straighten vessel input image dims = " + str(imp.getWidth()) + "x" + str(imp.getHeight())) rot_imp = utils.rot3d(imp, axis='x') if it == 1: roi = PolygonRoi([x for x, y, z in smooth_centres], [z for x, y, z in smooth_centres], Roi.FREELINE) print("len interp polygon = " + str(roi.getInterpolatedPolygon().npoints)) elif it == 2: new_zs = [z for z in range(rot_imp.getWidth())] new_ys = lin_interp_1d([z for x, y, z in smooth_centres], [y for x, y, z in smooth_centres], new_zs) roi = PolygonRoi(new_zs, new_ys, Roi.FREELINE) split_ch = ChannelSplitter().split(rot_imp) mch_imp = split_ch[0] egfp_imp = split_ch[1] roi_imp = split_ch[2] roi_imp.setRoi(roi) for zidx in range(egfp_imp.getNSlices()): for chidx in range(3): split_ch[chidx].setZ(zidx + 1) split_ch[chidx].setRoi(roi) ip = Straightener().straightenLine(split_ch[chidx], 150) if chidx == 1: if zidx == 0: egfp_straight_stack = ImageStack(ip.getWidth(), ip.getHeight()) egfp_straight_stack.addSlice(ip) elif chidx == 0: if zidx == 0: mch_straight_stack = ImageStack(ip.getWidth(), ip.getHeight()) mch_straight_stack.addSlice(ip) else: if zidx == 0: roi_straight_stack = ImageStack(ip.getWidth(), ip.getHeight()) roi_straight_stack.addSlice(ip) egfp_out_imp = ImagePlus("Straightened EGFP", egfp_straight_stack) mch_out_imp = ImagePlus("Straightened mCh", mch_straight_stack) roi_out_imp = ImagePlus("Straightened ROI", roi_straight_stack) if it == 2: egfp_out_imp = utils.rot3d(egfp_out_imp, axis='y') mch_out_imp = utils.rot3d(mch_out_imp, axis='y') roi_out_imp = utils.rot3d(roi_out_imp, axis='y') egfp_out_imp.show() mch_out_imp.show() roi_out_imp.show() IJ.run( "Merge Channels...", "c1=[" + mch_out_imp.getTitle() + "] c2=[" + egfp_out_imp.getTitle() + "] c7=[" + roi_out_imp.getTitle() + "] create keep") # WaitForUserDialog("pause").show(); # if it==1: egfp_out_imp.close() mch_out_imp.close() roi_out_imp.close() new_composite = IJ.getImage() if save_output: FileSaver(new_composite).saveAsTiffStack( os.path.join(output_path, "after rotation " + str(it) + ".tif")) return new_composite
def process_image(imps, rois, ais_chno, nucleus_chno, bg_roino=3, sample_width=3, method='mean', dilations=3, average=1, threshold=0.1): """Opens a file and applies a Gaussian filter.""" orig_title = imps[ais_chno-1].getTitle() print ",".join([i.getTitle() for i in imps]) print "Processing", orig_title options = IS.MEAN | IS.MEDIAN # many others nucleus_imp = imps[nucleus_chno-1].duplicate() IJ.run(nucleus_imp, "Median...", "radius=10") IJ.setAutoThreshold(nucleus_imp, "Default"); IJ.run(nucleus_imp, "Make Binary", "") IJ.run(nucleus_imp, "Invert", "") IJ.run(nucleus_imp, "Options...", "iterations=1 count=1 black do=Nothing"); IJ.run(nucleus_imp, "Watershed", ""); IJ.run(nucleus_imp, "Analyze Particles...", "size=20-Infinity clear add"); rm = RoiManager.getInstance2() nuclei = rm.getRoisAsArray() ais_imp = imps[ais_chno-1].duplicate() print ais_imp.getTitle() IJ.run(ais_imp, "8-bit","") IJ.run(ais_imp, "Median...", "radius=1") bg = 0 for i in range(bg_roino): bg_roi = rois[i] ais_imp.setRoi(bg_roi) stats = ais_imp.getStatistics(options) bg += stats.mean print "Bg Roi %s, %s: %s" % (bg_roi.getName(), bg_roi, stats) background = (int)(bg / bg_roino) results = [] for i in range(bg_roino, len(rois)): roiresult = {} print i, rois[i].getName() mimp = ais_imp.duplicate() mimp.setTitle("%s-%s-AIS-Skeleton" % (orig_title, rois[i].getName())) # IJ.run(mimp, "Median...", "radius=3") mimp.setRoi(rois[i]) # IJ.setAutoThreshold(mimp, "Huang dark") IJ.run(mimp, "Auto Local Threshold", "method=Phansalkar radius=15 parameter_1=0 parameter_2=0 white") IJ.setBackgroundColor(0,0,0) IJ.run(mimp, "Clear Outside", "") Prefs.blackBackground = True for j in range(dilations): IJ.run(mimp, "Dilate", "") IJ.run(mimp, "Skeletonize", "") #IJ.run(mimp, "Analyze Skeleton (2D/3D)", "prune=none prune_0 calculate show display"); ais_skeleton, ais_points, points, orthogonals, ais_roi, nucleus_roi = create_skeleton(mimp, '%s-%s-AIS' % (orig_title, rois[i].getName()), nuclei_rois=nuclei, sample_width=sample_width) if ais_skeleton is None: print "Skipping -- AIS skeleton segmentation failed for ROI", rois[i].getName() continue #images['ais-skeleton-' + rois[i].getName()] = ais_skeleton # subtract background print "Subtracting background: bg=%d" % background IJ.run(ais_imp, "Subtract...", "value=%d" % int(background)) ais_imp.setRoi(ais_roi) ip = Straightener().straightenLine(ais_imp, sample_width) straight_imp = ImagePlus('%s-%s-AIS-Straight' % (orig_title, rois[i].getName()), ip) straight_imp.setCalibration(imps[ais_chno-1].getCalibration().copy()) IJ.run(straight_imp, "Green Fire Blue", "") roiresult = { 'roi-name': rois[i].getName(), 'ais-image': straight_imp, 'ais-roi': ais_roi, 'nucleus-roi': nucleus_roi, } # plot if len(points) > 1: if method == 'sum': threshold *= sample_width plot, rt = create_plot(straight_imp, method, average, threshold=threshold) roiresult['plot'] = plot roiresult['table'] = rt results.append(roiresult) return results, background
#roi = zproj_imp.getRoi(); zproj_imp.changes = False; zproj_imp.close(); z_planes = egfp_imp.getNSlices(); #straight_stack = Straightener().straightenStack(egfp_imp, roi, 100); #out_imp = ImagePlus("Straightened", straight_stack); for zidx in range(z_planes): for chidx in range(3): #print("Working on " + str(["egfp", "mCh", "roi"][chidx])); split_ch[chidx].setZ(zidx+1); split_ch[chidx].setRoi(roi); ip = Straightener().straightenLine(split_ch[chidx], 150); if chidx==1: if zidx==0: egfp_straight_stack = ImageStack(ip.getWidth(), ip.getHeight()); egfp_straight_stack.addSlice(ip); elif chidx==0: if zidx==0: mch_straight_stack = ImageStack(ip.getWidth(), ip.getHeight()); mch_straight_stack.addSlice(ip); else: if zidx==0: roi_straight_stack = ImageStack(ip.getWidth(), ip.getHeight()); roi_straight_stack.addSlice(ip); egfp_out_imp = ImagePlus("Straightened EGFP", egfp_straight_stack); mch_out_imp = ImagePlus("Straightened mCh", mch_straight_stack);
shell_width = 10 imp = IJ.getImage() overlay = imp.getOverlay() raster_shells = [] if imp and overlay: for i in range(overlay.size()): roi = overlay.get(i) if roi.getName() and "Shell" in roi.getName(): imp.setRoi(roi) IJ.run(imp, "Area to Line", "") raster = ImagePlus( roi.getName(), Straightener().straighten(imp, roi, shell_width)) raster_shells.append(raster) if raster_shells: holding_imp = ImagesToStack.run(raster_shells) IJ.run(holding_imp, "Make Montage...", "columns=1 rows={} scale=1".format(holding_imp.getNSlices())) measurable_imp = IJ.getImage() measurable_imp.setTitle("Rasterized Shells") IJ.setAutoThreshold(measurable_imp, "Default dark") IJ.run(measurable_imp, "Analyze Particles...", " show=[Overlay Masks] display clear overlay") else: error() else: error()
def __fmaxfinder(self) : #stack = self.__impRes.getStack() self.__impD.killRoi() self.__impF.killRoi() stack = self.__impF.getStack() n_slices = stack.getSize() #newstack=ImageStack(self.__impRes.getWidth(), self.__impRes.getHeight()) newstack=ImageStack(self.__impF.getWidth(), self.__impF.getHeight()) noise = self.__display3.text for index in range(1,n_slices+1): IJ.selectWindow(self.__impF.getTitle()) self.__impF.setSlice(index) ip = self.__impF.getProcessor() mf=MaximumFinder() ipmax = mf.findMaxima(ip, int(noise), 0, 0, False, False) newstack.addSlice("", ipmax) newimage=ImagePlus("max points"+self.__name, newstack) newimage.show() newimage.updateAndDraw() listip = [] maxh=self.__impRes.getHeight() for roi in self.__cellsrois : straightener = Straightener() newimage.setSlice(roi[1]) newimage.setRoi(roi[0]) #listip.append(straightener.straighten(newimage, roi[0], int(self.__widthl))) listip.append(straightener.straighten(newimage, roi[0], maxh)) listip.sort(key = lambda ip : ip.width) ipw=[ ip.getWidth() for ip in listip ] iph=[ ip.getHeight() for ip in listip ] maxw=max(ipw) maxh=max(iph) if self.__enlarge : resizelist = [ ip.resize(maxw, maxh, True) for ip in listip ] else : resizelist = [] for ip in listip : tempip = ByteProcessor(maxw, maxh) xloc = int(math.floor((maxw/2.00) - (ip.width/2.00))) yloc = int(math.floor((maxh/2.00) - (ip.height/2.00))) tempip.copyBits(ip, xloc, yloc, Blitter.COPY) resizelist.append(tempip) ims = ImageStack(maxw, maxh) #for ip in resizelist : ims.addSlice("", ip) for i in range(len(resizelist)) : ims.addSlice(self.__labels[i], resizelist[i]) self.__impMax = ImagePlus(self.__name+"-max", ims) self.__impMax.show() stack = self.__impMax.getStack() # get the stack within the ImagePlus n_slices = stack.getSize() for index in range(1, n_slices+1): self.__impMax.killRoi() self.__impMax.setSlice(index) roi = self.__listrois[index-1] if self.__sens[index-1]<0 : self.__impMax.setRoi(roi) ip1 = self.__impMax.getProcessor() ip1.flipHorizontal() self.__impMax.killRoi() self.__impMax.updateAndDraw() ip = self.__impMax.getProcessor() for i in range(ip.getWidth()*ip.getHeight()) : if ip.getf(i) > 0 : ip.setf(i, 255) #else : ip.setf(i, 0) IJ.run(self.__impMax, "8-bit", "") IJ.run(self.__impMax, "Options...", "iterations=2 count=1 black edm=Overwrite do=Close stack") IJ.run(self.__impMax, "Ultimate Points", "stack") self.__impMax.updateAndDraw()
def __addroi(self, event) : if ( not self.__init) : IJ.showMessage("", "please start a new stack") return if ( not self.__initDIA) : IJ.showMessage("", "please select an image for DIA") return if ( not self.__initFLUO) : IJ.showMessage("", "please select an image for FLUO") return twres = TextWindow("measures-"+self.__name, "label\tname\tsol\tarea\tcirc\tAR\tFeret\taxis\traf\tdMajor\tdFeret\tdArea", "", 300, 450) tab="\t" self.__widthl = self.__display2.getText() IJ.selectWindow(self.__impF.getTitle()) self.__rm = RoiManager.getInstance() if (self.__rm==None): self.__rm = RoiManager() if self.__impF.getImageStackSize() > 1 : roisarray =[(roi, self.__rm.getSliceNumber(roi.getName())) for roi in self.__rm.getRoisAsArray()] else : roisarray =[(roi, 1) for roi in self.__rm.getRoisAsArray()] self.__rm.runCommand("reset") #self.__rm.runCommand("Delete") IJ.selectWindow(self.__impF.getTitle()) self.__maxraf=float(self.__display19.text) self.__minraf=float(self.__display20.text) count=1 for roielement in roisarray : roi = roielement[0] pos = roielement[1] lab = self.__impF.getImageStack().getShortSliceLabel(pos) if lab==None : lab=str(pos) if self.__conEllipses : IJ.selectWindow(self.__impF.getTitle()) self.__impF.setSlice(pos) self.__impF.setRoi(roi) self.__rm.runCommand("Add") IJ.run(self.__impF, "Fit Ellipse", "") ellipse=self.__impF.getRoi() params = ellipse.getParams() ferets = ellipse.getFeretValues() imp2 = Duplicator().run(self.__impF,pos,pos) IJ.run(imp2, "Rotate... ", "angle="+str(ferets[1])+" grid=0 interpolation=Bilinear enlarge slice") temproi=Roi((imp2.getWidth()-ferets[0])/2.0,(imp2.getHeight()-ferets[2])/2.0,ferets[0],ferets[2]) imp2.setRoi(temproi) imp3 = Duplicator().run(imp2,1,1) ip3=imp3.getProcessor() if int(self.__display5.text) < ip3.getWidth() < int(self.__display6.text) : self.__iplist.append(ip3) self.__display.text = self.__name + " cell " + str(len(self.__iplist)) fer=Line(params[0],params[1],params[2],params[3]) self.__cellsrois.append((fer, pos)) self.__labels.append(self.__isF.getShortSliceLabel(pos)) m=Morph(self.__impF, roi) twres.append(lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(fer.getLength())+tab+str(1)+tab+str(0)+tab+str(0)+tab+str(0)) self.__dictCells[count]=(str(roi.getName()), lab, roi) count=count+1 continue if roi.getType() in [6,7] : self.__impF.setSlice(pos) self.__impF.setRoi(roi) self.__rm.runCommand("Add") elif roi.getType() in [2,4] : self.__impF.setSlice(pos) self.__impF.setRoi(roi) m=Morph(self.__impF, roi) m.setMidParams(10, 2) midroi=m.MidAxis if midroi == None : continue raf = m.MaxFeret/midroi.getLength() if (self.__maxraf < raf) or (raf < self.__minraf) : continue maxsol = float(self.__display7.text) minsol = float(self.__display8.text) maxarea = float(self.__display9.text) minarea = float(self.__display10.text) maxcirc = float(self.__display11.text) mincirc = float(self.__display12.text) maxar = float(self.__display13.text) minar = float(self.__display14.text) maxfer = float(self.__display15.text) minfer = float(self.__display16.text) maxmean = float(self.__display17.text) minmean = float(self.__display18.text) maxmferet = float(self.__display21.text) minmferet = float(self.__display22.text) testsol = (minsol<= m.Solidity <= maxsol) testarea = (minarea<= m.Area <= maxarea) testcirc = (mincirc<= m.Circ <= maxcirc) testar = (minar<= m.AR <= maxar) testfer = (minfer<= m.MaxFeret <= maxfer) testmean = (minmean <= m.Mean <= maxmean) testmferet = (minmferet <= m.MinFeret <= maxmferet) #print minmferet , m.MinFeret , maxmferet test = (testsol+testarea+testcirc+testar+testfer+testmean+testmferet)/7 if test : fmaj, ffmx, fa =[],[],[] for r in m.getMidSegments(10, 40, 0)[0] : if r == None : continue m2=Morph(self.__impF, r) fmaj.append(m2.Major) ffmx.append(m2.MaxFeret) fa.append(m2.Area) diffmajor, diffferet, diffarea = 0,0,0 if len(fa) > 4 : medfmaj = self.listmean(fmaj[1:-1]) medffmx = self.listmean(ffmx[1:-1]) medfa = self.listmean(fa[1:-1]) diffmajor = (max(fmaj[1:-1])-medfmaj)/medfmaj diffferet = (max(ffmx[1:-1])-medffmx)/medffmx diffarea = (max(fa[1:-1])-medfa)/medfa twres.append(lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(midroi.getLength())+tab+str(m.MaxFeret/midroi.getLength())+tab+str(diffmajor)+tab+str(diffferet)+tab+str(diffarea)) #print lab+tab+str(roi.getName())+tab+str(m.Solidity)+tab+str(m.Area)+tab+str(m.Circ)+tab+str(m.AR)+tab+str(m.MaxFeret)+tab+str(midroi.getLength())+tab+str(m.MaxFeret/midroi.getLength())+tab+str(diffmajor)+tab+str(diffferet)+tab+str(diffarea) self.__impF.setRoi(roi) self.__rm.runCommand("Add") self.__impF.killRoi() self.__impF.setRoi(midroi) #self.__dictCells[str(roi.getName())]=(str(roi.getName()), lab, roi) self.__dictCells[count]=(str(roi.getName()), lab, roi) count=count+1 else : #print "test falls" continue else : print "out loop" continue straightener = Straightener() new_ip = straightener.straighten(self.__impF, midroi, int(self.__widthl)) if int(self.__display5.text) < new_ip.getWidth() < int(self.__display6.text) : self.__iplist.append(new_ip.convertToShort(False)) self.__display.text = self.__name + " cell " + str(len(self.__iplist)) #print "add", roi.getName(), roi.getType() self.__cellsrois.append((midroi, pos)) self.__labels.append(self.__isF.getShortSliceLabel(pos)) #roisarray=self.__rm.getRoisAsArray() #self.__rm.runCommand("reset") #self.__rm.runCommand("Delete") self.__impD.killRoi() self.__impF.killRoi() IJ.selectWindow(self.__impD.getTitle())