Пример #1
0
def segmentNuc(impc2):
	impdup = Duplicator().run(impc2)
	IJ.run(impdup, "8-bit", "")
	IJ.run(impdup, "Gaussian Blur...", "sigma=1.5 stack")
#	AutoThresholder().getThreshold(AutoThresholder.Method.valuOf('Otsu'), int[] histogram) 
	IJ.setAutoThreshold(impdup, "Otsu dark")
	IJ.run(impdup, "Convert to Mask", "stack")
 	#IJ.setAutoThreshold(impdup, "Otsu dark")
	#opt = PA.SHOW_MASKS + PA.SHOW_RESULTS + PA.EXCLUDE_EDGE_PARTICLES + PA.INCLUDE_HOLES # option for stack missing
	opt = PA.SHOW_MASKS + PA.EXCLUDE_EDGE_PARTICLES + PA.INCLUDE_HOLES # option for stack missing
	##area mean centroid bounding integrated stack redirect=None decimal=4
	meas = Meas.AREA + Meas.MEAN + Meas.CENTROID + Meas.RECT + Meas.INTEGRATED_DENSITY + Meas.STACK_POSITION
	rt = ResultsTable().getResultsTable()
	pa = PA(opt, meas, rt, 10.0, 300000.0, 0, 1.0)
	PA.processStack = True
	pa.setHideOutputImage(True)
	##run("Analyze Particles...", "size=800-Infinity circularity=0.00-1.00 pixel show=Masks display exclude include stack");
	outstack = ImageStack(impdup.getWidth(), impdup.getHeight())
	for i in range(1,impdup.getStackSize()+1):
		impdup.setSlice(i)
		pa.analyze(impdup)
		impbin = pa.getOutputImage()
		outstack.addSlice(impbin.getProcessor())
 	impbin = ImagePlus("out", outstack)
	IJ.run(impbin, "Invert LUT", "")
	#IJ.run(impbin, "Fill Holes", "stack")
	return impbin, rt
Пример #2
0
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 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)
def generate_background_rois(input_mask_imp,
                             params,
                             membrane_edges,
                             dilations=5,
                             threshold_method=None,
                             membrane_imp=None):
    """automatically identify background region based on auto-thresholded image, existing membrane edges and position of midpoint anchor"""
    if input_mask_imp is None and membrane_imp is not None:
        segmentation_imp = Duplicator().run(membrane_imp)
        # do thresholding using either previous method if threhsold_method is None or using (less conservative?) threshold method
        if (threshold_method is None
                or not (threshold_method in params.listThresholdMethods())):
            mask_imp = make_and_clean_binary(segmentation_imp,
                                             params.threshold_method)
        else:
            mask_imp = make_and_clean_binary(segmentation_imp,
                                             threshold_method)
        segmentation_imp.close()
    else:
        input_mask_imp.killRoi()
        mask_imp = Duplicator().run(input_mask_imp)

    rois = []
    IJ.setForegroundColor(0, 0, 0)
    roim = RoiManager(True)
    rt = ResultsTable()

    for fridx in range(mask_imp.getNFrames()):
        mask_imp.setT(fridx + 1)
        # add extra bit to binary mask from loaded membrane in case user refined edges...
        # flip midpoint anchor across the line joining the two extremes of the membrane,
        # and fill in the triangle made by this new point and those extremes
        poly = membrane_edges[fridx].getPolygon()
        l1 = (poly.xpoints[0], poly.ypoints[0])
        l2 = (poly.xpoints[-1], poly.ypoints[-1])
        M = (0.5 * (l1[0] + l2[0]), 0.5 * (l1[1] + l2[1]))
        Mp1 = (params.manual_anchor_midpoint[0][0] - M[0],
               params.manual_anchor_midpoint[0][1] - M[1])
        p2 = (M[0] - Mp1[0], M[1] - Mp1[1])
        new_poly_x = list(poly.xpoints)
        new_poly_x.append(p2[0])
        new_poly_y = list(poly.ypoints)
        new_poly_y.append(p2[1])
        mask_imp.setRoi(PolygonRoi(new_poly_x, new_poly_y, PolygonRoi.POLYGON))
        IJ.run(mask_imp, "Fill", "slice")
        mask_imp.killRoi()

        # now dilate the masked image and identify the unmasked region closest to the midpoint anchor
        ip = mask_imp.getProcessor()
        dilations = 5
        for d in range(dilations):
            ip.dilate()
        ip.invert()
        mask_imp.setProcessor(ip)
        mxsz = mask_imp.getWidth() * mask_imp.getHeight()
        pa = ParticleAnalyzer(
            ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.SHOW_PROGRESS,
            ParticleAnalyzer.CENTROID, rt, 0, mxsz)
        pa.setRoiManager(roim)
        pa.analyze(mask_imp)
        ds_to_anchor = [
            math.sqrt((x - params.manual_anchor_midpoint[0][0])**2 +
                      (y - params.manual_anchor_midpoint[0][1])**2)
            for x, y in zip(
                rt.getColumn(rt.getColumnIndex("X")).tolist(),
                rt.getColumn(rt.getColumnIndex("Y")).tolist())
        ]
        if len(ds_to_anchor) > 0:
            roi = roim.getRoi(ds_to_anchor.index(min(ds_to_anchor)))
            rois.append(roi)
        else:
            rois.append(None)
        roim.reset()
        rt.reset()
    roim.close()
    mask_imp.close()
    return rois
Пример #5
0
	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())