def select_images():
    """
    Returns two ImagePlus objects that can be used by the drift correction.
    If more than two images are available a dialog is used for selection.
    """
    if WindowManager.getImageCount() > 0:
        imp = WindowManager.getCurrentImage()
        if imp.getImageStackSize() == 2:
            dup = Duplicator()
            img1 = dup.run(imp, 1, 1)
            img1.setTitle("Slice1")
            img2 = dup.run(imp, 2, 2)
            img2.setTitle("Slice2")
        elif WindowManager.getImageCount() == 2:
            img1, img2 = [WindowManager.getImage(id) for id in WindowManager.getIDList()]
        elif WindowManager.getImageCount() > 2:
            image_ids = WindowManager.getIDList()
            image_titles = [WindowManager.getImage(id).getTitle() for id in image_ids]
            try:
                sel1, sel2 = dialogs.create_selection_dialog(image_titles, range(2))
            except TypeError:
                return(None, None)
            img1 = WindowManager.getImage(image_ids[sel1])
            img2 = WindowManager.getImage(image_ids[sel2])
        else:
            IJ.error("You need two images to run the script.")
            return(None, None)
    else:
        IJ.error("You need two images to run the script.")
        return(None, None)
    return (img1, img2)
Beispiel #2
0
 def crop(self):
     self.imp.setRoi(self.outlineRoi)
     duplicator = Duplicator()
     self.imp.setHideOverlay(True)
     self.impCrop = duplicator.run(self.imp)
     self.impCrop.show()
     self.imp.setHideOverlay(False)
Beispiel #3
0
    def creating_vor_roi(self):
        """
        runs voronoi on cell to create vor_rois
        """
        rm = RoiManager.getRoiManager()
        rm.reset()
        d = Duplicator()
        nuc_bin_copy = d.run(self.hseg.nuc_bin())
        nuc_bin_copy.show()

        IJ.run(nuc_bin_copy, "Make Binary", "")
        nuc_bin_copy.setRoi(self.roi())
        IJ.run(nuc_bin_copy, "Clear Outside", "")

        # 1/0

        IJ.run(nuc_bin_copy, "Voronoi", "")
        nuc_bin_copy.setRoi(None)
        ip = nuc_bin_copy.getProcessor()
        ip.setMinAndMax(0, 1)
        IJ.run(nuc_bin_copy, "Apply LUT", "")

        nuc_bin_copy.setRoi(self.roi())
        IJ.run(nuc_bin_copy, "Analyze Particles...", "add")
        vor_rois = rm.getRoisAsArray()

        # self.hseg.raw_stack().show()
        # 10/0

        futils.force_close(nuc_bin_copy)

        return vor_rois
Beispiel #4
0
    def process(self, image, seeds=None):
        self.objects = None
        self.labelImage = None
        duplicator = Duplicator()
        spots = duplicator.run(image)
        IJ.setMinAndMax(spots, 0, 1)
        IJ.run(spots, "16-bit", "")
        spot3DImage = ImageHandler.wrap(spots)
        if seeds != None:
            seed3DImage = ImageHandler.wrap(seeds)
        else:
            seed3DImage = self.__computeSeeds(spots)

        algorithm = Segment3DSpots(spot3DImage, seed3DImage)
        algorithm.show = False
        algorithm.setSeedsThreshold(self.seedsThreshold)
        algorithm.setLocalThreshold(self.localBackground)
        algorithm.setWatershed(self.watershed)
        algorithm.setVolumeMin(self.volumeMin)
        algorithm.setVolumeMax(self.volumeMax)
        algorithm.setMethodLocal(Segment3DSpots.LOCAL_CONSTANT)
        algorithm.setMethodSeg(Segment3DSpots.SEG_MAX)
        algorithm.segmentAll()
        self.objects = algorithm.getObjects()
        self.labelImage = ImagePlus("OM_" + spots.getTitle(), algorithm.getLabelImage().getImageStack())

        return self.labelImage
Beispiel #5
0
def vor_cell(nuc_bin_imp, cell):
    """creates the voronoi for one cell, cell is assumed to have nucs"""

    rm = RoiManager.getRoiManager()
    rm.reset()
    d = Duplicator()
    nuc_bin_copy = d.run(nuc_bin_imp)

    IJ.run(nuc_bin_copy, "Make Binary", "")
    nuc_bin_copy.setRoi(cell.roi)
    IJ.run(nuc_bin_copy, "Clear Outside", "")

    IJ.run(nuc_bin_copy, "Voronoi", "")

    nuc_bin_copy.setRoi(None)
    ip = nuc_bin_copy.getProcessor()
    ip.setMinAndMax(0, 1)
    IJ.run(nuc_bin_copy, "Apply LUT", "")
    IJ.run(nuc_bin_copy, "Invert", "")

    nuc_bin_copy.setRoi(cell.roi)
    IJ.run(nuc_bin_copy, "Analyze Particles...", "add")
    vor_rois = rm.getRoisAsArray()

    nuc_inds = [x for x in range(len(cell.nucs))]
    for vor_roi in vor_rois:

        temp = None
        for i, nuc_ind in enumerate(nuc_inds):
            nuc_roi = cell.nucs[nuc_ind].roi

            nuc_cent = roi_cent(nuc_roi, integer=True)

            if vor_roi.contains(*nuc_cent):
                cell.nucs[nuc_ind].vor_roi = vor_roi
                ## I don't think I need to do this, I could just use i outside of loop but it feels so insecure or something
                temp = i
                break

        else:
            IJ.log('cell: {}, issue with voronoi nuc match up'.format(
                cell.name))
            rm.reset()
            for i, nuc in enumerate(cell.nucs):

                x = int(nuc.roi.getXBase())
                y = int(nuc.roi.getYBase())
                IJ.log('{}. ({},{})'.format(i, x, y))
                add_roi(Roi(x, y, 10, 10), str(i))
            IJ.log(str(nuc_inds))
            add_roi(vor_roi, "vor_roi")

            ## raise RuntimeError('cell: {}, issue with voronoi nuc match up'.format(cell.name))

        if temp is not None:
            del nuc_inds[temp]

    force_close(nuc_bin_copy)
def runSimulation(options, image):
	
	print "Testing segmentation with blur" + \
					" x=" + "%f" % options['gaussXY'] + \
					" y=" + "%f" % options['gaussXY'] + \
					" z=" + "%f" % options['gaussZ'] + \
					" localBackground="  + "%i" % options['localBackground'] + \
					" seedRadius="  + "%i" % options['seedRadius']

	duplicator = Duplicator()
	inputPM = duplicator.run(image)
	inputPM.setTitle("Gauss_segment_input")

	inputName = image.getTitle()
	inputName = inputName[:inputName.rfind('.')]
	
	### Blur nuclei probability map to smoothen segmentation
	IJ.run(inputPM, "Gaussian Blur 3D...",
		" x=" + "%f" % options['gaussXY'] + \
		" y=" + "%f" % options['gaussXY'] + \
		" z=" + "%f" % options['gaussZ'])

	### Segment image using nuclear probability map
	print ">>> Segmenting image..."
	segmentator = Segmentator(options, "Segmented")
	segmentedImage = segmentator.process(inputPM)
	outputName = "OM_XY" + ("%f" % options['gaussXY']) + "_Z" + ("%f" % options['gaussZ']) + \
		"_TH" + ("%i" % options['localBackground']) + \
		"_SR" + ("%i" % options['seedRadius']) + \
		"_" + inputName
	segmentator.save(segmentedImage, outputName)

	### Get object measurements
	print ">>> Measuring objects..."
	results = {'all':0, '0':0, '250':0, '500':0, '750':0, '1000':0, '1500':0, 'edge':0}
	analyzer = Analyzer(options, segmentator.objects, "Results")
	segmented = ImageInt.wrap(segmentedImage)
	for objectV in analyzer.objects.getObjectsList():
		if (options['edgeXY'] and options['edgeZ']) or \
			(not objectV.edgeImage(segmented, not options['edgeXY'], not options['edgeZ'])):
			results['all'] = results['all'] + 1
			volume = objectV.getVolumePixels()
			if volume <= 250:
				results['0'] = results['0'] + 1
			elif volume > 250 and volume <= 500:
				results['250'] = results['250'] + 1
			elif volume > 500 and volume <= 750:
				results['500'] = results['500'] + 1
			elif volume > 750 and volume <= 1000:
				results['750'] = results['750'] + 1
			elif volume > 1000 and volume <= 1500:
				results['1000'] = results['1000'] + 1
			else:
				results['1500'] = results['1500'] + 1
		else:
			results['edge'] = results['edge'] + 1
	
	return results
def getMask(imp, chan):
	dup = Duplicator()
	mask = dup.run(imp, chan, chan, 1,1, 1,1)
	sigma = 0.2
	IJ.run(mask, "Gaussian Blur...", "sigma="+str(sigma)+" scaled")
	if chan==1:
		method = "Otsu"
	else:
		method = "MaxEntropy"
	IJ.setAutoThreshold(mask, method+" dark")
	Prefs.blackBackground = True
	IJ.run(mask, "Convert to Mask", "")
	IJ.run(mask, "Close-", "")
	IJ.run(mask, "Watershed", "")
	return mask
def make_and_clean_binary(imp, threshold_method):
    """convert the membrane identification channel into binary for segmentation"""
    if "Local: " in threshold_method:
        dup = Duplicator()
        imp1 = dup.run(imp)
        imp2 = dup.run(imp)
        imp.changes = False
        imp.close()
        threshold_method = threshold_method.split("Local: ")[1]
        IJ.run(imp1, "8-bit", "")
        IJ.run(
            imp1, "Auto Local Threshold", "method=" + threshold_method +
            " radius=15 parameter_1=0 parameter_2=0 white stack")
        IJ.run(imp2, "Make Binary",
               "method=MinError background=Dark calculate")
        ic = ImageCalculator()
        imp = ic.run("AND create stack", imp1, imp2)
        IJ.run(imp, "Invert", "stack")
        IJ.run(imp, "Make Binary",
               "method=Default background=Default calculate")
    elif "Edge" in threshold_method:
        IJ.run(imp, "Find Edges", "stack")
        IJ.run(imp, "Make Binary", "method=Mean background=Dark calculate")
    else:
        IJ.run(imp, "Make Binary",
               "method=" + threshold_method + " background=Dark calculate")
        # "calculate" ensures that threshold is calculated image-wise

    IJ.run(imp, "Open", "stack")
    IJ.run(imp, "Close-", "stack")
    IJ.run(imp, "Close-", "stack")
    IJ.run(imp, "Open", "stack")
    IJ.run(imp, "Fill Holes", "stack")
    IJ.run(imp, "Erode", "stack")
    IJ.run(imp, "Erode", "stack")
    keep_largest_blob(imp)
    IJ.run(imp, "Dilate", "stack")
    IJ.run(imp, "Dilate", "stack")
    IJ.run(imp, "Open", "stack")
    if "Edge" in threshold_method:
        IJ.run(imp, "Erode", "stack")
        IJ.run(imp, "Erode", "stack")
    return imp
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters):
	
	title =  inputImp.getTitle()
	title=title.replace('UV', 'SD')
	
	print title
	
	#trueColorImp= WindowManager.getImage(title)
	#print type( trueColorImp)
	
	# calculate are of roi 
	stats=inputImp.getStatistics()
	inputRoiArea=stats.area
	
	print inputRoi
	
	# get the bounding box of the active roi
	inputRec = inputRoi.getBounds()
	x1=long(inputRec.getX())
	y1=long(inputRec.getY())
	x2=x1+long(inputRec.getWidth())-1
	y2=y1+long(inputRec.getHeight())-1

	print x1
	print y1
	print x2
	print y2
	
	# crop the roi
	interval=FinalInterval( array([x1, y1 ,0], 'l'), array([x2, y2, 2], 'l') )
	cropped=ops.crop(interval, None, inputDataset.getImgPlus() ) 
	
	datacropped=data.create(cropped)
	display.createDisplay("cropped", datacropped)
	croppedPlus=IJ.getImage()
	
	duplicator=Duplicator()
	substackMaker=SubstackMaker()
	
	# duplicate the roi
	duplicate=duplicator.run(croppedPlus)
	#duplicate.show()
	
	# convert duplicate of roi to HSB and get brightness
	IJ.run(duplicate, "HSB Stack", "");
	brightnessPlus=substackMaker.makeSubstack(duplicate, "3-3")
	brightness=ImgPlus(ImageJFunctions.wrapByte(brightnessPlus))
	brightnessPlus.setTitle("Brightness")
	#brightnessPlus.show()
	
	# make another duplicate, split channels and get red
	duplicate=duplicator.run(croppedPlus)
	channels=ChannelSplitter().split(duplicate)
	redPlus=channels[0]
	red=ImgPlus(ImageJFunctions.wrapByte(redPlus))
	redPlus.show()
	
	# convert to lab
	IJ.run(croppedPlus, "Color Transformer", "colour=Lab")
	IJ.selectWindow('Lab')
	labPlus=IJ.getImage()
	
	# get the A channel
	APlus=substackMaker.makeSubstack(labPlus, "2-2")
	APlus.setTitle('A')
	APlus.show()
	APlus.getProcessor().resetMinAndMax()
	APlus.updateAndDraw()
	AThresholded=threshold(APlus, -10, 50)
	
	# get the B channel
	BPlus=substackMaker.makeSubstack(labPlus, "3-3")
	BPlus.setTitle('B')
	BPlus.show()
	BPlus.getProcessor().resetMinAndMax()
	BPlus.updateAndDraw()
	BThresholded=threshold(BPlus, -10, 50)
	
	# AND the Athreshold and Bthreshold to get a map of the red pixels
	ic = ImageCalculator();
	redMask = ic.run("AND create", AThresholded, BThresholded);
	IJ.run(redMask, "Divide...", "value=255");
	#redMask.show()
	
	labPlus.close()
	
	# threshold the spots from the red channel
	thresholdedred=SpotDetectionGray(red, data, display, ops, False)
	display.createDisplay("thresholdedred", data.create(thresholdedred))
	impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped")
	
	# threshold the spots from the brightness channel
	thresholded=SpotDetectionGray(brightness, data, display, ops, False)
	display.createDisplay("thresholded", data.create(thresholded))
	impthresholded=ImageJFunctions.wrap(thresholded, "wrapped")
	
	# or the thresholding results from red and brightness channel
	impthresholded = ic.run("OR create", impthresholded, impthresholdedred);
	
	# convert to mask
	Prefs.blackBackground = True
	IJ.run(impthresholded, "Convert to Mask", "")
	
	# clear the region outside the roi
	clone=inputRoi.clone()
	clone.setLocation(0,0)
	Utility.clearOutsideRoi(impthresholded, clone)
	
	# create a hidden roi manager
	roim = RoiManager(True)
	
	# count the particlesimp.getProcessor().setColor(Color.green)
	countParticles(impthresholded, roim, detectionParameters.minSize, detectionParameters.maxSize, detectionParameters.minCircularity, detectionParameters.maxCircularity)
	
	# define a function to determine the percentage of pixels that are foreground in a binary image
	# inputs:
	#    imp: binary image, 0=background, 1=foreground
	#    roi: an roi
	def isRed(imp, roi):
		stats = imp.getStatistics()
	
		if (stats.mean>detectionParameters.redPercentage): return True
		else: return False
	
	def notRed(imp, roi):
		stats = imp.getStatistics()
	
		if (stats.mean>detectionParameters.redPercentage): return False
		else: return True

	allList=[]

	for roi in roim.getRoisAsArray():
		allList.append(roi.clone())
	
	# count particles that are red
	redList=CountParticles.filterParticlesWithFunction(redMask, allList, isRed)
	# count particles that are red
	blueList=CountParticles.filterParticlesWithFunction(redMask, allList, notRed)

	print "Total particles: "+str(len(allList))
	print "Filtered particles: "+str(len(redList))

	# for each roi add the offset such that the roi is positioned in the correct location for the 
	# original image
	[roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in allList]
	
	# create an overlay and add the rois
	overlay1=Overlay()
		
	inputRoi.setStrokeColor(Color.green)
	overlay1.add(inputRoi)
	[CountParticles.addParticleToOverlay(roi, overlay1, Color.red) for roi in redList]
	[CountParticles.addParticleToOverlay(roi, overlay1, Color.cyan) for roi in blueList]
	
	def drawAllRoisOnImage(imp, mainRoi, redList, blueList):
		imp.getProcessor().setColor(Color.green)
		IJ.run(imp, "Line Width...", "line=3");
		imp.getProcessor().draw(inputRoi)
		imp.updateAndDraw()
		IJ.run(imp, "Line Width...", "line=1");
		[CountParticles.drawParticleOnImage(imp, roi, Color.magenta) for roi in redList]
		[CountParticles.drawParticleOnImage(imp, roi, Color.green) for roi in blueList]
		imp.updateAndDraw()
	
	drawAllRoisOnImage(inputImp, inputRoi, redList, blueList)
	#drawAllRoisOnImage(trueColorImp, inputRoi, redList, blueList)
	
	# draw overlay
	#inputImp.setOverlay(overlay1)
	#inputImp.updateAndDraw()
	
	statsdict=CountParticles.calculateParticleStats(APlus, BPlus, redMask, roim.getRoisAsArray())
	
	print inputRoiArea

	areas=statsdict['Areas']
	poreArea=0
	for area in areas:
		poreArea=poreArea+area

	ATotal=0
	ALevels=statsdict['ALevel']
	for A in ALevels:
		ATotal=ATotal+A

	AAverage=ATotal/len(ALevels)

	BTotal=0
	BLevels=statsdict['BLevel']
	for B in BLevels:
		BTotal=BTotal+B

	BAverage=BTotal/len(BLevels)

	redTotal=0
	redPercentages=statsdict['redPercentage']
	for red in redPercentages:
		redTotal=redTotal+red

	redAverage=redTotal/len(redPercentages)
	pixwidth=inputImp.getCalibration().pixelWidth

	inputRoiArea=inputRoiArea/(pixwidth*pixwidth)
	
	print str(len(allList))+" "+str(len(redList))+" "+str(len(blueList))+" "+str(poreArea/inputRoiArea)+" "+str(redAverage)
Beispiel #10
0
        Nuclei.close()
        imp2.changes = False
        imp2.close()

        if automatic_save_results:
            dataname = imp1.getTitle()
            filename = dataname + ".csv"
            #files = glob.glob(savepath+"/"+dataname+"*.csv")
            savename = savepath + "/" + filename
            ort.saveAs(savename)
        else:
            print "not saving"

        if filenum == 0:
            dup = Duplicator()
            stack1 = dup.run(imp1)
            print "first round"
        else:
            try:
                dup = Duplicator()
                stack2 = dup.run(imp1)
                stack1 = concat.run(stack1, stack2)
                stack1.setTitle(directory)
                print "making stack"
            except NameError:
                dup = Duplicator()
                stack1 = dup.run(imp1)
                print "first image was empty"

        imp1.changes = False
        imp1.close()
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters):

	# set calibration
	detectionParameters.setCalibration(inputImp);
	
	# calculate area of roi 
	stats=inputImp.getStatistics()
	inputRoiArea=stats.area
	
	# get the bounding box of the active roi
	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.image().crop(interval, None, inputDataset.getImgPlus() ) 
	cropped=ops.image().crop(inputDataset.getImgPlus() , interval) 
	
	datacropped=data.create(cropped)
	display.createDisplay("cropped", datacropped)
	croppedPlus=IJ.getImage()
	
	# instantiate the duplicator and the substackmaker classes
	duplicator=Duplicator()
	substackMaker=SubstackMaker()
	
	# duplicate the roi
	duplicate=duplicator.run(croppedPlus)
	
	# convert duplicate of roi to HSB and get brightness
	IJ.run(duplicate, "HSB Stack", "");
	brightnessPlus=substackMaker.makeSubstack(duplicate, "3-3")
	brightness=ImgPlus(ImageJFunctions.wrapByte(brightnessPlus))
	brightnessPlus.setTitle("Brightness")
	#brightnessPlus.show()
	
	# make another duplicate, split channels and get red
	duplicate=duplicator.run(croppedPlus)
	channels=ChannelSplitter().split(duplicate)
	redPlus=channels[0]
	red=ImgPlus(ImageJFunctions.wrapByte(redPlus))
	
	# convert to lab
	IJ.run(croppedPlus, "Color Transformer", "colour=Lab")
	IJ.selectWindow('Lab')
	labPlus=IJ.getImage()

	croppedPlus.changes=False
	croppedPlus.close()
	
	# get the A channel
	APlus=substackMaker.makeSubstack(labPlus, "2-2")
	APlus.setTitle('A')
	#APlus.show()
	APlus.getProcessor().resetMinAndMax()
	#APlus.updateAndDraw()
	AThresholded=threshold(APlus, -10, 50)
	
	# get the B channel
	BPlus=substackMaker.makeSubstack(labPlus, "3-3")
	BPlus.setTitle('B')
	#BPlus.show()
	BPlus.getProcessor().resetMinAndMax()
	#BPlus.updateAndDraw()
	BThresholded=threshold(BPlus, -10, 50)
	
	# AND the Athreshold and Bthreshold to get a map of the red pixels
	ic = ImageCalculator();
	redMask = ic.run("AND create", AThresholded, BThresholded);
	IJ.run(redMask, "Divide...", "value=255");
	
	labPlus.close()

	fast=True
	
	# threshold the spots from the red channel
	if (fast==False):
		thresholdedred=SpotDetectionGray(red, data, display, ops, "triangle")
		impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped")
	else:
		impthresholdedred=SpotDetection2(redPlus)
	
	# threshold the spots from the brightness channel
	if (fast==False):
		thresholded=SpotDetectionGray(brightness, data, display, ops, "triangle")
		impthresholded=ImageJFunctions.wrap(thresholded, "wrapped")
	else:
		impthresholded=SpotDetection2(brightnessPlus)
		
	# or the thresholding results from red and brightness channel
	impthresholded = ic.run("OR create", impthresholded, impthresholdedred);
	
	roim=RoiManager(True)
	
	# convert to mask
	Prefs.blackBackground = True
	IJ.run(impthresholded, "Convert to Mask", "")
	
	def isRed(imp, roi):
		stats = imp.getStatistics()
	
		if (stats.mean>detectionParameters.porphyrinRedPercentage): return True
		else: return False
	
	def notRed(imp, roi):
		stats = imp.getStatistics()
	
		if (stats.mean>detectionParameters.porphyrinRedPercentage): return False
		else: return True


	roiClone=inputRoi.clone()
	roiClone.setLocation(0,0)
	Utility.clearOutsideRoi(impthresholded, roiClone)

	impthresholded.show()
	
	countParticles(impthresholded, roim, detectionParameters.porphyrinMinSize, detectionParameters.porphyrinMaxSize, \
		detectionParameters.porphyrinMinCircularity, detectionParameters.porphyrinMaxCircularity)
	
	uvPoreList=[]
	for roi in roim.getRoisAsArray():
		uvPoreList.append(roi.clone())

	
	#allList=uvPoreList+closedPoresList+openPoresList
	
	# count particles that are porphyrins (red)
	porphyrinList=CountParticles.filterParticlesWithFunction(redMask, uvPoreList, isRed)
	# count particles that are visible on uv but not porphyrins
	sebumList=CountParticles.filterParticlesWithFunction(redMask, uvPoreList, notRed)

	
	# for each roi add the offset such that the roi is positioned in the correct location for the 
	# original image
	[roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in uvPoreList]
	
	# draw the ROIs on to the image
	inputImp.getProcessor().setColor(Color.green)
	IJ.run(inputImp, "Line Width...", "line=3");
	inputImp.getProcessor().draw(inputRoi)
	IJ.run(inputImp, "Line Width...", "line=1");
	[CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta) for roi in porphyrinList]
	[CountParticles.drawParticleOnImage(inputImp, roi, Color.green) for roi in sebumList]	
	inputImp.updateAndDraw()

	# calculate stats for the UV visible particles
	detectionParameters.setCalibration(APlus)
	statsDictUV=CountParticles.calculateParticleStatsUV(APlus, BPlus, redMask, roim.getRoisAsArray())
	
	totalUVPoreArea=0
	for area in statsDictUV['Areas']:
		totalUVPoreArea=totalUVPoreArea+area
	averageUVPoreArea=totalUVPoreArea/len(statsDictUV['Areas'])

	poreDiameter=0
	for diameter in statsDictUV['Diameters']:
		poreDiameter=poreDiameter+diameter
	poreDiameter=poreDiameter/len(statsDictUV['Diameters'])

	redTotal=0
	for red in statsDictUV['redPercentage']:
		redTotal=redTotal+red
	redAverage=redTotal/len(statsDictUV['redPercentage'])

	statslist=[len(porphyrinList), 100*redAverage];
	statsheader=[Messages.Porphyrins,  Messages.PercentageRedPixels]

	print("Roi Area: "+str(inputRoiArea))
	print("Total Pore Area: "+str(totalUVPoreArea))
	print("Average Pore Area: "+str(averageUVPoreArea))
	print str(len(uvPoreList))+" "+str(len(porphyrinList))+" "+str(len(sebumList))+" "+str(100*totalUVPoreArea/inputRoiArea)+" "+str(100*redAverage)
	print "cp min circularity"+str(detectionParameters.closedPoresMinCircularity)+":"+str(detectionParameters.closedPoresMinSize)

	# close the thresholded image
	impthresholded.changes=False
	impthresholded.close()
	
	return uvPoreList, statslist, statsheader
Beispiel #12
0
def duplicate_channel(imp, start_slice, end_slice, channel):
    d = Duplicator()
    new_imp = d.run(imp, channel, channel, start_slice, end_slice, 1, 1)
    return new_imp
def NND(imp, mapC, compareC):
    cal = imp.getCalibration()
    title = imp.getTitle()
    impZ = imp.getNSlices()
    dup = Duplicator()
    compare = dup.run(imp, compareC, compareC, 1, impZ, 1, 1)
    compare = reslice(compare, cal.pixelWidth)
    IJ.run(compare, "Gaussian Blur 3D...", "x=3 y=3 z=3")
    Z = compare.getNSlices()
    IJ.setAutoThreshold(compare, THRESHOLD + " dark stack")
    Prefs.blackBackground = True
    IJ.run(compare, "Convert to Mask",
           "method=" + THRESHOLD + " background=Dark black")
    IJ.run(compare, "Exact Signed Euclidean Distance Transform (3D)", "")
    edtcompare = WindowManager.getImage("EDT")
    edtcompare.getWindow().setVisible(False)

    mapp = dup.run(imp, mapC, mapC, 1, impZ, 1, 1)
    mapp = reslice(mapp, cal.pixelWidth)
    IJ.run(mapp, "Gaussian Blur 3D...", "x=3 y=3 z=3")
    IJ.setAutoThreshold(mapp, THRESHOLD + " dark stack")
    Prefs.blackBackground = True
    IJ.run(mapp, "Convert to Mask",
           "method=" + THRESHOLD + " background=Dark black")

    dists = []
    rt = ResultsTable()
    ol = Overlay()
    row = 0
    for z in range(Z):
        mapp.setPosition(z + 1)
        IJ.run(mapp, "Create Selection", "")
        if mapp.getStatistics().mean == 0:
            IJ.run(mapp, "Make Inverse", "")
        roi = mapp.getRoi()
        if roi is None:
            continue

        edtcompare.setPosition(z + 1)
        edtcompare.setRoi(roi)
        IJ.setBackgroundColor(0, 0, 0)
        IJ.run(edtcompare, "Clear Outside", "slice")

        ip = edtcompare.getProcessor()
        roiList = ShapeRoi(roi).getRois()  #split roi to limit bounds
        for sr in roiList:
            bounds = sr.getBounds()
            for y in range(0, bounds.height):
                for x in range(0, bounds.width):
                    if sr.contains(bounds.x + x, bounds.y + y):
                        d = ip.getf(bounds.x + x,
                                    bounds.y + y) * cal.pixelWidth * 1000
                        rt.setValue("C" + str(mapC) + " X", row,
                                    (bounds.x + x) * cal.pixelWidth)
                        rt.setValue("C" + str(mapC) + " Y", row,
                                    (bounds.y + y) * cal.pixelHeight)
                        rt.setValue("C" + str(mapC) + " Z", row,
                                    z * cal.pixelDepth)
                        rt.setValue("Distance to C" + str(compareC) + " (nm)",
                                    row, d)
                        row += 1
                        histD = d
                        if histD >= 0:  #set all overlapping voxel distances to 0
                            histD = 0
                        dists.append(
                            -histD)  #invert to positive for outside distance
        posZ = int(((z + 1) / float(Z)) * impZ) + 1
        roi.setPosition(0, posZ, 1)
        roi.setStrokeColor(Colour.MAGENTA)
        ol.add(roi)

        compare.setPosition(z + 1)
        IJ.run(compare, "Create Selection", "")
        if compare.getStatistics().mean == 0:
            IJ.run(compare, "Make Inverse", "")
        compareRoi = compare.getRoi()
        if compareRoi is not None:
            compareRoi.setPosition(0, posZ, 1)
            compareRoi.setStrokeColor(Colour.CYAN)
            ol.add(compareRoi)

    edtcompare.killRoi()
    histogram(title + " C" + str(mapC) + "-C" + str(compareC) + " Distance",
              dists)
    rt.show(title + " C" + str(mapC) + "-C" + str(compareC) + " Distance")
    imp.setOverlay(ol)
    compare.close()
    edtcompare.changes = False
    edtcompare.close()
    mapp.close()
Beispiel #14
0
	def getThreshold(self, imp, method):
		thresholder = Auto_Threshold()
		duplicator = Duplicator()
		tmp = duplicator.run(imp)
		return thresholder.exec(tmp, method, False, False, True, False, False, True)
Beispiel #15
0
def poreDetectionUV(inputImp, inputDataset, inputRoi, ops, data, display,
                    detectionParameters):

    # set calibration
    detectionParameters.setCalibration(inputImp)

    # calculate area of roi
    stats = inputImp.getStatistics()
    inputRoiArea = stats.area

    # get the bounding box of the active roi
    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.image().crop(interval, None, inputDataset.getImgPlus() )
    cropped = ops.image().crop(inputDataset.getImgPlus(), interval)

    datacropped = data.create(cropped)
    display.createDisplay("cropped", datacropped)
    croppedPlus = IJ.getImage()

    # instantiate the duplicator and the substackmaker classes
    duplicator = Duplicator()
    substackMaker = SubstackMaker()

    # duplicate the roi
    duplicate = duplicator.run(croppedPlus)

    # convert duplicate of roi to HSB and get brightness
    IJ.run(duplicate, "HSB Stack", "")
    brightnessPlus = substackMaker.makeSubstack(duplicate, "3-3")
    brightness = ImgPlus(ImageJFunctions.wrapByte(brightnessPlus))
    brightnessPlus.setTitle("Brightness")
    #brightnessPlus.show()

    # make another duplicate, split channels and get red
    duplicate = duplicator.run(croppedPlus)
    channels = ChannelSplitter().split(duplicate)
    redPlus = channels[0]
    red = ImgPlus(ImageJFunctions.wrapByte(redPlus))

    # convert to lab
    IJ.run(croppedPlus, "Color Transformer", "colour=Lab")
    IJ.selectWindow('Lab')
    labPlus = IJ.getImage()

    croppedPlus.changes = False
    croppedPlus.close()

    # get the A channel
    APlus = substackMaker.makeSubstack(labPlus, "2-2")
    APlus.setTitle('A')
    #APlus.show()
    APlus.getProcessor().resetMinAndMax()
    #APlus.updateAndDraw()
    AThresholded = threshold(APlus, -10, 50)

    # get the B channel
    BPlus = substackMaker.makeSubstack(labPlus, "3-3")
    BPlus.setTitle('B')
    #BPlus.show()
    BPlus.getProcessor().resetMinAndMax()
    #BPlus.updateAndDraw()
    BThresholded = threshold(BPlus, -10, 50)

    # AND the Athreshold and Bthreshold to get a map of the red pixels
    ic = ImageCalculator()
    redMask = ic.run("AND create", AThresholded, BThresholded)
    IJ.run(redMask, "Divide...", "value=255")

    labPlus.close()

    fast = True

    # threshold the spots from the red channel
    if (fast == False):
        thresholdedred = SpotDetectionGray(red, data, display, ops, "triangle")
        impthresholdedred = ImageJFunctions.wrap(thresholdedred, "wrapped")
    else:
        impthresholdedred = SpotDetection2(redPlus)

    # threshold the spots from the brightness channel
    if (fast == False):
        thresholded = SpotDetectionGray(brightness, data, display, ops,
                                        "triangle")
        impthresholded = ImageJFunctions.wrap(thresholded, "wrapped")
    else:
        impthresholded = SpotDetection2(brightnessPlus)

    # or the thresholding results from red and brightness channel
    impthresholded = ic.run("OR create", impthresholded, impthresholdedred)

    roim = RoiManager(True)

    # convert to mask
    Prefs.blackBackground = True
    IJ.run(impthresholded, "Convert to Mask", "")

    def isRed(imp, roi):
        stats = imp.getStatistics()

        if (stats.mean > detectionParameters.porphyrinRedPercentage):
            return True
        else:
            return False

    def notRed(imp, roi):
        stats = imp.getStatistics()

        if (stats.mean > detectionParameters.porphyrinRedPercentage):
            return False
        else:
            return True

    roiClone = inputRoi.clone()
    roiClone.setLocation(0, 0)
    Utility.clearOutsideRoi(impthresholded, roiClone)

    impthresholded.show()

    countParticles(impthresholded, roim, detectionParameters.porphyrinMinSize, detectionParameters.porphyrinMaxSize, \
     detectionParameters.porphyrinMinCircularity, detectionParameters.porphyrinMaxCircularity)

    uvPoreList = []
    for roi in roim.getRoisAsArray():
        uvPoreList.append(roi.clone())

    #allList=uvPoreList+closedPoresList+openPoresList

    # count particles that are porphyrins (red)
    porphyrinList = CountParticles.filterParticlesWithFunction(
        redMask, uvPoreList, isRed)
    # count particles that are visible on uv but not porphyrins
    sebumList = CountParticles.filterParticlesWithFunction(
        redMask, uvPoreList, notRed)

    # for each roi add the offset such that the roi is positioned in the correct location for the
    # original image
    [
        roi.setLocation(roi.getXBase() + x1,
                        roi.getYBase() + y1) for roi in uvPoreList
    ]

    # draw the ROIs on to the image
    inputImp.getProcessor().setColor(Color.green)
    IJ.run(inputImp, "Line Width...", "line=3")
    inputImp.getProcessor().draw(inputRoi)
    IJ.run(inputImp, "Line Width...", "line=1")
    [
        CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta)
        for roi in porphyrinList
    ]
    [
        CountParticles.drawParticleOnImage(inputImp, roi, Color.green)
        for roi in sebumList
    ]
    inputImp.updateAndDraw()

    # calculate stats for the UV visible particles
    detectionParameters.setCalibration(APlus)
    statsDictUV = CountParticles.calculateParticleStatsUV(
        APlus, BPlus, redMask, roim.getRoisAsArray())

    totalUVPoreArea = 0
    for area in statsDictUV['Areas']:
        totalUVPoreArea = totalUVPoreArea + area
    averageUVPoreArea = totalUVPoreArea / len(statsDictUV['Areas'])

    poreDiameter = 0
    for diameter in statsDictUV['Diameters']:
        poreDiameter = poreDiameter + diameter
    poreDiameter = poreDiameter / len(statsDictUV['Diameters'])

    redTotal = 0

    for red in statsDictUV['redPercentage']:
        redTotal = redTotal + red
    redAverage = redTotal / len(statsDictUV['redPercentage'])

    statslist = [len(porphyrinList), 100 * redAverage]
    statsheader = [Messages.Porphyrins, Messages.PercentageRedPixels]

    print("Roi Area: " + str(inputRoiArea))
    print("Total Pore Area: " + str(totalUVPoreArea))
    print("Average Pore Area: " + str(averageUVPoreArea))
    print str(len(uvPoreList)) + " " + str(len(porphyrinList)) + " " + str(
        len(sebumList)) + " " + str(
            100 * totalUVPoreArea / inputRoiArea) + " " + str(100 * redAverage)
    print "cp min circularity" + str(
        detectionParameters.closedPoresMinCircularity) + ":" + str(
            detectionParameters.closedPoresMinSize)

    # close the thresholded image
    impthresholded.changes = False
    impthresholded.close()

    return uvPoreList, statslist, statsheader
def poreDetectionTrueColor(inputImp, inputDataset, inputRoi, ops, data, display, detectionParameters):
	
	detectionParameters.setCalibration(inputImp);
	
	# calculate area of roi 
	stats=inputImp.getStatistics()
	inputRoiArea=stats.area
	
	# get the bounding box of the active roi
	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.image().crop(inputDataset.getImgPlus(), interval ) 
	
	datacropped=data.create(cropped)
	display.createDisplay("cropped", datacropped)
	croppedPlus=IJ.getImage()
	
	# instantiate the duplicator and the substackmaker classes
	duplicator=Duplicator()
	substackMaker=SubstackMaker()
	
	# duplicate the roi
	duplicate=duplicator.run(croppedPlus)

	# separate into RGB and get the blue channel
	IJ.run(duplicate, "RGB Stack", "")
	bluePlus=substackMaker.makeSubstack(duplicate, "3-3")
	blue=ImgPlus(ImageJFunctions.wrapByte(bluePlus))
	bluePlus.setTitle("Blue")
	
	# duplicate and look for bright spots
	thresholdedLight=SpotDetection2(bluePlus)

	# duplicate and look for dark spots
	thresholdedDark=SpotDetection3(bluePlus, True)

	# convert to mask
	Prefs.blackBackground = True
	#IJ.run(thresholdedDark, "Convert to Mask", "")substackMaker

	# clear the region outside the roi
	clone=inputRoi.clone()
	clone.setLocation(0,0)
	Utility.clearOutsideRoi(thresholdedLight, clone)
	Utility.clearOutsideRoi(thresholdedDark, clone)
	roimClosedPores = RoiManager(True)
	detectionParameters.setCalibration(thresholdedDark)
	countParticles(thresholdedDark, roimClosedPores, detectionParameters.closedPoresMinSize, detectionParameters.closedPoresMaxSize, \
		detectionParameters.closedPoresMinCircularity, detectionParameters.closedPoresMaxCircularity)

	# count number of open pores
	roimOpenPores = RoiManager(True)
	detectionParameters.setCalibration(thresholdedDark)
	countParticles(thresholdedDark, roimOpenPores, detectionParameters.openPoresMinSize, detectionParameters.openPoresMaxSize, \
		detectionParameters.openPoresMinCircularity, detectionParameters.openPoresMaxCircularity)

	# count number of sebum
	roimSebum = RoiManager(True)
	detectionParameters.setCalibration(thresholdedLight)
	countParticles(thresholdedLight, roimSebum, detectionParameters.sebumMinSize, detectionParameters.sebumMaxSize, \
		detectionParameters.sebumMinCircularity, detectionParameters.sebumMaxCircularity)
	
	# create lists for open and closed pores
	closedPoresList=[]
	for roi in roimClosedPores.getRoisAsArray():
		closedPoresList.append(roi.clone())
	openPoresList=[]
	for roi in roimOpenPores.getRoisAsArray():
		openPoresList.append(roi.clone())

	# create lists for sebum
	sebumsList=[]
	for roi in roimSebum.getRoisAsArray():
		sebumsList.append(roi.clone())

	# a list of all pores
	allList=closedPoresList+openPoresList+sebumsList
	
	# calculate the stats for all pores
	detectionParameters.setCalibration(bluePlus)
	statsDict=CountParticles.calculateParticleStats(bluePlus, allList)

	poresTotalArea=0
	for area in statsDict['Areas']:
		poresTotalArea=poresTotalArea+area
		print area
	poresAverageArea=poresTotalArea/len(statsDict['Areas'])
		

	# for each roi add the offset such that the roi is positioned in the correct location for the 
	# original image
	[roi.setLocation(roi.getXBase()+x1, roi.getYBase()+y1) for roi in allList]
	
	# draw the rois on the image
	inputImp.getProcessor().setColor(Color.green)
	IJ.run(inputImp, "Line Width...", "line=3");
	inputImp.getProcessor().draw(inputRoi)
	IJ.run(inputImp, "Line Width...", "line=1");
	[CountParticles.drawParticleOnImage(inputImp, roi, Color.red) for roi in closedPoresList]
	[CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta) for roi in openPoresList]
	[CountParticles.drawParticleOnImage(inputImp, roi, Color.green) for roi in sebumsList]
	
	inputImp.updateAndDraw()
	
	# close images that represent intermediate steps
	croppedPlus.changes=False
	croppedPlus.close()
	bluePlus.changes=False
	bluePlus.close()

	print "Total ROI Area: "+str(inputRoiArea)
	print "Num closed pores: "+str(len(closedPoresList))
	print "Num open pores: "+str(len(openPoresList))
	print "Num sebums: "+str(len(sebumsList))
	
	print "Total particles: "+str(len(allList))+ " total area: "+str(poresTotalArea)
	
	statslist=[inputRoiArea, len(allList), len(closedPoresList), len(openPoresList), len(sebumsList), poresAverageArea, 100*poresTotalArea/inputRoiArea]
	header=[Messages.TotalAreaMask, Messages.TotalDetectedPores, Messages.ClosedPores, Messages.OpenPores, Messages.Sebum, Messages.PoresAverageArea, Messages.PoresFractionalArea]
	
	return header,statslist

	
def poreDetectionTrueColor(inputImp, inputDataset, inputRoi, ops, data,
                           display, detectionParameters):

    detectionParameters.setCalibration(inputImp)

    # calculate area of roi
    stats = inputImp.getStatistics()
    inputRoiArea = stats.area

    # get the bounding box of the active roi
    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())

    datacropped = data.create(cropped)
    display.createDisplay("cropped", datacropped)
    croppedPlus = IJ.getImage()

    duplicator = Duplicator()
    substackMaker = SubstackMaker()
    # duplicate the roi
    duplicate = duplicator.run(croppedPlus)

    # separate into RGB and get the blue channel
    IJ.run(duplicate, "RGB Stack", "")
    bluePlus = substackMaker.makeSubstack(duplicate, "3-3")
    blue = ImgPlus(ImageJFunctions.wrapByte(bluePlus))
    bluePlus.setTitle("Blue")

    # duplicate and look for bright spots
    thresholdedLight = SpotDetection2(bluePlus)

    # duplicate and look for dark spots
    thresholdedDark = SpotDetection3(bluePlus, True)

    # convert to mask
    Prefs.blackBackground = True
    #IJ.run(thresholdedDark, "Convert to Mask", "")

    # clear the region outside the roi
    clone = inputRoi.clone()
    clone.setLocation(0, 0)
    Utility.clearOutsideRoi(thresholdedLight, clone)
    Utility.clearOutsideRoi(thresholdedDark, clone)
    roimClosedPores = RoiManager(True)
    detectionParameters.setCalibration(thresholdedDark)
    countParticles(thresholdedDark, roimClosedPores, detectionParameters.closedPoresMinSize, detectionParameters.closedPoresMaxSize, \
     detectionParameters.closedPoresMinCircularity, detectionParameters.closedPoresMaxCircularity)

    # count number of open pores
    roimOpenPores = RoiManager(True)
    detectionParameters.setCalibration(thresholdedDark)
    countParticles(thresholdedDark, roimOpenPores, detectionParameters.openPoresMinSize, detectionParameters.openPoresMaxSize, \
     detectionParameters.openPoresMinCircularity, detectionParameters.openPoresMaxCircularity)

    # count number of sebum
    roimSebum = RoiManager(True)
    detectionParameters.setCalibration(thresholdedLight)
    countParticles(thresholdedLight, roimSebum, detectionParameters.sebumMinSize, detectionParameters.sebumMaxSize, \
     detectionParameters.sebumMinCircularity, detectionParameters.sebumMaxCircularity)

    # create lists for open and closed pores
    closedPoresList = []
    for roi in roimClosedPores.getRoisAsArray():
        closedPoresList.append(roi.clone())
    openPoresList = []
    for roi in roimOpenPores.getRoisAsArray():
        openPoresList.append(roi.clone())

    # create lists for sebum
    sebumsList = []
    for roi in roimSebum.getRoisAsArray():
        sebumsList.append(roi.clone())

    # a list of all pores
    allList = closedPoresList + openPoresList + sebumsList

    # calculate the stats for all pores
    detectionParameters.setCalibration(bluePlus)
    statsDict = CountParticles.calculateParticleStats(bluePlus, allList)

    poresTotalArea = 0
    for area in statsDict['Areas']:
        poresTotalArea = poresTotalArea + area
        print area
    poresAverageArea = poresTotalArea / len(statsDict['Areas'])

    # for each roi add the offset such that the roi is positioned in the correct location for the
    # original image
    [
        roi.setLocation(roi.getXBase() + x1,
                        roi.getYBase() + y1) for roi in allList
    ]

    # draw the rois on the image
    inputImp.getProcessor().setColor(Color.green)
    IJ.run(inputImp, "Line Width...", "line=3")
    inputImp.getProcessor().draw(inputRoi)
    IJ.run(inputImp, "Line Width...", "line=1")
    [
        CountParticles.drawParticleOnImage(inputImp, roi, Color.red)
        for roi in closedPoresList
    ]
    [
        CountParticles.drawParticleOnImage(inputImp, roi, Color.magenta)
        for roi in openPoresList
    ]
    [
        CountParticles.drawParticleOnImage(inputImp, roi, Color.green)
        for roi in sebumsList
    ]

    inputImp.updateAndDraw()

    # close images that represent intermediate steps
    croppedPlus.changes = False
    croppedPlus.close()
    bluePlus.changes = False
    bluePlus.close()

    print "Total ROI Area: " + str(inputRoiArea)
    print "Num closed pores: " + str(len(closedPoresList))
    print "Num open pores: " + str(len(openPoresList))
    print "Num sebums: " + str(len(sebumsList))

    print "Total particles: " + str(
        len(allList)) + " total area: " + str(poresTotalArea)

    statslist = [
        inputRoiArea,
        len(allList),
        len(closedPoresList),
        len(openPoresList),
        len(sebumsList), poresAverageArea, 100 * poresTotalArea / inputRoiArea
    ]
    header = [
        Messages.TotalAreaMask, Messages.TotalDetectedPores,
        Messages.ClosedPores, Messages.OpenPores, Messages.Sebum,
        Messages.PoresAverageArea, Messages.PoresFractionalArea
    ]

    return header, statslist