Ejemplo n.º 1
0
def bSaveZProject(imp, dstFolder, shortname):
	#bring to front
	impWinStr = imp.getTitle()
	IJ.selectWindow(impWinStr)
	
	bPrintLog('Making Z-Project from ' + impWinStr, 2)
	madez = 0
	z1 = 1
	z2 = imp.getNSlices()
	if z2>1:
		paramStr = 'start=%s stop=%s projection=[Max Intensity]' % (z1, z2)
		IJ.run('Z Project...', paramStr) #makes 'MAX_' window
		zWinStr = 'MAX_' + impWinStr
		zImp = WindowManager.getImage(zWinStr)
		madez = 1
	else:
		zImp = imp
			
	if dstFolder != None:
		dstFile = dstFolder + 'max_' + shortname + '.tif'
		bPrintLog('Saving Z-Project: ' + dstFile, 2)
		bSaveStack(zImp, dstFile)

	if madez:
		zImp.changes = 0
		zImp.close()
Ejemplo n.º 2
0
	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()) 
Ejemplo n.º 3
0
def Processing_Type_1():
	IJ.selectWindow("Red channel");
	IJ.run("Duplicate...", "title=[Red channel Processed 1] duplicate range=1-103");
	IJ.selectWindow("Red channel Processed 1");
	#IJ.setAutoThreshold("Default dark");
	#IJ.run("Enhance Contrast...", "saturated=0.4 normalize process_all");
	#IJ.run("16-bit");
	IJ.run("Convert to Mask", "method=Huang background=Dark calculate");
	IJ.run("Despeckle", "stack");
def draw_bounding_boxes(objects,title,templateImage):
	drawnIp = ByteProcessor(templateImage.getWidth(),templateImage.getHeight())
	drawnImage = ImagePlus(title,drawnIp)
	drawnImage.show()
	IJ.selectWindow(title)
	for j in range(len(objects)):
		IJ.makeRectangle(objects[j][42],objects[j][43],objects[j][45]-objects[j][42],objects[j][46]-objects[j][43])
		IJ.run("Draw","stack")
	drawnImage.hide()
	return(drawnImage)
Ejemplo n.º 5
0
def main():
	LoadData()
	Extract_Red_Channel(RED)
	Processing_Type_1()
	#ConnectedRegions()
	IJ.selectWindow("Red channel Processed 1")
	for i in range(1,103):
		IJ.run("Next Slice [>]")
		RoiSelection(i)
	IJ.selectWindow("Red channel Processed 1")
	LoadRoi()
Ejemplo n.º 6
0
def LoadRoi():
	IJ.selectWindow("Loaded Image")
	rm.runCommand("Select All")
	rm.runCommand("Deselect")
	imp_load = IJ.getImage()
	index = 0
	for rio_polygon in regions_array:
		index=index+1
		imp_load.setSlice(index)
		rm.addRoi(rio_polygon)
	rm.moveRoisToOverlay(imp)
Ejemplo n.º 7
0
def detection(imp, c):
    cal = imp.getCalibration()
    model = Model()
    settings = Settings()
    settings.setFrom(imp)
    # Configure detector - Manually determined as best
    settings.detectorFactory = LogDetectorFactory()
    settings.detectorSettings = {
        'DO_SUBPIXEL_LOCALIZATION': True,
        'RADIUS': 2.0,
        'TARGET_CHANNEL': c,
        'THRESHOLD': 20.0,
        'DO_MEDIAN_FILTERING': False,
    }
    settings.addSpotAnalyzerFactory(SpotIntensityAnalyzerFactory())
    settings.addSpotAnalyzerFactory(SpotContrastAndSNRAnalyzerFactory())
    settings.trackerFactory = SparseLAPTrackerFactory()
    settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap()
    trackmate = TrackMate(model, settings)
    ok = trackmate.checkInput()
    if not ok:
        sys.exit(str(trackmate.getErrorMessage()))
    try:
        ok = trackmate.process()
    except:
        IJ.log("Nothing detected")
        IJ.selectWindow('test')
        IJ.run('Close')
    else:
        selectionModel = SelectionModel(model)
        displayer = HyperStackDisplayer(model, selectionModel, imp)
        displayer.render()
        displayer.refresh()
        # Get spots information
        spots = model.getSpots()
        spotIt = spots.iterator(0, False)
        # Loop through spots and save into files
        # Fetch spot features directly from spot
        sid = []
        x = []
        y = []
        q = []
        r = []
        spotID = 0
        for spot in spotIt:
            spotID = spotID + 1
            sid.append(spotID)
            x.append(spot.getFeature('POSITION_X'))
            y.append(spot.getFeature('POSITION_Y'))
            q.append(spot.getFeature('QUALITY'))
            r.append(spot.getFeature('RADIUS'))
        data = zip(sid, x, y, q, r)
        return data
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
	def ShowRoi(self,imp,point, name):
		for indices in self.__gridrectangle.keys() :
			if self.__gridrectangle[indices].contains(point) :
				roitemp=self.__dictCells[name][self.__listcellname[indices[0]-1]].getRoi(indices[1]-1)
		if isinstance(roitemp,Roi) :
			idimages=WindowManager.getIDList()
			for i in range(len(idimages)) :
				if idimages[i]==self.__img.getID() :
					IJ.selectWindow(self.__img.getID())	
			rm = RoiManager.getInstance()
			for i in range(rm.getCount()) :
				if rm.getName(str(i))==roitemp.getName() :
					rm.select(i)
					selectroi=self.__img.getRoi()
					#col=rm.getSelectedRoisAsArray().getStrokeColor()
					selectroi.setStrokeColor(Color.red)
					selectroi.setStrokeWidth(3)
					self.__img.updateAndDraw()
					break
def main():
	
	
	IJ.open(dir_path+file_name) #IJ.open("/Users/richardhart/Dropbox/AMRE/2013-08-03-96dpiPrintTesting-DifferentZheights-Sample.png")
	
	IJ.selectWindow(file_name) #IJ.selectWindow("2013-08-03-96dpiPrintTesting-DifferentZheights-Sample.png")
	
	IJ.run("Options...", "iterations=1 count=1 edm=Overwrite") #setting binary mask options
	
	IJ.run("Make Binary") #converting a picture o a binary image. 

	IJ.run("Watershed")	#Watershed breaks appart blobs in a binary image into smaller pieces
	
	IJ.run("Set Measurements...", "area mean standard modal min centroid center perimeter bounding fit shape feret's integrated median skewness kurtosis area_fraction stack redirect=None decimal=3") #Specifying what measurements to take 
	
	IJ.run("Analyze Particles...", "size=0-Infinity circularity=0.00-1.00 show=Ellipses display clear include") #taking measurements
	
	IJ.selectWindow("Results") #Making sure the results are selected so the window's data will be saved
	
	IJ.saveAs("Results", dir_path + "Results.txt"); #IJ.saveAs("/Users/richardhart/Dropbox/AMRE/Results.txt")
Ejemplo n.º 11
0
	def __selectMeasureStack(self) : 
		# We allow the user to choose what to measure in the stack, and on which stack.
		gd1=NonBlockingGenericDialog("Stack Choice for measures")
		idimages=WindowManager.getIDList()
		images=[WindowManager.getImage(imgID) for imgID in idimages if WindowManager.getImage(imgID).getImageStackSize()>1 ]
		imagesnames=[img.getTitle() for img in images]

		activindex=0
		
		for i in range(len(imagesnames)) : 
				if imagesnames[i] == self.__activeTitle : 
					activindex=i
				
		gd1.addChoice("Select a stack in the list : ",imagesnames,imagesnames[activindex])
		gd1.showDialog()
		chosenstack=gd1.getNextChoice()
		self.__img=WindowManager.getImage(chosenstack)
		IJ.selectWindow(self.__img.getID())
		if gd1.wasOKed() : return True
		else : 	return False
Ejemplo n.º 12
0
def Extract_Red_Channel(color):
	IJ.selectWindow("Loaded Image");
	imp = IJ.getImage()
	stack = imp.getImageStack()  
	print "number of slices:", imp.getNSlices()  
	# A list of red slices  
	reds = []  
	# Iterate each slice in the stack  
	for i in xrange(1, imp.getNSlices()+1):  
	  # Get the ColorProcessor slice at index i  
	  cp = stack.getProcessor(i)
	  # Get its green channel as a FloatProcessor  
	  fp = cp.toFloat(color, None)  
	  # ... and store it in a list  
	  reds.append(fp)  
	# Create a new stack with only the green channel  
	stack2 = ImageStack(imp.width, imp.height)  
	for fp in reds:  
	  stack2.addSlice(None, fp)  
	# Create a new image with the stack of green channel slices  
	imp2 = ImagePlus("Red channel", stack2)  
	# Set a green look-up table:  
	IJ.run(imp2, "Red", "")  
	imp2.show()  	
Ejemplo n.º 13
0
	def __selectTrackStack(self) : 
		gd0=NonBlockingGenericDialog("Stack Choice")
		idimages=WindowManager.getIDList()
		#images=[WindowManager.getImage(imgID) for imgID in idimages if WindowManager.getImage(imgID).getImageStackSize()>1 ]
		images=[WindowManager.getImage(imgID) for imgID in idimages]
		imagesnames=[img.getTitle() for img in images]
		for i in range(len(imagesnames)) : 
			if imagesnames[i] == self.__activeTitle : activindex=i
				
		gd0.addChoice("Select a stack in the list : ",imagesnames,imagesnames[activindex])
		gd0.showDialog()
			
		chosenstack=gd0.getNextChoice()
		self.__img = WindowManager.getImage(chosenstack)
		self.__maxLife = self.__img.getImageStackSize()

		IJ.selectWindow(self.__img.getID())
		self.__activeTitle=self.__img.getTitle()
		self.__imagesnames[:]=[]
		#self.__imagesnames.append("image1")
		self.__imagesnames.append(self.__activeTitle)

		if gd0.wasOKed() : return True
		else : 	return False
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')
Ejemplo n.º 15
0
def runOneFile(fullFilePath):
	global gFileType
	global gNumChannels
	global gAlignBatchVersion
	
	if not os.path.isfile(fullFilePath):
		bPrintLog('\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n',0)
		return 0

	bPrintLog(time.strftime("%H:%M:%S") + ' starting runOneFile(): ' + fullFilePath, 1)
	
	enclosingPath = os.path.dirname(fullFilePath)
	head, tail = os.path.split(enclosingPath)
	enclosingPath += '/'
	
	#make output folders
	destFolder = enclosingPath + tail + '_channels/'
	if not os.path.isdir(destFolder):
		os.makedirs(destFolder)
	destMaxFolder = destFolder + 'max/'
	if not os.path.isdir(destMaxFolder):
		os.makedirs(destMaxFolder)

	if gDoAlign:
		destAlignmentFolder = destFolder + 'alignment/'
		if not os.path.isdir(destAlignmentFolder):
			os.makedirs(destAlignmentFolder)
			
	if gSave8bit:
		eightBitFolder = destFolder + 'channels8/'
		if not os.path.isdir(eightBitFolder):
			os.makedirs(eightBitFolder)
		eightBitMaxFolder = eightBitFolder + 'max/'
		if not os.path.isdir(eightBitMaxFolder):
			os.makedirs(eightBitMaxFolder)
	
	if gFileType=='tif':
		# open .tif image
		imp = Opener().openImage(fullFilePath)
	else:
		# open .lsm
		cmdStr = 'open=%s autoscale color_mode=Default view=Hyperstack stack_order=XYCZT' % (fullFilePath,)
		IJ.run('Bio-Formats Importer', cmdStr)
		lsmpath, lsmfilename = os.path.split(fullFilePath)
		lsWindow = lsmfilename
		imp = WindowManager.getImage(lsWindow)
		
	# get parameters of image
	(width, height, nChannels, nSlices, nFrames) = imp.getDimensions()
	bitDepth = imp.getBitDepth()
	infoStr = imp.getProperty("Info") #get all .tif tags
	if not infoStr:
		infoStr = ''
	infoStr += 'bAlignBatch_Version=' + str(gAlignBatchVersion) + '\n'
	infoStr += 'bAlignBatch_Time=' + time.strftime("%Y%m%d") + '_' + time.strftime("%H%M%S") + '\n'
		
	msgStr = 'w:' + str(width) + ' h:' + str(height) + ' slices:' + str(nSlices) \
				+ ' channels:' + str(nChannels) + ' frames:' + str(nFrames) + ' bitDepth:' + str(bitDepth)
	bPrintLog(msgStr, 1)
	
	path, filename = os.path.split(fullFilePath)
	shortName, fileExtension = os.path.splitext(filename)

	#
	# look for num channels in ScanImage infoStr
	if gGetNumChanFromScanImage:
		for line in infoStr.split('\n'):
			#scanimage.SI4.channelsSave = [1;2]
			scanimage4 = find(line, 'scanimage.SI4.channelsSave =') == 0
			#state.acq.numberOfChannelsSave=2
			scanimage3 = find(line, 'state.acq.numberOfChannelsSave=') == 0
			if scanimage3:
				#print 'line:', line
				equalIdx = find(line, '=')
				line2 = line[equalIdx+1:]
				if gGetNumChanFromScanImage:
					gNumChannels = int(line2)
					bPrintLog('over-riding gNumChannels with: ' + str(gNumChannels), 2)
			if scanimage4:
				#print '   we have a scanimage 4 file ... now i need to exptract the number of channel'
				#print 'line:', line
				equalIdx = find(line, '=')
				line2 = line[equalIdx+1:]
				for delim in ';[]':
					line2 = line2.replace(delim, ' ')
				if gGetNumChanFromScanImage:
					gNumChannels = len(line2.split())
					bPrintLog('over-riding gNumChannels with: ' + str(gNumChannels), 2)

	# show
	imp.show()
	# split channels if necc. and grab the original window names
	if gNumChannels == 1:
		origImpWinStr = imp.getTitle() #use this when only one channel
		origImpWin = WindowManager.getWindow(origImpWinStr) #returns java.awt.Window
	
	if gNumChannels == 2:
		winTitle = imp.getTitle()
		bPrintLog('Deinterleaving 2 channels...', 1)
		IJ.run('Deinterleave', 'how=2 keep') #makes ' #1' and ' #2', with ' #2' frontmost
		origCh1WinStr = winTitle + ' #1'
		origCh2WinStr = winTitle + ' #2'
		origCh1Imp = WindowManager.getImage(origCh1WinStr)
		origCh2Imp = WindowManager.getImage(origCh2WinStr)
		origCh1File = destFolder + shortName + '_ch1.tif'
		origCh2File = destFolder + shortName + '_ch2.tif'

	# work on a copy, mostly for alignment with cropping
	copy = Duplicator().run(imp)
	#copy.copyAttributes(imp) #don't copy attributes, it copies the name (which we do not want)
	copy.show()
	
	#
	# crop (on copy)
	if gDoCrop:
		bPrintLog('making cropping rectangle (left,top,width,height) ',1)
		bPrintLog(str(gCropLeft) + ' ' + str(gCropTop) + ' ' +str(gCropWidth) + ' ' +str(gCropHeight), 2)
		
		roi = Roi(gCropLeft, gCropTop, gCropWidth, gCropHeight) #left,top,width,height
		copy.setRoi(roi)
		
		time.sleep(0.5) # otherwise, crop SOMETIMES failes. WHAT THE F**K FIJI DEVELOPERS, REALLY, WHAT THE F**K
		
		#bPrintLog('cropping', 1)
		IJ.run('Crop')
		infoStr += 'bCropping=' + str(gCropLeft) + ',' + str(gCropTop) + ',' + str(gCropWidth) + ',' + str(gCropHeight) + '\n'
	
	#
	# remove calibration ( on original)
	if gRemoveCalibration:
		cal = imp.getCalibration()
		calCoeff = cal.getCoefficients()
		if calCoeff:
			msgStr = 'Calibration is y=a+bx' + ' a=' + str(calCoeff[0]) + ' b=' + str(calCoeff[1])
			bPrintLog(msgStr, 1)
			
			#remove calibration
			bPrintLog('\tRemoving Calibration', 2)
			imp.setCalibration(None)
				
			#without these, 8-bit conversion goes to all 0 !!! what the f**k !!!
			#bPrintLog('calling imp.resetStack() and imp.resetDisplayRange()', 2)
			imp.resetStack()
			imp.resetDisplayRange()

			#get and print out min/max
			origMin = StackStatistics(imp).min
			origMax = StackStatistics(imp).max
			msgStr = '\torig min=' + str(origMin) + ' max=' + str(origMax)
			bPrintLog(msgStr, 2)
			
			# 20150723, 'shift everybody over by linear calibration intercept calCoeff[0] - (magic number)
			if 1:
				# [1] was this
				#msgStr = 'Subtracting original min '+str(origMin) + ' from stack.'
				#bPrintLog(msgStr, 2)
				#subArgVal = 'value=%s stack' % (origMin,)
				#IJ.run('Subtract...', subArgVal)
				# [2] now this
				#msgStr = 'Adding calCoeff[0] '+str(calCoeff[0]) + ' from stack.'
				#bPrintLog(msgStr, 2)
				#addArgVal = 'value=%s stack' % (int(calCoeff[0]),)
				#IJ.run('Add...', addArgVal)
				# [3] subtract a magic number 2^15-2^7 = 32768 - 128
				magicNumber = gLinearShift #2^15 - 128
				msgStr = 'Subtracting a magic number (linear shift) '+str(magicNumber) + ' from stack.'
				bPrintLog(msgStr, 2)
				infoStr += 'bLinearShift=' + str(gLinearShift) + '\n'
				subArgVal = 'value=%s stack' % (gLinearShift,)
			IJ.run(imp, 'Subtract...', subArgVal)
				
			# 20150701, set any pixel <0 to 0
			if 0:
				ip = imp.getProcessor() # returns a reference
				pixels = ip.getPixels() # returns a reference
				msgStr = '\tSet all pixels <0 to 0. This was added 20150701 ...'
				bPrintLog(msgStr, 2)
				pixels = map(lambda x: 0 if x<0 else x, pixels)
				bPrintLog('\t\t... done', 2)
				
			#get and print out min/max
			newMin = StackStatistics(imp).min
			newMax = StackStatistics(imp).max
			msgStr = '\tnew min=' + str(newMin) + ' max=' + str(newMax)
			bPrintLog(msgStr, 2)
			
			#append calibration to info string
			infoStr += 'bCalibCoeff_a = ' + str(calCoeff[0]) + '\n'
			infoStr += 'bCalibCoeff_b = ' + str(calCoeff[1]) + '\n'
			infoStr += 'bNewMin = ' + str(newMin) + '\n'
			infoStr += 'bNewMax = ' + str(newMax) + '\n'

	#
	# set up
	if gNumChannels == 1:
		impWinStr = copy.getTitle() #use this when only one channel
		impWin = WindowManager.getWindow(impWinStr) #returns java.awt.Window
	
	if gNumChannels == 2:
		winTitle = copy.getTitle()
		bPrintLog('Deinterleaving 2 channels...', 1)
		IJ.run('Deinterleave', 'how=2 keep') #makes ' #1' and ' #2', with ' #2' frontmost
		ch1WinStr = winTitle + ' #1'
		ch2WinStr = winTitle + ' #2'
		ch1Imp = WindowManager.getImage(ch1WinStr)
		ch2Imp = WindowManager.getImage(ch2WinStr)
		ch1File = destFolder + shortName + '_ch1.tif'
		ch2File = destFolder + shortName + '_ch2.tif'
		
	#
	# alignment
	if gDoAlign and gNumChannels == 1 and copy.getNSlices()>1:
		infoStr += 'AlignOnChannel=1' + '\n'
		#snap to middle slice
		if gAlignOnMiddleSlice:
			middleSlice = int(math.floor(copy.getNSlices() / 2)) #int() is necc., python is f*****g picky
		else:
			middleSlice = gAlignOnThisSlice
		copy.setSlice(middleSlice)
		
		transformationFile = destAlignmentFolder + shortName + '.txt'
		
		bPrintLog('MultiStackReg aligning:' + impWinStr, 1)
		stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' %(impWin,transformationFile)
		IJ.run('MultiStackReg', stackRegParams)
		infoStr += 'AlignOnSlice=' + str(middleSlice) + '\n'

		#20150723, we just aligned on a cropped copy, apply alignment to original imp
		origImpTitle = imp.getTitle()
		stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(origImpTitle,transformationFile)
		IJ.run('MultiStackReg', stackRegParams)		
		
	if gDoAlign and gNumChannels == 2 and ch1Imp.getNSlices()>1 and ch2Imp.getNSlices()>1:
		#apply to gAlignThisChannel
		alignThisWindow = ''
		applyAlignmentToThisWindow = ''
		if gAlignThisChannel == 1:
			infoStr += 'AlignOnChannel=1' + '\n'
			transformationFile = destAlignmentFolder + shortName + '_ch1.txt'
			alignThisWindow = ch1WinStr
			applyAlignmentToThisWindow = ch2WinStr
		else:
			infoStr += 'AlignOnChannel=2' + '\n'
			transformationFile = destAlignmentFolder + shortName + '_ch2.txt'
			alignThisWindow = ch2WinStr
			applyAlignmentToThisWindow = ch1WinStr
	
		alignThisImp = WindowManager.getImage(alignThisWindow)
		#snap to middle slice
		if gAlignOnMiddleSlice:
			middleSlice = int(math.floor(alignThisImp.getNSlices() / 2)) #int() is necc., python is f*****g picky
		else:
			middleSlice = gAlignOnThisSlice
		alignThisImp.setSlice(middleSlice)

		infoStr += 'bAlignOnSlice=' + str(middleSlice) + '\n'
		
		bPrintLog('MultiStackReg aligning:' + alignThisWindow, 1)
		stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' %(alignThisWindow,transformationFile)
		IJ.run('MultiStackReg', stackRegParams)
	
		# 20150723, we just aligned on a copy, apply alignment to both channels of original
		# ch1
		bPrintLog('MultiStackReg applying alignment to:' + origCh1WinStr, 1)
		stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(origCh1WinStr,transformationFile)
		IJ.run('MultiStackReg', stackRegParams)		
		# ch2
		bPrintLog('MultiStackReg applying alignment to:' + origCh2WinStr, 1)
		stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(origCh2WinStr,transformationFile)
		IJ.run('MultiStackReg', stackRegParams)		
		
		#apply alignment to other window
		#bPrintLog('MultiStackReg applying alignment to:' + applyAlignmentToThisWindow, 1)
		#applyAlignThisImp = WindowManager.getImage(applyAlignmentToThisWindow)
		#stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(applyAlignmentToThisWindow,transformationFile)
		#IJ.run('MultiStackReg', stackRegParams)		
	elif gDoAlign:
		bPrintLog('Skipping alignment, there may be only one slice?',3)
						
	#
	# save
	if gNumChannels == 1:
		imp.setProperty("Info", infoStr);
		impFile = destFolder + shortName + '.tif'
		#bPrintLog('Saving:' + impFile, 1)
		bSaveStack(imp, impFile)
		#max project
		bSaveZProject(imp, destMaxFolder, shortName)

	if gNumChannels == 2:
		#ch1
		origCh1Imp.setProperty("Info", infoStr);
		#bPrintLog('Saving:' + ch1File, 1)
		bSaveStack(origCh1Imp, ch1File)
		#max project
		bSaveZProject(origCh1Imp, destMaxFolder, shortName+'_ch1')

		#ch2
		origCh2Imp.setProperty("Info", infoStr);
		#bPrintLog('Saving:' + ch2File, 1)
		bSaveStack(origCh2Imp, ch2File)
 		#max project
		bSaveZProject(origCh2Imp, destMaxFolder, shortName+'_ch2')
		
 	#
	# post convert to 8-bit and save
	if gSave8bit:
		if bitDepth == 16:
			if gNumChannels == 1:
				bPrintLog('Converting to 8-bit:' + impWinStr, 1)
				IJ.selectWindow(impWinStr)
				#IJ.run('resetMinAndMax()')
				IJ.run("8-bit")
				impFile = eightBitFolder + shortName + '.tif'
				bPrintLog('Saving 8-bit:' + impFile, 2)
				bSaveStack(imp, impFile)
				#max project
				bSaveZProject(imp, eightBitMaxFolder, shortName)
				
			if gNumChannels == 2:
				#
				bPrintLog('Converting to 8-bit:' + origCh1WinStr, 1)
				IJ.selectWindow(origCh1WinStr)
				
				IJ.run("8-bit")
				impFile = eightBitFolder + shortName + '_ch1.tif'
				bPrintLog('Saving 8-bit:' + impFile, 2)
				bSaveStack(origCh1Imp, impFile)
				#max project
				bSaveZProject(origCh1Imp, eightBitMaxFolder, shortName+'_ch1')

				#
				bPrintLog('Converting to 8-bit:' + origCh2WinStr, 1)
				IJ.selectWindow(origCh2WinStr)
				#IJ.run('resetMinAndMax()')
				IJ.run("8-bit")
 				impFile = eightBitFolder + shortName + '_ch2.tif'
				bPrintLog('Saving 8-bit:' + impFile, 2)
				bSaveStack(origCh2Imp, impFile)
				#max project
				bSaveZProject(origCh2Imp, eightBitMaxFolder, shortName+'_ch2')
				
	#
	# close original window
	imp.changes = 0
	imp.close()
	#copy
	copy.changes = 0
	copy.close()

	#
	# close ch1/ch2
	if gNumChannels == 2:
		#original
		origCh1Imp.changes = 0
		origCh1Imp.close()
		origCh2Imp.changes = 0
		origCh2Imp.close()
		#copy
		ch1Imp.changes = 0
		ch1Imp.close()
		ch2Imp.changes = 0
		ch2Imp.close()

	bPrintLog(time.strftime("%H:%M:%S") + ' finished runOneFile(): ' + fullFilePath, 1)
Ejemplo n.º 16
0
    def doInBackground(self):
       try:                # In case there is an error, so that FIJI doesn't crash
          print "INICIO"
          print self.files
          print self.pix_erosion_mult

          label_files = [f for f in self.files if f.endswith('_label.png') or
                                                  f.endswith('_label.tif') or
                                                  f.endswith('_label.jpg')]
          total_label_files = len(label_files)

          print "total label files:"
          print total_label_files
          gvars["total label files"] = total_label_files



          for filenum, f in enumerate(label_files): # Loop through the files in the directory
            self.label_update(filenum+1, total_label_files)
            label_file = f
            print "----"
            print label_file
            original_name = re.sub(r"_label.*", "",f) # get name of the original image without extension

            if (original_name+".tif") in self.files: # for an original image with extension .tif
               original_file = original_name+".tif"
               print original_file
            elif (original_name+".tiff") in self.files: # for an original image with extension .tiff (with double f)
               original_file = original_name+".tiff"
               print original_file
            else:                   # If there is no original image
               original_file = "None"
               print original_file

            path_multiple = gvars['path_multiple_image_directory']
            print path_multiple

            ########### Section Label To Roi ###########
            RM = RoiManager()
            rm = RM.getRoiManager()
            label_image = IJ.openImage(path_multiple + "\\" + label_file)

            rm.reset()
            rm.runCommand(label_image,"Show All without labels") # we make sure we see the ROIs as they are loading

            imp2 = label_image.duplicate()
            ip = imp2.getProcessor()
            width = imp2.getWidth()
            height = imp2.getHeight() - 1

            max_label = int(imp2.getStatistics().max)
            max_digits = int(math.ceil(math.log(max_label,10))) # Calculate the number of digits for the name of the ROI (padding with zeros)
            IJ.setForegroundColor(0, 0, 0) # We pick black color to delete the label already computed

            for j in range(height):
               for i in range(width):
                  current_pixel_value = ip.getValue(i,j)
                  if current_pixel_value > 0:
                     IJ.doWand(imp2, i, j, 0.0, "Legacy smooth");

                     # We add this ROI to the ROI manager
                     roi = imp2.getRoi()
                     roi.setName(str(int(current_pixel_value)).zfill(max_digits))
                     rm.addRoi(roi)

                     ip.fill(roi) # Much faster than IJ.run(imp2, "Fill", ....

                     # Update ProgressBar
                     progress = int((current_pixel_value / max_label) * 100)
                     self.super__setProgress(progress)

            rm.runCommand(label_image,"Sort") # Sort the ROIs in the ROI manager
            rm.runCommand(label_image,"Show All without labels")

            ######### Section ROI erotion #########

            for i in range(0, rm.getCount()):
               roi = rm.getRoi(i)
               new_roi = RoiEnlarger.enlarge(roi, -self.pix_erosion_mult) # Important to use this instead of the IJ.run("Enlarge... much faster!!
               rm.setRoi(new_roi,i)

            ####### Section Save ROIs ##############
            print original_name
            path_to_multiple_ROIs = str(gvars['path_multiple_image_directory']) + "\\" + original_name + "_Erosion_" +str(self.pix_erosion_mult)+ "px_" + "RoiSet.zip"
            print path_to_multiple_ROIs
            rm.runCommand("Save", path_to_multiple_ROIs)
            print("ROIs saved")

            ####### Section open Original Image ##############
            if original_file != "None": # If there is an original image file besides the label image, we'll measure and generate table of measurements
                print "There is an original image associated to this label"
                original_image = IJ.openImage(path_multiple + "\\" + original_file)
                IJ.run(original_image, "Enhance Contrast", "saturated=0.35")
                rm.runCommand(original_image,"Show All without labels")
                #original_image.show()

                table_message = []
                is_scaled = original_image.getCalibration().scaled()
                if is_scaled:
                    spatial_cal = "True"
                else:
                    spatial_cal = "False"

                nChannels = original_image.getNChannels()

                print "Total channels:"
                print nChannels
                for current_channel in range(1,nChannels+1):
                   print "Current channel:"
                   print current_channel

                   original_image.setSlice(current_channel)
                   current_slice = str(original_image.getCurrentSlice()) #Get current slice for saving into filename
                   print "Current slice:"
                   print current_slice

                   IJ.run("Clear Results", "")
                   rm.runCommand(original_image,"Select All");
                   rm.runCommand(original_image,"Measure")

                   table = ResultsTable.getResultsTable().clone()
                   IJ.selectWindow("Results")
                   IJ.run("Close")


                   for i in range(0, table.size()):
                      table.setValue('File', i, str(original_name))
                      table.setValue('Channel', i, current_channel)
                      table.setValue('Pixels_eroded', i, str(self.pix_erosion_mult))
                      table.setValue('Spatial_calibration', i, spatial_cal)

                   table.show("Tabla actualizada")

                   path_to_multiple_Tables = str(gvars['path_multiple_image_directory']) + "\\" + original_name + "_Erosion_" +str(self.pix_erosion_mult)+ "px_Channel_" + str(current_channel) + ".csv"

                   IJ.saveAs("Results", path_to_multiple_Tables)

                   # Section Save jpg with outlines
                   path_to_multiple_outline = str(gvars['path_multiple_image_directory']) + "\\" + original_name + "_Erosion_" +str(self.pix_erosion_mult)+ "px_" + "Outlines.jpg"
                   outlines_image = original_image.flatten()
                   IJ.saveAs(outlines_image, "JPG", path_to_multiple_outline)

                   IJ.run("Close")


            else:
                print "There is NOT an original image associated to this label"


            label_image.close()

         ####### Section ending ##############

       except Exception as e:
          print e
Ejemplo n.º 17
0
	        print(imp.getTitle())
	        IJ.run(colors[colorind])
	        colorind+=1
	    
	hoechstind=str(hoechstind)
	#Make RGB not including hoechst
	mergestring=[]
	ind=1
	for i in range(len(gene_names)):
	    if gene_names[i].lower()!='hoechst':
			mergestring.append('c'+str(ind)+'='+gene_names[i])
			ind+=1
	print(mergestring)
	IJ.run("Merge Channels...", " ".join(mergestring) + " create keep")
	IJ.run("Stack to RGB")
	IJ.selectWindow("Composite")
	IJ.run("Close")
	IJ.run("Images to Stack", "name=compstack use")
	
	
	myWait = ij.gui.WaitForUserDialog('Add arrows!')
	myWait.show()
	
	gd = GenericDialog("Montage downscale factor?")
	gd.addChoice("Factor:",["1.0",".25",".1"],"1.0")
	gd.showDialog()
	scale = gd.getChoices().get(0).getSelectedItem()
	
	IJ.run("Make Montage...", "columns=3 rows=2 scale="+scale+" label")
	montagename=os.path.join(inputDir1,region+"_montage.png")
	IJ.save(montagename)
Ejemplo n.º 18
0
	def __settings(self, imgName, flag) :
		"""
		Allows the user to choose several parameters for the tracking.
		
		"""
		
		#fenetre=JFrame("Import")
		#optionpane=JOptionPane("Do you want to import previous preferences ?",JOptionPane.QUESTION_MESSAGE ,JOptionPane.YES_NO_OPTION )
		#optionpane.setVisible(True)
		#dialog = optionpane.createDialog(fenetre, "Import")
     		#dialog.show()
     		#choice = optionpane.getValue()
     		#if choice==JOptionPane.YES_OPTION : self.__ImportPref()

		image=self.__dictImages[imgName]

		def outputpath(event) : 
			macrodir=IJ.getDirectory("macros")
			frame = Frame("Select the macro file")
			fd = FileDialog(frame)
			fd.setDirectory(macrodir)
			fd.show()
			macrodir = fd.getDirectory() 
			self.__macropath = fd.getFile()
			self.__text.setText(self.__macropath)
			print self.__macropath
			#self.__macropath=IJ.getDirectory("macros")
			#self.__macropath=IJ.getDirectory("")
			#self.__text.setText(self.__macropath)
		
		panel0=Panel()
		pathbutton=Button("Select macro file", actionPerformed = outputpath)
		#pathbutton.actionPerformed = outputpath
		self.__text = TextField(self.__macropath)
		panel0.add(pathbutton)
		panel0.add(self.__text)
		
		# -------- start batch mode --------- # 
		if self.__batch :
			pass
			#self.__ImportPref(flag) 
			image.hide()
		else :
			image.show()
			IJ.selectWindow(image.getID())
			gd0=NonBlockingGenericDialog("Settings")
			gd0.setFont(Font("Courrier", 1, 10))
			gd0.addMessage("---------------- PRE-PROCESSING OPTIONS -------------------")
			gd0.addCheckbox("Substract Background",self.__subback)				#box 1 subback
			gd0.addNumericField("Radius",self.__radius,0)
			gd0.addCheckbox("Run a macro for pre processing",self.__runmacro)		#box 2 runmacro
			gd0.addPanel(panel0)
			gd0.addMessage("-------------------------------------------")
			gd0.addMessage("Tracking parameters")
			gd0.addMessage("Coeffs modulate de weight of each parameter")
			gd0.addMessage("Max delta set the maximum allowed change in absolute units")
			gd0.addMessage(" ")
			gd0.addNumericField("Coeff Area   : ",self.__distparam[0],0)
			gd0.addNumericField("Max deltaArea   : ",self.__distparam[1],self.__nbdigits,6,"x times")
			gd0.addNumericField("Coeff Angle   : ",self.__distparam[2],0)
			gd0.addNumericField("Max deltaAngle   : ",self.__distparam[3],self.__nbdigits,6,"degrees")
			gd0.addNumericField("Coeff Feret   : ",self.__distparam[4],0)
			gd0.addNumericField("Max deltaFeret   : ",self.__distparam[5],self.__nbdigits,6,"x times")
			gd0.addNumericField("Coeff PositionX   : ",self.__distparam[6],0)
			gd0.addNumericField("Max deltaPositionX   : ",self.__distparam[7],self.__nbdigits,6,"pixels")
			gd0.addNumericField("Coeff PositionY   : ",self.__distparam[8],0)
			gd0.addNumericField("Max deltaPositionY   : ",self.__distparam[9],self.__nbdigits,6,"pixels")
			gd0.addMessage("-------------------------------------------")
			automethods=AutoThresholder.getMethods()
			gd0.addCheckbox("Manual Threshold",self.__manthresh)		#box 3 manthresh
			gd0.addChoice("Threshol Method : ",automethods,self.__thresMethod)
			gd0.addMessage("-------------------------------------------")
			#gd0.addCheckbox("Symmetry Around 0-180",self.__optionAngle)
			#gd0.addMessage("-------------------------------------------")
			#gd0.addCheckbox("Save cell files", self.__optionSave)
			#gd0.addMessage("-------------------------------------------")
			gd0.addCheckbox("Track new cells", self.__optionNewCells)	#box 4 newcells
			gd0.addMessage("-------------------------------------------")	
			gd0.addCheckbox("Generate time list with follow time lapse interval ?", self.__optionTimelapse)	#box 5 timelapse
			gd0.addNumericField("Estimated time lapse   : ",self.__timelapse,self.__nbdigits,6,"seconds")
			#gd0.hideCancelButton()
			gd0.showDialog()

			if gd0.wasCanceled() : return False
			#chosenstack=gd0.getNextChoice()
			#self.__img=WindowManager.getImage(chosenstack)
		
			self.__subback=gd0.getNextBoolean()				#box 1 subback
			self.__radius=gd0.getNextNumber()
			self.__runmacro=gd0.getNextBoolean()				#box 2 runmacro
			for i in range(10) : self.__distparam[i]=gd0.getNextNumber()
			#self.__distmethod=gd0.getNextChoice()
			self.__manthresh=gd0.getNextBoolean()				#box 3 manthresh
			self.__thresMethod=gd0.getNextChoice()
			#self.__optionAngle=gd0.getNextBoolean()
			#self.__optionSave=gd0.getNextBoolean()
			self.__optionNewCells=gd0.getNextBoolean()			#box 4 newcells
			self.__optionTimelapse=gd0.getNextBoolean()			#box 5 timelapse
			self.__timelapse=int(gd0.getNextNumber())
			
		# -------- start end batch mode --------- # 
		
		if self.__optionTimelapse :
			self.__dictTimeStack[imgName]=range(0,image.getImageStackSize()*self.__timelapse, self.__timelapse)

		if not self.__optionTimelapse and self.__source=="image" :
			self.__dictTimeStack[imgName]=range(0,image.getImageStackSize())
		
		#if option_import==True :
		#	temparray=
		#else : temparray=self.__calRois("image1", 1)
		#imp=self.__dictImages["image1"]
		if self.__manthresh :
			ip=image.getProcessor()
			self.__maxthr=ip.getMaxThreshold()
			self.__minthr=ip.getMinThreshold()

		temparray=self.__calRois(image, 1)
		self.__rr=RangeRois(temparray, image)		

		if (not self.__batch) : 
			image.show()
			self.__params=self.__rr.showSettingsDialog().values()
		if self.__batch : image.hide()

		return True
Ejemplo n.º 19
0
#		rgbstack = lastimage.createEmptyStack()
#		rgbstack.addSlice(cle, cp)
#	lastimage.close()
	
	del(reversions)
	del(speed)
	del(cumuld)

#imprgb=ImagePlus("rgbStack", rgbstack)
#imprgb.show()
#IJ.selectWindow("rgbStack")
#IJ.run("Hide Overlay", "")


imp.show()
IJ.selectWindow(imp.getTitle())
imp.setOverlay(overlay)
IJ.run("Show Overlay", "")


for i in range(len(cles)) :
	pos=dicPos[cles[i]]
	command = 'Overlay.drawString("'+cles[i]+'", '+str(pos[0][0])+', '+str(pos[0][1])+')'
	IJ.runMacro(command)


f2 = open(rootdir+now+"-R2-MT.txt", "w")
f3 = open(rootdir+now+"-R3-MT.txt", "w")
f4 = open(rootdir+now+"-R4-MT.txt", "w")

tab="\t"
Ejemplo n.º 20
0
#path = '/Users/cudmore/box/data/sami/Cell_1/1_5ADVMLEG1L1.oir'
path = '/Users/cudmore/box/data/sami/200108/WT_Female/Cell_8/8_5ADVMLEG1L1_ch2.tif'

# ask user for file. I do not know how to handle when users hits cancel??? Script will just fail
if path is None or not os.path.isfile(path):
    notUsedBy_oxs = 'Open a _ch2.tif file'
    path = OpenDialog(notUsedBy_oxs).getPath()
    if path is None:
        exit()

print('    user selected path:', path)
fileName = os.path.basename(path)

# load
imp = IJ.openImage(path)
imp.show()

# save channel 1
windowName = 'C1-' + fileName
IJ.selectWindow(windowName)
windowName_notSure = ij.WindowManager.getImage(windowName)

saveFilePath = os.path.splitext(
    path
)[0] + '_ch1.tif'  # this is getting garbled when we have spaces (' ') in path !!!!!!!!!
print('    saving', saveFilePath)
#windowName_notSure.close()

print('    done')
Ejemplo n.º 21
0
        nuclei_count = rm.getCount()

        if rm.getCount() != 0:
            rois = rm.getIndexes()
            rm.setSelectedIndexes(rois)
            if rm.getCount() > 1:
                rm.runCommand("Combine")
                rm.runCommand("Delete")
                rm.runCommand("Add")
            rois1 = rm.getIndexes()
            for roi in rois1:
                rm.select(imp1, roi)
                imp1.setC(1)
                IJ.run(imp1, "Draw", "slice")

        IJ.selectWindow(name1)
        IJ.run("Select None")

        print nuclei_count
        nuclei_count_sum = nuclei_count_sum + nuclei_count
        if nuclei_count < 1:
            Nuclei.changes = False
            Nuclei.close()
            imp1.changes = False
            imp1.close()
            continue

        IJ.run("Clear Results", "")

        if rm.getCount() != 0:
            rm.runCommand("Delete")
Ejemplo n.º 22
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 main_function():
    # Clean up
    IJ.run("Close All")
    # TODO: condition closing or reseting log window to the fact that it is open
    # IJ.selectWindow("Log")
    # IJ.run("Close")

    # Connect to OMERO
    gateway = omero_connect(omero_server, omero_port, user_name, user_pw)

    # Get Images IDs and names
    images_dict = get_image_properties(gateway, dataset_id, group_id)

    images = [(images_dict[id]['name'], id) for id in images_dict]

    # Sort and get image names
    images.sort(key=itemgetter(0))

    # We are assuming here a standard OMX naming pattern for raw and sim images
    sim_images = [i[0] for i in images if i[0].endswith(sim_subfix)]
    raw_images = [i.rstrip(sim_subfix) + raw_subfix for i in sim_images]
    sim_images_ids = [i for i in images if i[0] in sim_images]
    raw_images_ids = [i for i in images if i[0] in raw_images]

    if len(sim_images_ids) != len(raw_images_ids):
        print("Some of the images do not have a raw-sim correspondance")
        gateway.disconnect()
        print("Script has been aborted")
        return

    # Iterate through the list of images to analyze
    for i in range(len(sim_images_ids)):
        raw_image_title = raw_images_ids[i][0]
        raw_image_id = raw_images_ids[i][1]
        sim_image_title = sim_images_ids[i][0]
        sim_image_id = sim_images_ids[i][1]

        print("Analyzing RAW image: " + raw_image_title + " with id: " +
              str(raw_image_id))
        print("Analyzing SIM image: " + sim_image_title + " with id: " +
              str(sim_image_id))

        #Reset raw_imp and sim_imp so we can test to see if we have downloaded
        # the relevant image later
        raw_imp = None
        sim_imp = None
        log_window = None
        raw_image_measurements = {}
        sim_image_measurements = {}
        output_images = []

        if (do_channel_intensity_profiles
                and not ((raw_image_title.rsplit('.', 1)[0] + '_CIP.ome.tiff')
                         in map(lambda x: x[0], images))):

            if raw_imp is None:
                open_image_plus(omero_server, user_name, user_pw, group_id,
                                raw_image_id)
                IJ.selectWindow(raw_image_title)
                raw_imp = IJ.getImage()
            output, measurement = channel_intensity_profiles(raw_image_title)
            raw_image_measurements.update(measurement)
            log_window = True
            output_images += output

        if (do_fourier_projections
                and not ((raw_image_title.rsplit('.', 1)[0] + '_FPJ.ome.tiff')
                         in map(lambda x: x[0], images))):
            if raw_imp is None:
                open_image_plus(omero_server, user_name, user_pw, group_id,
                                raw_image_id)
                IJ.selectWindow(raw_image_title)
                raw_imp = IJ.getImage()
            output_images += fourier_projections(raw_image_title)

        if (do_motion_illumination_variation
                and not ((raw_image_title.rsplit('.', 1)[0] + '_MIV.ome.tiff')
                         in map(lambda x: x[0], images))):
            if raw_imp is None:
                open_image_plus(omero_server, user_name, user_pw, group_id,
                                raw_image_id)
                IJ.selectWindow(raw_image_title)
                raw_imp = IJ.getImage()
            output_images += motion_illumination_variation(raw_image_title)

        if ((do_modulation_contrast or do_modulation_contrast_map)
                and not ((raw_image_title.rsplit('.', 1)[0] + '_MCN.ome.tiff')
                         in map(lambda x: x[0], images))):
            if raw_imp is None:
                open_image_plus(omero_server, user_name, user_pw, group_id,
                                raw_image_id)
                IJ.selectWindow(raw_image_title)
                raw_imp = IJ.getImage()
            if sim_imp is None:
                open_image_plus(omero_server, user_name, user_pw, group_id,
                                sim_image_id)
                IJ.selectWindow(sim_image_title)
                sim_imp = IJ.getImage()
            output, measurement = modulation_contrast(
                raw_image_title, sim_image_title, do_modulation_contrast_map)
            raw_image_measurements.update(measurement)
            log_window = True
            output_images += output

        if do_intensity_histogram:
            if sim_imp is None:
                open_image_plus(omero_server, user_name, user_pw, group_id,
                                sim_image_id)
                IJ.selectWindow(sim_image_title)
                sim_imp = IJ.getImage()
            measurement = intensity_histogram(sim_image_title)
            print(measurement)
            log_window = True
            sim_image_measurements.update(measurement)

        if (do_spherical_aberration_mismatch
                and not ((sim_image_title.rsplit('.', 1)[0] + '_SAM.ome.tiff')
                         in map(lambda x: x[0], images))):
            if sim_imp is None:
                open_image_plus(omero_server, user_name, user_pw, group_id,
                                sim_image_id)
                IJ.selectWindow(sim_image_title)
                sim_imp = IJ.getImage()
            output, measurement = spherical_aberration_mismatch(
                sim_image_title)
            log_window = True
            print(measurement)
            output_images += output
            sim_image_measurements.update(measurement)

        if (do_fourier_plots
                and not ((sim_image_title.rsplit('.', 1)[0] + '_FTL.ome.tiff')
                         in map(lambda x: x[0], images))):
            if sim_imp is None:
                open_image_plus(omero_server, user_name, user_pw, group_id,
                                sim_image_id)
                IJ.selectWindow(sim_image_title)
                sim_imp = IJ.getImage()
            output_images += fourier_plots(sim_image_title)

        if raw_image_measurements:
            add_images_key_values(gateway, raw_image_measurements,
                                  raw_image_id, group_id, "SIMcheck")
        if sim_image_measurements:
            add_images_key_values(gateway, sim_image_measurements,
                                  sim_image_id, group_id, "SIMcheck")

        for output_image in output_images:

            image_title = output_image.getTitle() + ".ome.tiff"
            image_path = os.path.join(str(temp_path), image_title)
            IJ.run(output_image, 'Bio-Formats Exporter',
                   'save=' + image_path + ' export compression=Uncompressed')
            output_image.changes = False
            output_image.close()
            # Upload image to OMERO
            print('Success: ' + str(
                upload_image(gateway, image_path, omero_server, dataset_id)))

        # Clean up close widnows that have been opened
        if sim_imp or raw_imp:
            IJ.run("Close All")
        #close log window if it exists
        if log_window:
            IJ.selectWindow("Log")
            IJ.run("Close")

    print("Done")
    return gateway.disconnect()
def main():
	### debug ###############################################################
	#print (sys.version_info);
	#print(sys.path);
	#file_path = "D:\\data\\Inverse blebbing\\MAX_2dpf marcksl1b-EGFP inj_TgLifeact-mCh_movie e4_split-bleb1.tif";
	#output_root = "D:\\data\\Inverse blebbing\\output";
	#from datetime import datetime
	#timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S');
	#output_folder = os.path.join(output_root, (timestamp + ' output')); 
	#os.mkdir(output_folder); 
	########################################################################
	
	# ensure consistent preference settings
	Prefs.blackBackground = False;

	# prompt user for input parameters
	params = mbui.analysis_parameters_gui();

	# prompt user for file locations
	file_path, output_folder = mbio.file_location_chooser(params.input_image_path);
	params.setInputImagePath(file_path);
	params.setOutputPath(output_folder);

	# get image file
	import_opts, params = mbui.choose_series(file_path, params);
	imps = bf.openImagePlus(import_opts);
	imp = imps[0];

	# catch unexpected image dimensions - for now, project in Z...:
	if  imp.getNSlices() > 1:
		mbui.warning_dialog(["More than one Z plane detected.", 
							"I will do a maximum projection before proceeding", 
							"Continue?"]);
		imp = ZProjector.run(imp,"max all");

	params = mbio.get_metadata(params);
	params.setCurvatureLengthUm(round(params.curvature_length_um / params.pixel_physical_size) * params.pixel_physical_size);
	params.persistParameters();
	IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel");
	imp.show();
	if imp.getNChannels() > 1:
		imp.setPosition(params.membrane_channel_number, 1, 1);
	mbui.autoset_zoom(imp);
	IJ.run("Enhance Contrast", "saturated=0.35");

	# prompt user to select ROI
	original_imp, crop_params = mbui.crop_to_ROI(imp, params);
	if crop_params is not None:
		params.perform_spatial_crop = True;
		mbui.autoset_zoom(imp);
	else:
		params.perform_spatial_crop = False;


	# prompt user to do time cropping
	imp, start_end_tuple = mbui.time_crop(imp, params);
	params.setTimeCropStartEnd(start_end_tuple);

	repeats = 1;
	inner_outer_comparisons = None;
	if params.inner_outer_comparison:
		inner_outer_comparisons = InnerOuterComparisonData();
		repeats = 2;

	IJ.selectWindow(imp.getTitle());
	IJ.run("Enhance Contrast", "saturated=0.35");
	for r in range(0, repeats):
		calculated_objects = CalculatedObjects();
		if params.time_crop_start_end[0] is not None:
			calculated_objects.timelist = [idx * params.frame_interval for idx in range(params.time_crop_start_end[0], params.time_crop_start_end[1]+1)]
		else:
			calculated_objects.timelist = [idx * params.frame_interval for idx in range(imp.getNFrames())];
		calculated_objects, params, split_channels = mbfs.generate_edges(imp, params, calculated_objects, (r+1)/repeats);
		membrane_channel_imp = split_channels[0];
		actin_channel_imp = split_channels[1];
		segmentation_channel_imp = split_channels[2];

		calculated_objects = mbfs.calculate_outputs(params,
													calculated_objects, 
													split_channels, 
													repeat_fraction=(r+1)/repeats);
						
		# output colormapped images and kymographs 
		fig_imp_list = mbfs.generate_and_save_figures(imp, calculated_objects, params, membrane_channel_imp, segmentation_channel_imp);
		mbfs.save_csvs(calculated_objects, params);
	
		params.saveParametersToJson(os.path.join(params.output_path, "parameters used.json"));
		imp.changes = False;
		IJ.setTool("zoom");
		if params.close_on_completion or (params.inner_outer_comparison and r!=(repeats-1)):
			for fig_imp in fig_imp_list:
				fig_imp.close();
		elif params.close_on_completion and (r==(repeats-1)):
			imp.close();
	
	if params.inner_outer_comparison:
		tname = "Time, " + params.interval_unit;
		output_folder = os.path.dirname(params.output_path);
		profile = [[((inner, outer), (float(outer)/inner)) for inner, outer in zip(calculated_objects.inner_outer_data.inner_means, calculated_objects.inner_outer_data.outer_means)]];
		mbio.save_profile_as_csv(profile, 
								os.path.join(output_folder, "Intensity ratios.csv"), 
								"outer/inner", 
								xname="inner", 
								yname="outer",
								tname=tname, 
								time_list=calculated_objects.timelist);
		sd_profile = [[((inner, outer), (float(outer)/inner)) for inner, outer in zip(calculated_objects.inner_outer_data.inner_sds, calculated_objects.inner_outer_data.outer_sds)]];
		mbio.save_profile_as_csv(profile, 
								os.path.join(output_folder, "Intensity standard deviation ratios.csv"), 
								"outer sd/inner sd", 
								xname="inner sd", 
								yname="outer sd",
								tname=tname, 
								time_list=calculated_objects.timelist);
	return;
Ejemplo n.º 25
0
    imp3.setTitle("master2")
    imp3.setSlice(i)
    g = green()[i - 1]
    IJ.run("Multiply...", "value=" + str(g) + " slice")

for i in range(1, lim + 1):
    imp4.show()
    imp4 = IJ.getImage()
    imp4.setTitle("master4")
    imp4.setSlice(i)
    b = blue()[i - 1]
    IJ.run("Multiply...", "value=" + str(b) + " slice")

#fiddly bits to make an image stack and display

IJ.selectWindow("master")
IJ.run("Z Project...", "projection=[Average Intensity]")
imp2.changes = False
imp2.close()

IJ.selectWindow("master2")
IJ.run("Z Project...", "projection=[Average Intensity]")
imp3.changes = False
imp3.close()

IJ.selectWindow("master4")
IJ.run("Z Project...", "projection=[Average Intensity]")
imp4.changes = False
imp4.close()

IJ.run("Images to Stack", "name=Stack title=[] use")
Ejemplo n.º 26
0
def process(srcDir, dstDir, currentDir, fileName, keepDirectories, Channel_1, Channel_2, radius_background, sigmaSmaller, sigmaLarger, minPeakValue, min_dist):
 	IJ.run("Close All", "")

 	# Opening the image
 	IJ.log("Open image file:" + fileName)
 	#imp = IJ.openImage(os.path.join(currentDir, fileName))
	#imp = IJ.getImage()
	imp = BF.openImagePlus(os.path.join(currentDir, fileName))
	imp = imp[0]

	# getDimensions(width, height, channels, slices, frames)

	IJ.log("Computing Max Intensity Projection")

	if imp.getDimensions()[3] > 1:
		imp_max = ZProjector.run(imp,"max")
	else:
		imp_max = imp

	ip1, ip2 = extract_channel(imp_max, Channel_1, Channel_2)

	IJ.log("Substract background")

	imp1, imp2 = back_substraction(ip1, ip2, radius_background)

	IJ.log("Finding Peaks")

	ip1_1, ip2_1, peaks_1, peaks_2 = find_peaks(imp1, imp2, sigmaSmaller, sigmaLarger, minPeakValue)

	# Create a PointRoi from the DoG peaks, for visualization
	roi_1 = PointRoi(0, 0)
	roi_2 = PointRoi(0, 0)
	roi_3 = PointRoi(0, 0)
	roi_4 = PointRoi(0, 0)

	# A temporary array of integers, one per dimension the image has
	p_1 = zeros(ip1_1.numDimensions(), 'i')
	p_2 = zeros(ip2_1.numDimensions(), 'i')


	# Load every peak as a point in the PointRoi
	for peak in peaks_1:
	  # Read peak coordinates into an array of integers
	  peak.localize(p_1)
	  roi_1.addPoint(imp1, p_1[0], p_1[1])

	for peak in peaks_2:
	  # Read peak coordinates into an array of integers
	  peak.localize(p_2)
	  roi_2.addPoint(imp2, p_2[0], p_2[1])

	# Chose minimum distance in pixel
	#min_dist = 20

	for peak_1 in peaks_1:
		peak_1.localize(p_1)
		for peak_2 in peaks_2:
			peak_2.localize(p_2)
			d1 = distance(p_1, p_2)
			if  d1 < min_dist:
				roi_3.addPoint(imp1, p_2[0], p_2[1])
				break

	for peak_2 in peaks_2:
		peak_2.localize(p_2)
		for peak_1 in peaks_1:
			peak_1.localize(p_1)
			d2 = distance(p_2, p_1)
			if  d2 < min_dist:
				roi_4.addPoint(imp1, p_2[0], p_2[1])
				break

	cal = imp.getCalibration()
	min_distance = str(round((cal.pixelWidth * min_dist),1))

	table = ResultsTable()
	table.incrementCounter()
	table.addValue("Numbers of Neuron Markers", roi_1.getCount(0))
	table.addValue("Numbers of Glioma Markers", roi_2.getCount(0))
	table.addValue("Numbers of Glioma within %s um of Neurons" %(min_distance), roi_3.getCount(0))
	table.addValue("Numbers of Neurons within %s um of Glioma" %(min_distance), roi_4.getCount(0))
	#table.show("Results Analysis")
	saveDir = currentDir.replace(srcDir, dstDir) if keepDirectories else dstDir
	if not os.path.exists(saveDir):
		os.makedirs(saveDir)
	IJ.log("Saving to" + saveDir)
	table.save(os.path.join(saveDir, fileName + ".csv"))
	IJ.selectWindow("Log")
	IJ.saveAs("Text", os.path.join(saveDir, fileName + ".csv"));
Ejemplo n.º 27
0
    match_roi = [];
    match_count = 1;
    m = re.search('(Batch\d+_\d+_XY\d{2}).*.tif', i);
    match = m.group(1);
        
    for j in roi_list:
        if re.search(match, j):
            match_roi.append(j);

    if not mem_conserve:
    	if len(match_roi) >= 1:
        	image_path = image_directory + '/' + i;
        	imp = IJ.openImage(image_path);
        	imp.show();
        	for k in match_roi:
            		IJ.selectWindow(i);
            		cur_match_roi = k;
            		m = re.search('(Batch\d+_\d+_XY\d{2}_cropped_singlet\d+).roi', cur_match_roi);
            		crop_name = m.group(1);
            		roi_path = roi_directory + '/' + cur_match_roi;
            		IJ.open(roi_path);
            		temp_str = 'title=' + crop_name + '.tif duplicate';
            		IJ.run('Duplicate...', temp_str);
            		imp_cropped = IJ.getImage();
            		save_name = crop_dir + '/' + crop_name + '.tif';
            		print(save_name);
            		IJ.saveAsTiff(imp_cropped, save_name);
        	IJ.run('Close All');
    		gc.collect();
    else:
	if len(match_roi) >= 1:
Ejemplo n.º 28
0
			#----------------
			filename_only = os.path.splitext(filename)[0];
			out_filename = filename_only + '_Roi' + str(idx+1) + '_Tracks.xml';		
			outFile = File(OutFolfer, out_filename);
				
			#out_filename_stats = filename_only + '_Roi' + str(idx+1) + '_Track_Statistics.csv';
			out_filename_spots = filename_only + '_Roi' + str(idx+1) + '_Spots_Statistics.csv';
			#outFile_stats = File(OutFolfer, out_filename_stats);
			#outFile_spots = File(OutFolfer, out_filename_spots);
			outFile_spots = OutFolfer + out_filename_spots;	
			
			ExportTracksToXML.export(model,settings,outFile);

			if Export_spot_statistics:
				ExportStatsToIJAction(selectionModel).execute(trackmate);
				IJ.selectWindow("Track statistics");
				IJ.run("Close");
				IJ.selectWindow("Links in tracks statistics");
				IJ.run("Close");
				IJ.selectWindow("Spots in tracks statistics");		
				IJ.saveAs("Results",outFile_spots);
				IJ.run("Close");
			
		rm.runCommand("Select All");
		rm.runCommand("delete");
	
	 	if Close_images:
	 		imp.close();
	    
	   	ROI_idx = ROI_idx + 1;
	    
def closeEverything():
  IJ.run("Close All", "")
  IJ.selectWindow("Results")
  IJ.run("Close")
Ejemplo n.º 30
0
def cellSegmentation(srcDir, dstDir, currentDir, filename, keepDirectories):
  print "Processing:"  
  # Opening the image
  print "Open image file", filename
  imp = IJ.openImage(os.path.join(currentDir, dstDir))
  # Put your processing commands here!
  localinput=srcDir.replace("/", "\\")
  saveDir = localinput.replace(srcDir, dstDir)
  string="."
  dotIndex=filename.find(string)
  localfile= filename[0:dotIndex]
  print(localfile)
  IJ.run("New... ", "name="+f+" type=Table")
  print(f,"\\Headings:Cell\tarea\tCirc\tAR\tRoundness\tMaximum")
  IJ.run("Bio-Formats", "open=[" + localinput + os.path.sep + filename +"] autoscale color_mode=Default rois_import=[ROI manager] view=Hyperstack stack_order=XYCZT")
  IJ.open()
  idd= WM.getIDList();
  imageID= idd[0];
  IJ.run("Clear Results")
  WM.getImage(imageID)
  IJ.run("Duplicate...", "duplicate channels="+str(x)+"") #Nucleus channel #took away x
  IJ.run("Z Project...", "projection=[Standard Deviation]");#picture for frame detection
  IJ.run("8-bit");
  IJ.run("Duplicate...", "title=IMAGE");#frame
  IJ.run("Duplicate...", "title=SUBTRACT");#Background subtraction mask (for frame and watershed)
  imp=IJ.getImage()
  pixelWidth=imp.getWidth()
  pixelWidth=pixelWidth/1647.89
  pixelHeight= imp.getHeight()
#create subtraction mask, applying constraining maximum (step I)
  IJ.selectWindow("SUBTRACT")
  nResults=imp.getStatistics()
  row = nResults
  rt_exist = WM.getWindow("Results")
  if rt_exist==None:
    rt= ResultsTable()
  else:
    rt = rt_exist.getTextPanel().getOrCreateResultsTable()
  rt.setValue("Max ", 0, row.max) #text file
  rt.show("Results")
  u=math.floor(row.mean*3)
  IJ.run("Max...","value="+str(u)) #constraining maximum of 3-fold mean to reduce effect of extreme values during subtraction
		#gaussian blurring (step II)
  IJ.run("Gaussian Blur...", "sigma=100 scaled") #blurring for subtraction mask

  IJ.selectWindow("IMAGE")
  pxrollrad = cellradius/pixelWidth; #rolling ball radius in pixels needed (= predefined cell radius[µm]/pixelsize[µm/px])
  IJ.run("Subtract Background...", "rolling="+str(pxrollrad)+"")
  IJ.run("Gaussian Blur...", "sigma=2 scaled") #reduces punctate character of grayscale image '
  IM=IJ.selectWindow("IMAGE")
  SUB=IJ.selectWindow("SUBTRACT")
  ic().run("SUBTRACT", IM, SUB) #just subtracts two images
  IJ.selectWindow("IMAGE") #see how to call
  IJ.run("Duplicate...", "title=AND")#watershed
  IJ.run("Duplicate...", "title=CHECK")#for checking if maxima exist within selection later
  
#Apply threshold to get binary image of cell borders (step IV)
  IJ.selectWindow("IMAGE")
  imp = IJ.getImage()  # the current image
  imp.getProcessor().setThreshold(1, 255, ImageProcessor.NO_LUT_UPDATE)
  IJ.run("Subtract Background...","...")
  IJ.run("Convert to Mask", "method=Default background=Dark only black")
  IJ.run("Fill Holes")

#Create watershed line image (step V)
  IJ.selectWindow("AND")
  IJ.run("Gaussian Blur...", "sigma=2 scaled")
  imp=IJ.getImage()
  pixelWidth=imp.getWidth()
  pixelWidth=pixelWidth/1647.89
  pixelHeight= imp.getHeight()
  # Saving the image
  nResults=imp.getStatistics()
  row = nResults
  rt.setValue("Max ", 1, row.max) #text file
  nBins = 256
  Hist = HistogramWindow("Histogram",imp,nBins)
  Table = Hist.getResultsTable()
  Counts = Table.getColumn(1)
  #mean gray value of pixels belonging to cells needed (i.e. mean of ONLY non-zero pixel)
  Sum = 0 #all counts
  CV = 0 #weighed counts (= counts * intensity)
  for i in range(0, len(Counts)): #starting with 1 instead of 0. -> 0 intensity values are not considered.
    Sum += Counts[i]
    CV += Counts[i]*i
  m = (CV/Sum)
  m=math.floor(m)
  l = math.floor(2*m) #Maxima need to be at least twice the intensity of cellular mean intensity
  IJ.run("Find Maxima...", "noise="+str(l)+" output=[Segmented Particles] exclude") #watershedding

#Combine watershed lines and cell frame (step VI) 
  IJ.selectWindow("IMAGE")
  imp=IJ.getImage()
  imp.getProcessor().setThreshold(1, 255, ImageProcessor.NO_LUT_UPDATE)
  IJ.run(imp, "Watershed", "") #useful
  imp = IJ.getImage()
  ip = imp.getProcessor()
  segip = MaximumFinder().findMaxima( ip, 1, ImageProcessor.NO_THRESHOLD, MaximumFinder.SEGMENTED , False, False)
  segip.invert()
  segimp = ImagePlus("seg", segip)
  segimp.show()
  mergeimp = RGBStackMerge.mergeChannels(array([segimp, None, None, imp, None, None, None], ImagePlus), True)
  mergeimp.show()
  pa_exist = WM.getWindow("Results for PA")   
  if pa_exist==None:
    pa_rt= ResultsTable()   
  else:
    pa_rt = pa_exist.getTextPanel().getOrCreateResultsTable()     
  ParticleAnalyzer.setResultsTable(pa_rt)    
  IJ.run("Set Measurements...", "area mean perimeter shape decimal=3")  
  IJ.run("Analyze Particles...", "size=" + str(cellradius) + "-Infinity circularity=0.1-1.00 add"); #Cell bodies detected 
  pa_rt.show("Results for PA ")
  save_all(srcDir, dstDir, filename, localfile, keepDirectories, imageID)
def reduceZ():
    imp = IJ.getImage()  #get the standardtack
    title_1 = imp.getTitle()
    title = title_1.split(' - ')[1]
    print(title)
    dimentions = imp.getDimensions()
    numZ, numChannels, numframes = dimentions[3], dimentions[2], dimentions[4]
    print(numChannels)

    IJ.run(imp, "Set Measurements...", "kurtosis redirect=None decimal=3")

    kurtTotal = []
    for time in range(numframes):
        print(time)
        time = time + 1
        imp.setPosition(1, 1, time)
        kurt = []
        for z in range(numZ):
            z = z + 1
            imp.setPosition(1, z, time)
            imp.setRoi(70, 40, 437, 459)
            IJ.setAutoThreshold(imp, "MaxEntropy dark")
            IJ.run(imp, "Measure", "")
            IJ.resetThreshold(imp)
            rt = ResultsTable()
            t = rt.getResultsTable()
            kurt.append(t.getValueAsDouble(23, z - 1))  # 23 = kurtosis
        kurtTotal.append(kurt.index(max(kurt)) + 1)
        IJ.run(imp, "Clear Results", "")
    print(kurtTotal)

    IJ.run(imp, "Select All", "")

    imp2 = IJ.createImage("GFP", "16-bit black", dimentions[0], dimentions[1],
                          numframes)
    imp2 = HyperStackConverter.toHyperStack(imp2, 1, 1, numframes, "Color")
    print(' ------------')
    print(numframes)
    channel = 1
    i = 0
    for time in range(numframes):
        time = time + 1
        imp.setPosition(channel, kurtTotal[i], time)
        imp.copy()
        imp2.setPosition(channel, 1, time)
        imp2.paste()
        print(time)
        i = i + 1
    IJ.run(imp2, "Delete Slice", "delete=slice")
    imp2.show()

    imp4 = IJ.createImage("RFP", "16-bit black", dimentions[0], dimentions[1],
                          numframes)
    imp4 = HyperStackConverter.toHyperStack(imp4, 1, 1, numframes, "Color")
    print(' ------------')
    channel = 2
    i = 0
    for time in range(numframes):
        time = time + 1
        imp.setPosition(channel, kurtTotal[i], time)
        imp.copy()
        print(imp.title)
        imp4.setPosition(channel, 1, time)
        imp4.paste()
        i = i + 1
    IJ.run(imp4, "Delete Slice", "delete=slice")
    imp4.show()

    IJ.selectWindow(title_1)
    IJ.run("Close")

    imp5 = ImagePlus()
    IJ.run(imp5, "Merge Channels...", "c1=RFP c2=GFP create")
    imp5 = IJ.getImage()
    IJ.run(
        imp5, "Bio-Formats Exporter",
        "save=/home/rickettsia/Desktop/data/Clamydial_Image_Analysis/EMS_BMEC_20X_01192020/Zreduced/"
        + title + ".ome.tif export compression=LZW")
    IJ.selectWindow('Merged')
    IJ.run("Close")
Ejemplo n.º 32
0
from ij import IJ
from ij.plugin.frame import RoiManager
from ij.gui import Roi

# Get the active image, its title, and the directory where it lies
imp = IJ.getImage()
imp_title = imp.getTitle()
path = IJ.getDirectory("image")
IJ.log("Active image source: {}{}".format(path, imp_title))

# Set measurements to redirect to the active image
IJ.run(
    "Set Measurements...",
    "area mean standard min center perimeter bounding fit feret's integrated median stack display redirect={}"
    .format(imp_title))

# Instantiate RoiManager as rm, select all rois and measure them
roim = RoiManager.getInstance()
roim.runCommand("Select All")
roim.runCommand("Measure")

# Save the measurements just made using the name of the active image
measurements_filename = imp_title[:-4]
IJ.saveAs("Results", "{}{}_background.csv".format(path, measurements_filename))
IJ.selectWindow("Results")
IJ.run("Close")
IJ.log("Measurements saved at {}{}.csv".format(path, measurements_filename))
Ejemplo n.º 33
0
def batch_open_images(path, file_type=None, name_filter=None, horizontal=False):
    '''Open all files in the given folder.
    :param path: The path from were to open the images. String and java.io.File are allowed.
    :param file_type: Only accept files with the given extension (default: None).
    :param name_filter: Only accept files that contain the given string (default: None).
    '''
    # Converting a File object to a string.
    if isinstance(path, File):
        path = path.getAbsolutePath()

    def check_type(string):
        '''This function is used to check the file type.
        It is possible to use a single string or a list/tuple of strings as filter.
        This function can access the variables of the surrounding function.
        :param string: The filename to perform the check on.
        '''
        if file_type:
            # The first branch is used if file_type is a list or a tuple.
            if isinstance(file_type, (list, tuple)):
                for file_type_ in file_type:
                    if string.endswith(file_type_):
                        # Exit the function with True.
                        return True
                    else:
                        # Next iteration of the for loop.
                        continue
            # The second branch is used if file_type is a string.
            elif isinstance(file_type, string):
                if string.endswith(file_type):
                    return True
                else:
                    return False
            return False
        # Accept all files if file_type is None.
        else:
            return True

    def check_filter(string):
        '''This function is used to check for a given filter.
        It is possible to use a single string or a list/tuple of strings as filter.
        This function can access the variables of the surrounding function.
        :param string: The filename to perform the filtering on.
        '''
        if name_filter:
            # The first branch is used if name_filter is a list or a tuple.
            if isinstance(name_filter, (list, tuple)):
                for name_filter_ in name_filter:
                    if name_filter_ in string:
                        # Exit the function with True.
                        return True
                    else:
                        # Next iteration of the for loop.
                        continue
            # The second branch is used if name_filter is a string.
            elif isinstance(name_filter, string):
                if name_filter in string:
                    return True
                else:
                    return False
            return False
        else:
        # Accept all files if name_filter is None.
            return True

    # We collect all files to open in a list.
    path_to_images = []
    # Replacing some abbreviations (e.g. $HOME on Linux).
    path = os.path.expanduser(path)
    path = os.path.expandvars(path)

    # os.walk() is iterable.
    # Each iteration of the for loop processes a different directory.
    # the first return value represents the current directory.
    # The second return value is a list of included directories.
    # The third return value is a list of included files.
    for directory, dir_names, file_names in os.walk(path):
        # We are only interested in files.
        file_names = [f for f in file_names if not f[0] == '.']
        for file_name in file_names:
            # The list contains only the file names.
            # The full path needs to be reconstructed.
            full_path = os.path.join(directory, file_name)
            # Both checks are performed to filter the files.
            if check_type(file_name):
                if check_filter(file_name):
                    # Add the file to the list of images to open.
                    path_to_images.append(full_path)
    # Create the list that will be returned by this function.
    images = []
    for img_path in path_to_images:
        # IJ.openImage() returns an ImagePlus object or None.
        i = IJ.openImage(img_path)
        duty_cycle(img_path, horizontal)
        IJ.selectWindow("Log")
        IJ.saveAs("Text", csvpath + "Duty_Log.txt")
        IJ.run("Close All", "")
        # An object equals True and None equals False.
        if i:
            images.append(i)
    return images
Ejemplo n.º 34
0
                impBin1.changes = False
                impBin1.close()
                continue

            #Get nuclei ROIs
            ip2 = nucleistack.getProcessor(zslice)
            ip2.resetMinAndMax()
            ip2.blurGaussian(parameters['nucsigma'])
            bp2 = ip2.convertToByte(1)
            impBin2 = ImagePlus('BinarizedNuclei', bp2)
            impBin2.show()
            rmi.select(impBin2, rmi.getCount() - 1)
            IJ.setBackgroundColor(0, 0, 0)
            IJ.run('Clear Outside')
            impBin2.deleteRoi()
            IJ.selectWindow('BinarizedNuclei')
            IJ.run('Auto Threshold', 'method=' + parameters['nucmethod'] +
                   ' ignore_black white')  #threshold the template region
            IJ.run('Watershed')
            #Remove template ROI
            rmi.reset()
            impBin2.killRoi()
            #Add nuclei to ROIs
            IJ.run(
                'Analyze Particles...',
                'size=' + parameters['nucsize'] + ' circularity=' +
                parameters['nuccircularity'] + ' exclude add')
            rois.append([zslice, rmi.getRoisAsArray()])
            print 'Added ' + str(len(rmi.getRoisAsArray())) + ' ROIs'
            #Close images
            impBin1.changes = False
Ejemplo n.º 35
0
def process(srcDir, dstDir, currentDir, filename, keepDirectories):
    print "Processing:"

    # Opening the image
    print "Open image file", filename
    IJ.run(
        "Bio-Formats Importer",
        str("open=" + os.path.join(srcDir, filename) +
            " color_mode=Colorized open_files open_all_series display_metadata rois_import=[ROI manager] split_channels view=Hyperstack stack_order=XYCZT use_virtual_stack"
            ))

    # Exporting the Metadata to .csv
    IJ.selectWindow(str("Original Metadata - " + filename))
    IJ.saveAs(
        "Text",
        str(
            os.path.join(dstDir,
                         str("Original Metadata - " + filename[0:-4] +
                             ".csv"))))

    # Determines Number of Series and their names from Metadata
    md_file = open(
        str(
            os.path.join(dstDir,
                         str("Original Metadata - " + filename[0:-4] +
                             ".csv"))))
    md_reader = csv.reader(md_file)
    md_array = list(md_reader)
    find_series = re.compile(r'Series', re.IGNORECASE)
    index = []
    for i in range(len(md_array)):
        for x in range(0, 2):
            strv = str(md_array[i][x])
            please = find_series.findall(strv)
            if please != []:
                index.append(str(md_array[i][x + 1]))

    # Primary Processing Loop

    channels = ['C=0', 'C=1', 'C=2', 'C=3']
    for i in range(len(index)):
        print('loopedy loop')
        # Dealing with Channel 0
        IJ.selectWindow(str(filename + ' - ' + index[i] + ' - ' + channels[0]))
        IJ.run("Z Project...", "projection=[Max Intensity]")
        IJ.saveAs(
            "Tiff",
            str(
                os.path.join(
                    dstDir,
                    str("Max_" + filename[0:-4] + ' - ' + index[i] + ".tif"))))
        imp = IJ.getImage()
        imp.close()
        IJ.selectWindow(str(filename + ' - ' + index[i] + ' - ' + channels[0]))
        imp = IJ.getImage()
        imp.close()
        # Dealing with excess channels
        IJ.selectWindow(str(filename + ' - ' + index[i] + ' - ' + channels[1]))
        imp = IJ.getImage()
        imp.close()
        IJ.selectWindow(str(filename + ' - ' + index[i] + ' - ' + channels[2]))
        imp = IJ.getImage()
        imp.close()
        IJ.selectWindow(str(filename + ' - ' + index[i] + ' - ' + channels[3]))
        imp = IJ.getImage()
        imp.close()
Ejemplo n.º 36
0
def selectBest(imp):
    imp.getWindow().setLocation(0, 0)
    file_name = imp.getTitle()
    file_path = IJ.getDirectory('image')
    printLog("filepath is " + file_path, 1)

    [SI_version, nFrame, zStepSize,
     nStacks] = zyGetProperty(imp, "SI_version,nFrame,zStepSize,nStacks"
                              )  #need correct nSlices? do not delete any
    nSlices = imp.getNSlices() / nFrame  #otherwise, calculate by fiji function
    msgStr = "The image has " + str(nFrame) + " frames from " + str(
        nStacks) + " stacks, was collected by ScanImage version " + str(
            SI_version)
    printLog(msgStr, 0)
    if nFrame == 1:
        printLog("User need to import a file with multi-frames", 0)
    else:
        #duplicate one for resorting
        IJ.run(imp, "Duplicate...", "title=resortStack duplicate range=1-%d" %
               imp.getNSlices())  #bad fiji set this getNSlice() as all slice
        resort_stack = IJ.getImage()
        resort_stack.getWindow().setLocation(0, 0)
        IJ.run(resort_stack, "Label...",
               "format=0 starting=1 interval=1 x=5 y=20 font=18")

        #number pickup for every numRep
        IJ.selectWindow(file_name)
        #(width, height, nChannels, nSlices, nFrames) = imp.getDimensions(), bad fiji alway get wrong
        numRep = int(nFrame)
        m = int(nSlices)  #real slice number when correcting the nFrames

        sPick = []
        printLog("-Current tif file:" + file_name, 1)
        printLog("-nSlice=" + str(m) + ", nFrame=" + str(numRep), 2)
        printLog("-start picking the best repeat.", 1)
        for i in range(0, m):
            j = i * numRep + 1  #Z-step number
            #make montage to check all repeats at the same time for pickup
            IJ.run(
                imp, "Make Montage...",
                "columns=" + str(numRep / nStacks) + " rows=" + str(nStacks) +
                " scale=1 first=" + str(j) + " last=" + str(j + numRep - 1) +
                " increment=1 border=1 font=12 label")
            m1_imp = IJ.getImage()
            IJ.run(m1_imp, "8-bit", "")
            m1_imp.getWindow().setLocation(530, 0)
            IJ.run(m1_imp, "Set... ", "zoom=92 x=0 y=0")
            m1_title = m1_imp.getTitle()
            #merge the previous one if i>0
            if i == 0:
                prePick = 1  #use first slice as mask
                IJ.run(resort_stack, "Duplicate...",
                       "title=Max_z duplicate range=1-1")
                zMax = IJ.getImage()
                zMax_win = zMax.getWindow().setLocation(0, 580)
            else:
                prePick = sPick[i - 1]  #use previous selected slice as mask

            #duplicate numRep times of previous, concatenate, make montage, for merging channel as red with m1_imp
            m2_imp = mkMask(imp, prePick, numRep, nStacks)

            #merge the mask, and make new m1_imp as a 2-slice stack: Green (original) with merged
            m1_imp = zyMergeView(m1_imp, m2_imp)

            #pickup the best slice with slice number
            pickN = pickNum(numRep, nStacks)
            if not pickN:
                break
            else:
                pickN = pickN + j - 1

            #do the moveSlice on resort_stack: move to the initial of pick: j
            resort_stack = moveSlice(resort_stack, pickN, j)

            #preview Z projection in a copy of resort_stack
            zMax.close()  #clear previous Z projection
            zMax = preview_Z(resort_stack, numRep,
                             i + 1)  #show the new preview based on new pick

            #store the lucky slice number for making the substack in the future
            sPick.append(int(pickN))
            #mmp = IJ.getImage()
            m1_imp.close()

        if len(sPick) == m:
            #means you have pick all slices required, but not cancel during process (break all out)
            IJ.selectWindow(file_name)
            outList = ",".join(
                str(e)
                for e in sPick)  #better to make a str: outList="slices=1,2,3"
            printLog("-Slices picked by user:"******"Make Substack...",
                   "slices=%s" % (outList))  #all need to be str
            sr_imp = IJ.getImage()
            sr_imp.setTitle('P_' + file_name)
            #imp.changes = 0
            #imp.close()
            #zMax.close()
            #need to do: put a header for sr_imp here

            msgStr = "pixel_width=0.102857 pixel_height=0.102857 voxel_depth=" + str(
                zStepSize)
            printLog(
                "-Set the property of picked stack " + sr_imp.getTitle() +
                " to:" + msgStr, 1)
            IJ.run(sr_imp, "Properties...", msgStr)

            pickName = sr_imp.getTitle()
            destFolder_SR = os.path.join(file_path, 'Single_rep')
            #do multireg alignment
            doAlign(sr_imp, destFolder_SR)
            zyAddProperty(sr_imp)
            saveStack(destFolder_SR, pickName, sr_imp)

            destFolder_RS = os.path.join(file_path, 'reSort')
            #add Info
            zyAddProperty(resort_stack)
            saveStack(destFolder_RS, file_name, resort_stack)
        else:
            m1_imp.close()
            resort_stack.changes = 0
        imp.changes = 0
        imp.close()
        zMax.close()
        resort_stack.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
Ejemplo n.º 38
0
def process(subFolder, outputDirectory, filename):

    imp = IJ.openImage(inputDirectory + subFolder + '/' + filename)
    imp.show()
    IJ.run(
        imp, "Properties...",
        "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001"
    )
    ic = ImageConverter(imp)
    dup = imp.duplicate()
    dup_title = dup.getTitle()
    ic.convertToGray8()
    imp.updateAndDraw()
    IJ.run("Threshold...")

    IJ.setThreshold(218, 245)

    IJ.run(imp, "Convert to Mask", "")

    rm = RoiManager()
    imp.getProcessor().setThreshold(0, 0, ImageProcessor.NO_LUT_UPDATE)
    boundroi = ThresholdToSelection.run(imp)
    rm.addRoi(boundroi)

    imp.changes = False
    imp.close()

    images = [None] * 5
    intensities = [None] * 5
    blobsarea = [None] * 5
    blobsnuclei = [None] * 5
    cells = [None] * 5
    bigareas = [None] * 5

    IJ.run(dup, "Colour Deconvolution", "vectors=[H DAB]")

    images[0] = getImage(dup_title + "-(Colour_1)")
    images[1] = getImage(dup_title + "-(Colour_2)")
    images[2] = getImage(dup_title + "-(Colour_3)")

    images[2].close()

    for chan in channels:
        v, x = chan
        imp = images[x]
        imp.show()
        for roi in rm.getRoiManager().getRoisAsArray():
            imp.setRoi(roi)
            stats = imp.getStatistics(Measurements.MEAN | Measurements.AREA)
            intensities[x] = stats.mean
            bigareas[x] = stats.area

        rm.runCommand(imp, "Show None")

    rm.close()
    # Opens the ch00 image and sets default properties

    imp = images[0].duplicate()
    IJ.run(
        imp, "Properties...",
        "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001"
    )

    # Sets the threshold and watersheds. for more details on image processing, see https://imagej.nih.gov/ij/developer/api/ij/process/ImageProcessor.html

    imp.show()
    setTempCurrentImage(imp)
    ic = ImageConverter(imp)
    imp.updateAndDraw()
    IJ.run(imp, "Gaussian Blur...", "sigma=" + str(blur))
    imp.updateAndDraw()

    imp.show()
    IJ.run("Threshold...")
    IJ.setThreshold(30, lowerBounds[0])
    if displayImages:
        imp.show()
        WaitForUserDialog(
            "Title", "Adjust threshold for nuclei. Current region is: " +
            region).show()
    IJ.run(imp, "Convert to Mask", "")

    # Counts and measures the area of particles and adds them to a table called areas. Also adds them to the ROI manager

    table = ResultsTable()
    roim = RoiManager()
    pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER, Measurements.AREA,
                          table, 5, 9999999999999999, 0.05, 1.0)

    pa.setHideOutputImage(True)
    imp = IJ.getImage()
    # imp.getProcessor().invert()
    pa.analyze(imp)

    imp.changes = False
    imp.close()

    areas = table.getColumn(0)

    # This loop goes through the remaining channels for the other markers, by replacing the ch00 at the end with its corresponding channel
    # It will save all the area fractions into a 2d array called areaFractionsArray

    areaFractionsArray = [None] * 5
    maxThresholds = []
    for chan in channels:
        v, x = chan
        # Opens each image and thresholds

        imp = images[x]
        IJ.run(
            imp, "Properties...",
            "channels=1 slices=1 frames=1 unit=um pixel_width=0.8777017 pixel_height=0.8777017 voxel_depth=25400.0508001"
        )

        imp.show()

        setTempCurrentImage(imp)

        ic = ImageConverter(imp)
        ic.convertToGray8()
        imp.updateAndDraw()

        rm.runCommand(imp, "Show None")
        rm.runCommand(imp, "Show All")
        rm.runCommand(imp, "Show None")

        imp.show()
        IJ.selectWindow(imp.getTitle())

        IJ.run("Threshold...")
        IJ.setThreshold(20, lowerBounds[x])

        if displayImages:

            WaitForUserDialog(
                "Title", "Adjust threshold for " + v +
                ". Current region is: " + region).show()
            ip = imp.getProcessor()
            maxThresholds.append(ip.getMaxThreshold())

        IJ.run(imp, "Convert to Mask", "")

        # Measures the area fraction of the new image for each ROI from the ROI manager.
        areaFractions = []
        for roi in roim.getRoiManager().getRoisAsArray():
            imp.setRoi(roi)
            stats = imp.getStatistics(Measurements.AREA_FRACTION)
            areaFractions.append(stats.areaFraction)

        # Saves the results in areaFractionArray

        areaFractionsArray[x] = areaFractions

    roim.close()

    for chan in channels:
        v, x = chan

        imp = images[x]
        imp.deleteRoi()
        imp.updateAndDraw()
        setTempCurrentImage(imp)
        roim = RoiManager()
        pa = ParticleAnalyzer(ParticleAnalyzer.ADD_TO_MANAGER,
                              Measurements.AREA, table, 15, 9999999999999999,
                              0.2, 1.0)
        pa.analyze(imp)

        blobs = []
        cell = []
        for roi in roim.getRoiManager().getRoisAsArray():
            imp.setRoi(roi)
            stats = imp.getStatistics(Measurements.AREA)
            blobs.append(stats.area)
            if stats.area > tooSmallThresholdDAB and stats.area < tooBigThresholdDAB:
                cell.append(stats.area)

        blobsarea[x] = sum(blobs)
        blobsnuclei[x] = len(blobs)

        cells[x] = len(cell)
        imp.changes = False

        imp.close()
        roim.reset()
        roim.close()

    # Creates the summary dictionary which will correspond to a single row in the output csv, with each key being a column

    summary = {}

    summary['Image'] = filename
    summary['Directory'] = subFolder

    # Adds usual columns

    summary['size-average'] = 0
    summary['#nuclei'] = 0
    summary['all-negative'] = 0

    summary['too-big-(>' + str(tooBigThreshold) + ')'] = 0
    summary['too-small-(<' + str(tooSmallThreshold) + ')'] = 0

    # Creates the fieldnames variable needed to create the csv file at the end.

    fieldnames = [
        'Directory', 'Image', 'size-average',
        'too-big-(>' + str(tooBigThreshold) + ')',
        'too-small-(<' + str(tooSmallThreshold) + ')', '#nuclei',
        'all-negative'
    ]

    for row in info:
        if row['Animal ID'] == filename.replace('s', '-').replace(
                'p', '-').split('-')[0]:
            for key, value in row.items():
                fieldnames.insert(0, key)
                summary[key] = value

    # Adds the columns for each individual marker (ignoring Dapi since it was used to count nuclei)

    summary["tissue-area"] = bigareas[0]
    fieldnames.append("tissue-area")

    for chan in channels:
        v, x = chan
        summary[v + "-HEMO-cells"] = 0
        fieldnames.append(v + "-HEMO-cells")

        summary[v + "-intensity"] = intensities[x]
        fieldnames.append(v + "-intensity")

        summary[v + "-area"] = blobsarea[x]
        fieldnames.append(v + "-area")

        summary[v + "-area/tissue-area"] = blobsarea[x] / bigareas[0]
        fieldnames.append(v + "-area/tissue-area")

        summary[v + "-particles"] = blobsnuclei[x]
        fieldnames.append(v + "-particles")

        summary[v + "-cells"] = cells[x]
        fieldnames.append(v + "-cells")

        summary[v + "-particles/tissue-area"] = blobsnuclei[x] / bigareas[0]
        fieldnames.append(v + "-particles/tissue-area")

        fieldnames.append(v + "-HEMO-Cells/tissue-area")

    # Adds the column for colocalization between first and second marker

    if len(channels) > 2:
        summary[channels[1][0] + '-' + channels[2][0] + '-positive'] = 0
        fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-positive')

    # Adds the columns for colocalization between all three markers

    if len(channels) > 3:
        summary[channels[1][0] + '-' + channels[3][0] + '-positive'] = 0
        summary[channels[2][0] + '-' + channels[3][0] + '-positive'] = 0
        summary[channels[1][0] + '-' + channels[2][0] + '-' + channels[3][0] +
                '-positive'] = 0

        fieldnames.append(channels[1][0] + '-' + channels[3][0] + '-positive')
        fieldnames.append(channels[2][0] + '-' + channels[3][0] + '-positive')
        fieldnames.append(channels[1][0] + '-' + channels[2][0] + '-' +
                          channels[3][0] + '-positive')

    # Loops through each particle and adds it to each field that it is True for.

    areaCounter = 0
    for z, area in enumerate(areas):

        if area > tooBigThreshold:
            summary['too-big-(>' + str(tooBigThreshold) + ')'] += 1
        elif area < tooSmallThreshold:
            summary['too-small-(<' + str(tooSmallThreshold) + ')'] += 1
        else:

            summary['#nuclei'] += 1
            areaCounter += area

            temp = 0
            for chan in channels:
                v, x = chan
                if areaFractionsArray[x][z] > areaFractionThreshold[0]:
                    summary[chan[0] + '-HEMO-cells'] += 1
                    if x != 0:
                        temp += 1

            if temp == 0:
                summary['all-negative'] += 1

            if len(channels) > 2:
                if areaFractionsArray[1][z] > areaFractionThreshold[1]:
                    if areaFractionsArray[2][z] > areaFractionThreshold[2]:
                        summary[channels[1][0] + '-' + channels[2][0] +
                                '-positive'] += 1

            if len(channels) > 3:
                if areaFractionsArray[1][z] > areaFractionThreshold[1]:
                    if areaFractionsArray[3][z] > areaFractionThreshold[3]:
                        summary[channels[1][0] + '-' + channels[3][0] +
                                '-positive'] += 1
                if areaFractionsArray[2][z] > areaFractionThreshold[2]:
                    if areaFractionsArray[3][z] > areaFractionThreshold[3]:
                        summary[channels[2][0] + '-' + channels[3][0] +
                                '-positive'] += 1
                        if areaFractionsArray[1][z] > areaFractionThreshold[1]:
                            summary[channels[1][0] + '-' + channels[2][0] +
                                    '-' + channels[3][0] + '-positive'] += 1

    # Calculate the average of the particles sizes

    for chan in channels:
        v, x = chan
        summary[v + "-cells/tissue-area"] = summary[v + "-cells"] / bigareas[0]

    if float(summary['#nuclei']) > 0:
        summary['size-average'] = round(areaCounter / summary['#nuclei'], 2)

    if displayImages:

        fieldnames = ["Directory", "Image"]

        for chan in channels:
            v, x = chan
            summary[v + "-threshold"] = maxThresholds[x]
            fieldnames.append(v + "-threshold")
            allMaxThresholds[v + "-" + region].append(maxThresholds[x])

    # Opens and appends one line on the final csv file for the subfolder (remember that this is still inside the loop that goes through each image)

    with open(outputName, 'a') as csvfile:

        writer = csv.DictWriter(csvfile,
                                fieldnames=fieldnames,
                                extrasaction='ignore',
                                lineterminator='\n')
        if os.path.getsize(outputName) < 1:
            writer.writeheader()
        writer.writerow(summary)
Ejemplo n.º 39
0
def selectBest(imp):
	imp.getWindow().setLocation(0,0)
	file_name = imp.getTitle()
	file_path = IJ.getDirectory('image')
	printLog("filepath is "+file_path,1)
	
	
	[SI_version,nFrame,zStepSize,nStacks]=zyGetProperty(imp,"SI_version,nFrame,zStepSize,nStacks")	#need correct nSlices? do not delete any
	nSlices = imp.getNSlices()/nFrame				#otherwise, calculate by fiji function  
	msgStr = "The image has "+str(nFrame)+" frames from "+str(nStacks)+" stacks, was collected by ScanImage version "+str(SI_version)
	printLog(msgStr,0)
	if nFrame == 1:
		printLog("User need to import a file with multi-frames",0)
	else:			
		#duplicate one for resorting
		IJ.run(imp,"Duplicate...", "title=resortStack duplicate range=1-%d" %imp.getNSlices()) #bad fiji set this getNSlice() as all slice 
		resort_stack=IJ.getImage()
		resort_stack.getWindow().setLocation(0,0)
		IJ.run(resort_stack, "Label...", "format=0 starting=1 interval=1 x=5 y=20 font=18");
		
		#number pickup for every numRep
		IJ.selectWindow(file_name)
		#(width, height, nChannels, nSlices, nFrames) = imp.getDimensions(), bad fiji alway get wrong
		numRep = int(nFrame)
		m = int(nSlices) #real slice number when correcting the nFrames
		
		sPick = []
		printLog("-Current tif file:"+file_name,1)
		printLog("-nSlice="+str(m)+", nFrame="+str(numRep),2)
		printLog("-start picking the best repeat.",1)
		for i in range(0,m):
			j = i*numRep+1 #Z-step number
			#make montage to check all repeats at the same time for pickup
			IJ.run(imp,"Make Montage...", "columns="+str(numRep/nStacks)+" rows="+str(nStacks)+" scale=1 first="+str(j)+" last="+str(j+numRep-1)+" increment=1 border=1 font=12 label")
			m1_imp = IJ.getImage()
			IJ.run(m1_imp,"8-bit", "")
			m1_imp.getWindow().setLocation(530,0)
			IJ.run(m1_imp,"Set... ", "zoom=92 x=0 y=0")
			m1_title=m1_imp.getTitle()
			#merge the previous one if i>0
			if i==0:
				prePick = 1	#use first slice as mask
				IJ.run(resort_stack,"Duplicate...", "title=Max_z duplicate range=1-1" )
				zMax=IJ.getImage()
				zMax_win = zMax.getWindow().setLocation(0,580)
			else:	
				prePick = sPick[i-1]	#use previous selected slice as mask
							
			#duplicate numRep times of previous, concatenate, make montage, for merging channel as red with m1_imp
			m2_imp = mkMask(imp,prePick,numRep,nStacks)
			
			#merge the mask, and make new m1_imp as a 2-slice stack: Green (original) with merged
			m1_imp = zyMergeView(m1_imp,m2_imp)

			#pickup the best slice with slice number
			pickN = pickNum(numRep,nStacks)
			if not pickN:
				break
			else:
				pickN = pickN+j-1
					
			#do the moveSlice on resort_stack: move to the initial of pick: j
			resort_stack = moveSlice(resort_stack,pickN,j)

			#preview Z projection in a copy of resort_stack
			zMax.close()	#clear previous Z projection
			zMax = preview_Z(resort_stack,numRep,i+1) #show the new preview based on new pick
				
				
			#store the lucky slice number for making the substack in the future	
			sPick.append(int(pickN))
			#mmp = IJ.getImage()
			m1_imp.close()
		
		if len(sPick) == m:
			#means you have pick all slices required, but not cancel during process (break all out)
			IJ.selectWindow(file_name)
			outList =",".join(str(e) for e in sPick) #better to make a str: outList="slices=1,2,3"
			printLog("-Slices picked by user:"******"Make Substack...", "slices=%s" %(outList)) #all need to be str
			sr_imp = IJ.getImage()
			sr_imp.setTitle('P_'+file_name)
			#imp.changes = 0
			#imp.close()
			#zMax.close()
			#need to do: put a header for sr_imp here
		
			msgStr = "pixel_width=0.102857 pixel_height=0.102857 voxel_depth="+str(zStepSize)
			printLog("-Set the property of picked stack "+sr_imp.getTitle()+" to:"+msgStr,1) 
			IJ.run(sr_imp, "Properties...", msgStr)

			pickName = sr_imp.getTitle()
			destFolder_SR = os.path.join(file_path, 'Single_rep')
			#do multireg alignment
			doAlign(sr_imp,destFolder_SR)
			zyAddProperty(sr_imp)
			saveStack(destFolder_SR,pickName,sr_imp)
		
			destFolder_RS = os.path.join(file_path, 'reSort')
			#add Info
			zyAddProperty(resort_stack)
			saveStack(destFolder_RS,file_name,resort_stack)
		else:
			m1_imp.close()
			resort_stack.changes = 0
		imp.changes = 0
		imp.close()
		zMax.close()	
		resort_stack.close()
            roi.setName(hit['TemplateName'])
            roi.setPosition(i)  # set ROI Z-position
            #roi.setProperty("class", hit["TemplateName"])

            image.setSlice(i)
            image.setRoi(roi)

            if add_roi:
                rm.add(
                    None, roi, i
                )  # Trick to be able to set Z-position when less images than the number of ROI. Here i is an digit index before the Roi Name

                # Show All ROI + Associate ROI to slices
                rm.runCommand("Associate", "true")
                rm.runCommand("Show All with labels")
                IJ.selectWindow(ImageName)  # does not work always

            if show_table:
                Xcorner, Ycorner = hit['BBox'][0], hit['BBox'][1]
                Xcenter, Ycenter = CornerToCenter(Xcorner, Ycorner,
                                                  hit['BBox'][2],
                                                  hit['BBox'][3])

                Dico = {
                    'Image': hit['ImageName'],
                    'Slice': i,
                    'Template': hit['TemplateName'],
                    'Xcorner': Xcorner,
                    'Ycorner': Ycorner,
                    'Xcenter': Xcenter,
                    'Ycenter': Ycenter,
Ejemplo n.º 41
0
from ij.gui import WaitForUserDialog
from loci.plugins import BF
from ij.io import FileSaver
from ij.measure import Measurements
from ij.process import ImageStatistics as IS
from java.awt import Color
from ij import WindowManager
from ij import ImageStack

# Python imports
import socket
import os

# Close results window if it already exists
if WindowManager.getWindow('Results') is not None:
	IJ.selectWindow('Results')
	IJ.run('Close')

image = IJ.getImage()

# If there are multiple slices to the image, take the last one
# as that will be the original. That is our plan here to quickly
# deal with problems!

numSlices = image.getStackSize()
stack = image.getStack()
if numSlices > 1:
	for i in range(numSlices - 1):
		stack.deleteSlice(1)
image.setStack(stack)
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)
Ejemplo n.º 43
0
    os.rename(source_dir + '/' + f, source_dir + '/' + f[0:-6])

p = Register_Virtual_Stack_MT.Param()
#p.registrationModelIndex=5

Register_Virtual_Stack_MT.exec(source_dir, target_dir, transf_dir,
                               reference_name, p, use_shrinking_constraint)

WindowManager.getCurrentImage().setTitle("Orig")

lst = os.listdir(source_dir)
for f in lst:
    os.remove(source_dir + '/' + f)
IJ.log(imp.getTitle())

IJ.selectWindow(imp.getTitle())
nchannels = imp.getNChannels()

merge_string = ""

for i in range(1, nchannels + 1):
    IJ.selectWindow(imp.getTitle())
    IJ.run("Duplicate...", "duplicate channels=" + str(i))
    IJ.run("Image Sequence... ",
           "dir=" + source_dir + " format=TIFF, name=Tiffs")

    lst = os.listdir(source_dir)
    for f in lst:
        os.rename(source_dir + '/' + f, source_dir + '/' + f[0:-6])

    Transform_Virtual_Stack_MT.exec(source_dir, target_dir, transf_dir, True)
Ejemplo n.º 44
0
from ij.plugin.filter import ParticleAnalyzer
from ij.measure import Measurements
from ij.measure import ResultsTable
from ij.plugin.frame import RoiManager
from java.lang import Double

w = WindowManager 

inputImage='B013-D0-L-UV_cropped2.tif'
#IJ.selectWindow(inputImage)

title="pore_image";
IJ.run("Duplicate...", "title="+title)

IJ.run("RGB Stack");
IJ.selectWindow("pore_image")

IJ.run("Convert Stack to Images");

win = w.getWindow("Blue") 
win.removeNotify()

IJ.selectWindow("Red")
IJ.run("16-bit");
red=IJ.getImage()

IJ.selectWindow("Green")
IJ.run("16-bit")
green=IJ.getImage()

calc = ImageCalculator()
def process(srcDir, dstDir, currentDir, filename, keepDirectories):
    print "Processing:"

    # Opening the image
    print "Open image file", filename
    IJ.run(
        "Bio-Formats Importer",
        str("open=" + os.path.join(srcDir, filename) +
            " autoscale color_mode=Colorized open_files open_all_series display_metadata rois_import=[ROI manager] split_channels view=Hyperstack stack_order=XYCZT"
            ))

    # Exporting the Metadata to .csv
    IJ.selectWindow(str("Original Metadata - " + filename))
    IJ.saveAs(
        "Text",
        str(
            os.path.join(dstDir,
                         str("Original Metadata - " + filename[0:-4] +
                             ".csv"))))

    # Determines Number of Series and their names from Metadata
    md_file = open(
        str(
            os.path.join(dstDir,
                         str("Original Metadata - " + filename[0:-4] +
                             ".csv"))))
    md_reader = csv.reader(md_file)
    md_array = list(md_reader)
    find_series = re.compile(r'Series', re.IGNORECASE)
    index = []
    for i in range(len(md_array)):
        for x in range(0, 2):
            strv = str(md_array[i][x])
            please = find_series.findall(strv)
            if please != []:
                index.append(str(md_array[i][x + 1]))

    # PRIMARY PROCESSING LOOP

    # Using Series Information, the images can now be processes properly
    channels = ['C=0', 'C=1', 'C=2', 'C=3']
    it_chan = iter(channels)
    for i in range(len(index)):
        IJ.selectWindow(str(filename + ' - ' + index[i] + ' - ' + channels[0]))
        IJ.run("Z Project...", "projection=[Max Intensity]")
        IJ.selectWindow(str(filename + ' - ' + index[i] + ' - ' + channels[1]))
        IJ.run("Z Project...", "projection=[Max Intensity]")
        IJ.selectWindow(str(filename + ' - ' + index[i] + ' - ' + channels[2]))
        IJ.run("Z Project...", "projection=[Max Intensity]")
        #od = GenericDialog("Gray Field Slice")
        #od.addStringField("Which Layer is most in focus for C4?","")
        #od.showDialog()
        #if gd.wasCanceled():
        #	break
        #gf = od.getNextString()

        IJ.run(
            "Merge Channels...",
            str("c2=[MAX_" + filename + " - " + index[i] + " - C=0] c3=[MAX_" +
                filename + " - " + index[i] + " - C=2] c6=[MAX_" + filename +
                " - " + index[i] + " - C=1] create keep"))
        IJ.selectWindow(str(filename + ' - ' + index[i] + ' - ' + channels[0]))
        imp = IJ.getImage()
        imp.close()
        IJ.selectWindow(str(filename + ' - ' + index[i] + ' - ' + channels[1]))
        imp = IJ.getImage()
        imp.close()
        IJ.selectWindow(str(filename + ' - ' + index[i] + ' - ' + channels[2]))
        imp = IJ.getImage()
        imp.close()
Ejemplo n.º 46
0
	def __ImportCells(self, imagesnames) :

		#self.__dictCells[imgName]={}
		
		rm = RoiManager.getInstance()
		if (rm==None): rm = RoiManager()
		rm.runCommand("reset")

		listpaths = []
		listfilescells=[]

		if self.__optionImages :
			IJ.showMessage("Select the folder 'Cells' containing the cells to import")
			selectdir=IJ.getDirectory("image")
			selectdir=IJ.getDirectory("")
			listfilescells.extend(glob.glob(selectdir+os.path.sep+"*"))
			listpaths.append("")

		else : 
			IJ.showMessage("Select the text file containing the list cell paths (listpaths.txt)")
			selectdir=IJ.getDirectory("current")
			frame = Frame("Text file settings ?")
			fd = FileDialog(frame)
			fd.setDirectory(selectdir)
			fd.show()
			selectdir = fd.getDirectory() 
			textfile = fd.getFile()
			fichier = open(selectdir+textfile,"r")
			listpaths=[ glob.glob(f.split("\n")[0]+"Selected-Cells"+os.path.sep+"*") for f in fichier.readlines()]

			#for f in templist : 
			#	listpaths.append(f.split("\n")+"Cells")
				
			listfilescells.append("")

		if listfilescells[0]=="" : importmode = True
		else : importmode = False
		
		for j in range(len(listpaths)) :
			self.__dictCells[imagesnames[j]]={}
			if importmode : listfilescells = listpaths[j]
			pathtemp = []
			for cellfile in listfilescells :
				filetemp = open(cellfile,"r")
				linestemp=filetemp.readlines()
				for line in linestemp :
					params=line.split("=")
					values=params[1].split("\n")
					if params[0] == "NAMECELL" :
						celltemp=Bacteria_Cell(str(values[0]))
						self.__dictCells[imagesnames[j]][values[0]]=celltemp
						self.__dictMeasures[self.__dictCells[imagesnames[j]][values[0]]]={} 


					if params[0] == "PATHROIS" :
						pathtemp.append(str(values[0]))
						
					if params[0] == "NSLICES" : 
						for i in range(int(values[0])) :
							celltemp.getListRoi().append("")
				
					if params[0] == "SLICEINIT" :
						celltemp.setSlideInit(int(values[0]))
						for i in range(int(values[0])-2) :
							celltemp.setRoi("NOT HERE YET",i)
				
					if params[0] == "SLICEEND" :
						celltemp.setSlideEnd(int(values[0]))
						for i in range(int(values[0])) :
							celltemp.setRoi("LOST",i)
				
					if params[0] == "COLOR" :
						colorstemp=values[0].split(";")
						celltemp.setColor(Color(int(colorstemp[0]),int(colorstemp[1]),int(colorstemp[2])))
		
		
			indiceroi=0
			ind=0
			tempimp = WindowManager.getImage(imagesnames[j])
			if tempimp is not None : 
				IJ.selectWindow(imagesnames[j])
				tempimp.show()
			else : 
				if imagesnames[j][-4:]==".tif" : 
					IJ.selectWindow(imagesnames[j][:-4])
					tempimp = IJ.getImage()
				else : 
					IJ.selectWindow(imagesnames[j]+".tif")
					tempimp = IJ.getImage()
					
			rm.runCommand("reset")
			
			for cellname in self.__dictCells[imagesnames[j]].keys() :
				rm.runCommand("Open", pathtemp[ind])
				ind+=1
				nbtemp=self.__dictCells[imagesnames[j]][cellname].getLifeTime()
				for i in range(nbtemp) :
					rm.select(tempimp, indiceroi)
					roi=rm.getSelectedRoisAsArray()[0]
					self.__dictCells[imagesnames[j]][cellname].setRoi(roi,i+self.__dictCells[imagesnames[j]][cellname].getSlideInit()-1)
					indiceroi+=1

			IJ.run("Show Overlay", "")
			rm.runCommand("UseNames", "true")
			rm.runCommand("Associate", "true")
			IJ.run(tempimp, "Labels...", "color=red font=12 show use")
			if rm.getCount()>0 : IJ.run(tempimp, "From ROI Manager", "")
			rm.runCommand("Show None")
			rm.runCommand("Show All")

			roipath = os.path.split(pathtemp[0])[0]+os.path.sep
			rootpath = roipath.rsplit(os.path.sep, 2)[0]+os.path.sep

			self.__listpaths[j] = rootpath
			self.__rootpath=rootpath
Ejemplo n.º 47
0
def batch_open_images(pathRoi,
                      pathMask,
                      file_typeImage=None,
                      name_filterImage=None,
                      recursive=False):
    '''Open all files in the given folder.
    :param path: The path from were to open the images. String and java.io.File are allowed.
    :param file_type: Only accept files with the given extension (default: None).
    :param name_filter: Reject files that contain the given string (default: wild characters).
    :param recursive: Process directories recursively (default: False).
    '''
    # Converting a File object to a string.
    if isinstance(pathMask, File):
        pathMask = pathMask.getAbsolutePath()

    def check_type(string):
        '''This function is used to check the file type.
        It is possible to use a single string or a list/tuple of strings as filter.
        This function can access the variables of the surrounding function.
        :param string: The filename to perform the check on.
        '''
        if file_typeImage:
            # The first branch is used if file_type is a list or a tuple.
            if isinstance(file_typeImage, (list, tuple)):
                for file_type_ in file_typeImage:
                    if string.endswith(file_type_):
                        # Exit the function with True.
                        return True
                    else:
                        # Next iteration of the for loop.
                        continue
            # The second branch is used if file_type is a string.
            elif isinstance(file_typeImage, string):
                if string.endswith(file_typeImage):
                    return True
                else:
                    return False
            return False
        # Accept all files if file_type is None.
        else:
            return True

    def check_filter(string):
        '''This function is used to check for a given filter.
        It is possible to use a single string or a list/tuple of strings as filter.
        This function can access the variables of the surrounding function.
        :param string: The filename to perform the filtering on.
        '''
        if name_filterImage:
            # The first branch is used if name_filter is a list or a tuple.
            if isinstance(name_filterImage, (list, tuple)):
                for name_filter_ in name_filterImage:
                    if name_filter_ in string:
                        # Exit the function with True.

                        return True
                    else:
                        # Next iteration of the for loop.
                        continue
            # The second branch is used if name_filter is a string.
            elif isinstance(name_filterImage, string):
                if name_filterImage in string:
                    return True
                else:
                    return False
            return False
        else:
            # Accept all files if name_filter is None.
            return True

    # We collect all files to open in a list.
    path_to_Image = []
    # Replacing some abbreviations (e.g. $HOME on Linux).
    path = os.path.expanduser(pathMask)
    path = os.path.expandvars(pathMask)
    # If we don't want a recursive search, we can use os.listdir().
    if not recursive:
        for file_name in os.listdir(pathMask):
            full_path = os.path.join(pathMask, file_name)
            if os.path.isfile(full_path):
                if check_type(file_name):
                    if check_filter(file_name):
                        path_to_Image.append(full_path)
    # For a recursive search os.walk() is used.
    else:
        # os.walk() is iterable.
        # Each iteration of the for loop processes a different directory.
        # the first return value represents the current directory.
        # The second return value is a list of included directories.
        # The third return value is a list of included files.
        for directory, dir_names, file_names in os.walk(pathMask):
            # We are only interested in files.
            for file_name in file_names:
                # The list contains only the file names.
                # The full path needs to be reconstructed.
                full_path = os.path.join(directory, file_name)
                # Both checks are performed to filter the files.
                if check_type(file_name):
                    if check_filter(file_name) is False:
                        # Add the file to the list of images to open.
                        path_to_Image.append([
                            full_path,
                            os.path.basename(os.path.splitext(full_path)[0])
                        ])
    # Create the list that will be returned by this function.
    Masks = []
    rois = []
    ImageRois = []
    for img_path, file_name in path_to_Image:
        # IJ.openImage() returns an ImagePlus object or None.
        if check_filter(file_name):
            continue
        else:
            MaskName = str(pathMask) + '/' + file_name + '.tif'
            Mask = IJ.openImage(MaskName)

            Mask.show()
            rm = RoiManager.getInstance()
            if (rm == None):
                rm = RoiManager()
            rm.runCommand("Delete")
            IJ.selectWindow(file_name + '.tif')
            IJ.run("Find Edges")
            IJ.setAutoThreshold(Mask, "Default dark")
            IJ.run("Threshold")
            IJ.setThreshold(0, 0)

            IJ.run("Convert to Mask")
            IJ.run("Invert")
            IJ.run("Create Selection")
            rm.runCommand("Add")

            # An object equals True and None equals False.

            rois = rm.getRoisAsArray()
            rm.runCommand("Save",
                          str(pathRoi) + "/" + file_name + '.roi')
            Mask.changes = False
            Mask.close()

            ImageRois.append(rois)
    return ImageRois
Ejemplo n.º 48
0
def runOneFile(fullFilePath):
    global gFileType
    global gNumChannels
    global gAlignBatchVersion

    if not os.path.isfile(fullFilePath):
        bPrintLog(
            '\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n',
            0)
        return 0

    bPrintLog(
        time.strftime("%H:%M:%S") + ' starting runOneFile(): ' + fullFilePath,
        1)

    enclosingPath = os.path.dirname(fullFilePath)
    head, tail = os.path.split(enclosingPath)
    enclosingPath += '/'

    #make output folders
    destFolder = enclosingPath + tail + '_channels/'
    if not os.path.isdir(destFolder):
        os.makedirs(destFolder)

    #ZY: check whether aligned before
    elif os.path.basename(fullFilePath) in os.listdir(destFolder):
        bPrintLog('Has been aligned before', 1)
        return 0

    destMaxFolder = destFolder + 'max/'
    if not os.path.isdir(destMaxFolder):
        os.makedirs(destMaxFolder)
    #add ZY's deconvolution folder under root
    #destDecFolder = enclosingPath + 'deconvolution/'

    deconvolutionFolder = enclosingPath + tail + '_userRaw/'  #<session>_userRaw under root as deconvolution folder
    if not os.path.isdir(deconvolutionFolder):
        os.makedirs(deconvolutionFolder)

    #destDecFolder = destFolder + 'deconvolution/'
    #if not os.path.isdir(destDecFolder):
    #	os.makedirs(destDecFolder)

    if gDoAlign:
        destAlignmentFolder = destFolder + 'alignment/'
        if not os.path.isdir(destAlignmentFolder):
            os.makedirs(destAlignmentFolder)

    if gSave8bit:
        eightBitFolder = destFolder + 'channels8/'
        if not os.path.isdir(eightBitFolder):
            os.makedirs(eightBitFolder)
        eightBitMaxFolder = eightBitFolder + 'max/'
        if not os.path.isdir(eightBitMaxFolder):
            os.makedirs(eightBitMaxFolder)

    if gFileType == 'tif':
        # open .tif image
        imp = Opener().openImage(fullFilePath)
    else:
        # open .lsm
        cmdStr = 'open=%s autoscale color_mode=Default view=Hyperstack stack_order=XYCZT' % (
            fullFilePath, )
        IJ.run('Bio-Formats Importer', cmdStr)
        lsmpath, lsmfilename = os.path.split(fullFilePath)
        lsWindow = lsmfilename
        imp = WindowManager.getImage(lsWindow)

    # get parameters of image
    (width, height, nChannels, nSlices, nFrames) = imp.getDimensions()
    bitDepth = imp.getBitDepth()
    infoStr = imp.getProperty("Info")  #get all .tif tags
    if not infoStr:
        infoStr = ''
    infoStr += 'bAlignBatch_Version=' + str(gAlignBatchVersion) + '\n'
    infoStr += 'bAlignBatch_Time=' + time.strftime(
        "%Y%m%d") + '_' + time.strftime("%H%M%S") + '\n'

    msgStr = 'w:' + str(width) + ' h:' + str(height) + ' slices:' + str(nSlices) \
       + ' channels:' + str(nChannels) + ' frames:' + str(nFrames) + ' bitDepth:' + str(bitDepth)
    bPrintLog(msgStr, 1)

    path, filename = os.path.split(fullFilePath)
    shortName, fileExtension = os.path.splitext(filename)

    #
    # look for num channels in ScanImage infoStr
    #ZY: change the way read out the channel number, 20160617
    if gGetNumChanFromScanImage:
        #scanimage.SI4.channelsSave = [1;2]
        scanimage4 = 'scanimage.SI4.channelsSave =' in infoStr
        #state.acq.numberOfChannelsSave=2
        scanimage3 = 'state.acq.numberOfChannelsSave=' in infoStr
        if scanimage3:
            gNumChannels = int(
                infoStr.split('numberOfChannelsSave=')[1].split('\r')[0])
            bPrintLog('over-riding gNumChannels with: ' + str(gNumChannels), 2)
        #ZY: I do not know the format in scanImage4-_-, should be right with my math
        if scanimage4:
            gNumChannels = int(
                len(infoStr.split('numberOfChannelsSave=')[1].split('\r')[0]) /
                2)
            bPrintLog('over-riding gNumChannels with: ' + str(gNumChannels), 2)

    # show
    imp.show()
    # split channels if necc. and grab the original window names
    if gNumChannels == 1:
        origImpWinStr = imp.getTitle()  #use this when only one channel
        origImpWin = WindowManager.getWindow(
            origImpWinStr)  #returns java.awt.Window

    if gNumChannels == 2:
        winTitle = imp.getTitle()
        bPrintLog('Deinterleaving 2 channels...', 1)
        IJ.run('Deinterleave',
               'how=2 keep')  #makes ' #1' and ' #2', with ' #2' frontmost
        origCh1WinStr = winTitle + ' #1'
        origCh2WinStr = winTitle + ' #2'
        origCh1Imp = WindowManager.getImage(origCh1WinStr)
        origCh2Imp = WindowManager.getImage(origCh2WinStr)
        origCh1File = destFolder + shortName + '_ch1.tif'
        origCh2File = destFolder + shortName + '_ch2.tif'

    # work on a copy, mostly for alignment with cropping
    copy = Duplicator().run(imp)
    #copy.copyAttributes(imp) #don't copy attributes, it copies the name (which we do not want)
    copy.show()

    #
    # crop (on copy)
    if gDoCrop:
        bPrintLog('making cropping rectangle (left,top,width,height) ', 1)
        bPrintLog(
            str(gCropLeft) + ' ' + str(gCropTop) + ' ' + str(gCropWidth) +
            ' ' + str(gCropHeight), 2)

        roi = Roi(gCropLeft, gCropTop, gCropWidth,
                  gCropHeight)  #left,top,width,height
        copy.setRoi(roi)

        time.sleep(
            0.5
        )  # otherwise, crop SOMETIMES failes. WHAT THE F**K FIJI DEVELOPERS, REALLY, WHAT THE F**K

        #bPrintLog('cropping', 1)
        IJ.run('Crop')
        infoStr += 'bCropping=' + str(gCropLeft) + ',' + str(
            gCropTop) + ',' + str(gCropWidth) + ',' + str(gCropHeight) + '\n'

    #
    # remove calibration ( on original)
    if gRemoveCalibration:
        cal = imp.getCalibration()
        calCoeff = cal.getCoefficients()
        if calCoeff:
            msgStr = 'Calibration is y=a+bx' + ' a=' + str(
                calCoeff[0]) + ' b=' + str(calCoeff[1])
            bPrintLog(msgStr, 1)

            #remove calibration
            bPrintLog('\tRemoving Calibration', 2)
            imp.setCalibration(None)

            #without these, 8-bit conversion goes to all 0 !!! what the f**k !!!
            #bPrintLog('calling imp.resetStack() and imp.resetDisplayRange()', 2)
            imp.resetStack()
            imp.resetDisplayRange()

            #get and print out min/max
            origMin = StackStatistics(imp).min
            origMax = StackStatistics(imp).max
            msgStr = '\torig min=' + str(origMin) + ' max=' + str(origMax)
            bPrintLog(msgStr, 2)

            # 20150723, 'shift everybody over by linear calibration intercept calCoeff[0] - (magic number)
            if 1:
                # [1] was this
                #msgStr = 'Subtracting original min '+str(origMin) + ' from stack.'
                #bPrintLog(msgStr, 2)
                #subArgVal = 'value=%s stack' % (origMin,)
                #IJ.run('Subtract...', subArgVal)
                # [2] now this
                #msgStr = 'Adding calCoeff[0] '+str(calCoeff[0]) + ' from stack.'
                #bPrintLog(msgStr, 2)
                #addArgVal = 'value=%s stack' % (int(calCoeff[0]),)
                #IJ.run('Add...', addArgVal)
                # [3] subtract a magic number 2^15-2^7 = 32768 - 128
                magicNumber = gLinearShift  #2^15 - 128
                msgStr = 'Subtracting a magic number (linear shift) ' + str(
                    magicNumber) + ' from stack.'
                bPrintLog(msgStr, 2)
                infoStr += 'bLinearShift=' + str(gLinearShift) + '\n'
                subArgVal = 'value=%s stack' % (gLinearShift, )
            IJ.run(imp, 'Subtract...', subArgVal)

            # 20150701, set any pixel <0 to 0
            if 0:
                ip = imp.getProcessor()  # returns a reference
                pixels = ip.getPixels()  # returns a reference
                msgStr = '\tSet all pixels <0 to 0. This was added 20150701 ...'
                bPrintLog(msgStr, 2)
                pixels = map(lambda x: 0 if x < 0 else x, pixels)
                bPrintLog('\t\t... done', 2)

            #get and print out min/max
            newMin = StackStatistics(imp).min
            newMax = StackStatistics(imp).max
            msgStr = '\tnew min=' + str(newMin) + ' max=' + str(newMax)
            bPrintLog(msgStr, 2)

            #append calibration to info string
            infoStr += 'bCalibCoeff_a = ' + str(calCoeff[0]) + '\n'
            infoStr += 'bCalibCoeff_b = ' + str(calCoeff[1]) + '\n'
            infoStr += 'bNewMin = ' + str(newMin) + '\n'
            infoStr += 'bNewMax = ' + str(newMax) + '\n'

    #
    # set up
    if gNumChannels == 1:
        impWinStr = copy.getTitle()  #use this when only one channel
        impWin = WindowManager.getWindow(impWinStr)  #returns java.awt.Window

    if gNumChannels == 2:
        winTitle = copy.getTitle()
        bPrintLog('Deinterleaving 2 channels...', 1)
        IJ.run('Deinterleave',
               'how=2 keep')  #makes ' #1' and ' #2', with ' #2' frontmost
        ch1WinStr = winTitle + ' #1'
        ch2WinStr = winTitle + ' #2'
        ch1Imp = WindowManager.getImage(ch1WinStr)
        ch2Imp = WindowManager.getImage(ch2WinStr)
        ch1File = destFolder + shortName + '_ch1.tif'
        ch2File = destFolder + shortName + '_ch2.tif'

    #
    # alignment
    if gDoAlign and gNumChannels == 1 and copy.getNSlices() > 1:
        infoStr += 'AlignOnChannel=1' + '\n'
        #snap to middle slice
        if gAlignOnMiddleSlice:
            middleSlice = int(
                math.floor(copy.getNSlices() /
                           2))  #int() is necc., python is f*****g picky
        else:
            middleSlice = gAlignOnThisSlice
        copy.setSlice(middleSlice)

        transformationFile = destAlignmentFolder + shortName + '.txt'

        bPrintLog('MultiStackReg aligning:' + impWinStr, 1)
        stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Translation] save' % (
            impWin, transformationFile)
        IJ.run('MultiStackReg', stackRegParams)
        infoStr += 'AlignOnSlice=' + str(middleSlice) + '\n'

        #20150723, we just aligned on a cropped copy, apply alignment to original imp
        origImpTitle = imp.getTitle()
        stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Translation]' % (
            origImpTitle, transformationFile)
        IJ.run('MultiStackReg', stackRegParams)

    if gDoAlign and gNumChannels == 2 and ch1Imp.getNSlices(
    ) > 1 and ch2Imp.getNSlices() > 1:
        #apply to gAlignThisChannel
        alignThisWindow = ''
        applyAlignmentToThisWindow = ''
        if gAlignThisChannel == 1:
            infoStr += 'AlignOnChannel=1' + '\n'
            transformationFile = destAlignmentFolder + shortName + '_ch1.txt'
            alignThisWindow = ch1WinStr
            applyAlignmentToThisWindow = ch2WinStr
        else:
            infoStr += 'AlignOnChannel=2' + '\n'
            transformationFile = destAlignmentFolder + shortName + '_ch2.txt'
            alignThisWindow = ch2WinStr
            applyAlignmentToThisWindow = ch1WinStr

        alignThisImp = WindowManager.getImage(alignThisWindow)
        #snap to middle slice
        if gAlignOnMiddleSlice:
            middleSlice = int(
                math.floor(alignThisImp.getNSlices() /
                           2))  #int() is necc., python is f*****g picky
        else:
            middleSlice = gAlignOnThisSlice
        alignThisImp.setSlice(middleSlice)

        infoStr += 'bAlignOnSlice=' + str(middleSlice) + '\n'

        bPrintLog('MultiStackReg aligning:' + alignThisWindow, 1)
        stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Translation] save' % (
            alignThisWindow, transformationFile)
        IJ.run('MultiStackReg', stackRegParams)

        # 20150723, we just aligned on a copy, apply alignment to both channels of original
        # ch1
        bPrintLog('MultiStackReg applying alignment to:' + origCh1WinStr, 1)
        stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Translation]' % (
            origCh1WinStr, transformationFile)
        IJ.run('MultiStackReg', stackRegParams)
        # ch2
        bPrintLog('MultiStackReg applying alignment to:' + origCh2WinStr, 1)
        stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Translation]' % (
            origCh2WinStr, transformationFile)
        IJ.run('MultiStackReg', stackRegParams)

        #apply alignment to other window
        #bPrintLog('MultiStackReg applying alignment to:' + applyAlignmentToThisWindow, 1)
        #applyAlignThisImp = WindowManager.getImage(applyAlignmentToThisWindow)
        #stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(applyAlignmentToThisWindow,transformationFile)
        #IJ.run('MultiStackReg', stackRegParams)
    else:  #ZY: add more conditions
        bPrintLog('Skipping alignment, there may be only one slice?', 3)

    #
    # save
    if gNumChannels == 1:
        imp.setProperty("Info", infoStr)
        impFile = destFolder + shortName + '.tif'
        #bPrintLog('Saving:' + impFile, 1)
        bSaveStack(imp, impFile)
        #max project
        bSaveZProject(imp, destMaxFolder, shortName)

    if gNumChannels == 2:
        #ch1
        origCh1Imp.setProperty("Info", infoStr)
        #bPrintLog('Saving:' + ch1File, 1)
        bSaveStack(origCh1Imp, ch1File)
        #max project
        bSaveZProject(origCh1Imp, destMaxFolder, shortName + '_ch1')

        #ch2
        origCh2Imp.setProperty("Info", infoStr)
        #bPrintLog('Saving:' + ch2File, 1)
        bSaveStack(origCh2Imp, ch2File)
        #max project
        bSaveZProject(origCh2Imp, destMaxFolder, shortName + '_ch2')

#
    # post convert to 8-bit and save
    if gSave8bit:
        if bitDepth == 16:
            if gNumChannels == 1:
                bPrintLog('Converting to 8-bit:' + impWinStr, 1)
                IJ.selectWindow(impWinStr)
                #IJ.run('resetMinAndMax()')
                IJ.run("8-bit")
                impFile = eightBitFolder + shortName + '.tif'
                bPrintLog('Saving 8-bit:' + impFile, 2)
                bSaveStack(imp, impFile)
                #max project
                bSaveZProject(imp, eightBitMaxFolder, shortName)

            if gNumChannels == 2:
                #
                bPrintLog('Converting to 8-bit:' + origCh1WinStr, 1)
                IJ.selectWindow(origCh1WinStr)

                IJ.run("8-bit")
                impFile = eightBitFolder + shortName + '_ch1.tif'
                bPrintLog('Saving 8-bit:' + impFile, 2)
                bSaveStack(origCh1Imp, impFile)
                #max project
                bSaveZProject(origCh1Imp, eightBitMaxFolder,
                              shortName + '_ch1')

                #
                bPrintLog('Converting to 8-bit:' + origCh2WinStr, 1)
                IJ.selectWindow(origCh2WinStr)
                #IJ.run('resetMinAndMax()')
                IJ.run("8-bit")
                impFile = eightBitFolder + shortName + '_ch2.tif'
                bPrintLog('Saving 8-bit:' + impFile, 2)
                bSaveStack(origCh2Imp, impFile)
                #max project
                bSaveZProject(origCh2Imp, eightBitMaxFolder,
                              shortName + '_ch2')

    #
    # close original window
    imp.changes = 0
    imp.close()
    #copy
    copy.changes = 0
    copy.close()

    #
    # close ch1/ch2
    if gNumChannels == 2:
        #original
        origCh1Imp.changes = 0
        origCh1Imp.close()
        origCh2Imp.changes = 0
        origCh2Imp.close()
        #copy
        ch1Imp.changes = 0
        ch1Imp.close()
        ch2Imp.changes = 0
        ch2Imp.close()

    bPrintLog(
        time.strftime("%H:%M:%S") + ' finished runOneFile(): ' + fullFilePath,
        1)
Ejemplo n.º 49
0
def analyzeImage(passImage, passModel, passProbability, passOutput):
    retResults = list()

    # Apply weka training model to image
    wekaSeg = WekaSegmentation(passImage)
    wekaSeg.loadClassifier(passModel)
    wekaSeg.applyClassifier(True)

    # Extract probability map
    wekaImg = wekaSeg.getClassifiedImage()
    wekaImg.show()
    IJ.run("Clear Results")

    # Process each slice
    for sliceIdx in range(ROW_BACKGROUND + 1):
        # Select slice and duplicate
        IJ.selectWindow("Probability maps")
        IJ.setSlice(sliceIdx + 1)
        IJ.run("Duplicate...", "title=temp")

        # Apply threshold to probability
        IJ.setThreshold(passProbability, 1, "Black & White")

        # For background, take inverse
        if sliceIdx == ROW_BACKGROUND: IJ.run("Invert")

        # Change background to NaN for area, then measure
        IJ.run("NaN Background", ".")
        IJ.run("Measure")

        # Save image to output directory
        fileParts = passImage.getTitle().split(".")
        IJ.save(
            os.path.join(
                passOutput,
                "{0}-{1}.{2}".format(fileParts[0], FILE_TYPE[sliceIdx],
                                     '.'.join(fileParts[1:]))))

        IJ.selectWindow("temp")
        IJ.run("Close")

    # Close probability maps
    IJ.selectWindow("Probability maps")
    IJ.run("Close")

    # Obtain results
    tempResults = list()
    tableResults = ResultsTable.getResultsTable()
    for rowIdx in range(tableResults.size()):
        tempResults.append(
            [float(x) for x in tableResults.getRowAsString(rowIdx).split()])

    # Compile image statistics as M/(M+F), F/(M+F), M/total, F/total, U/total, E/total, M+F, total
    mfTotal = tempResults[ROW_MALE][FIELD_AREA] + tempResults[ROW_FEMALE][
        FIELD_AREA]
    total = tempResults[ROW_BACKGROUND][FIELD_AREA]

    retResults.append(tempResults[ROW_MALE][FIELD_AREA] / mfTotal)
    retResults.append(tempResults[ROW_FEMALE][FIELD_AREA] / mfTotal)
    retResults.append(tempResults[ROW_MALE][FIELD_AREA] / total)
    retResults.append(tempResults[ROW_FEMALE][FIELD_AREA] / total)
    retResults.append(tempResults[ROW_UNDIF][FIELD_AREA] / total)
    retResults.append(tempResults[ROW_EXTRA][FIELD_AREA] / total)
    retResults.append(mfTotal)
    retResults.append(total)

    return retResults
Ejemplo n.º 50
0
            else:
                done = done + 1
            # re-open original image because we need to crop it around the bead
            # to make sure our coordinates are right, we first crop to 300x300 just like before
            IJ.run(
                "Bio-Formats Importer", "open='" + path +
                "' autoscale color_mode=Default view=Hyperstack stack_order=XYCZT"
            )
            IJ.run("Specify...",
                   "width=300 height=300 x=512 y=512 slice=1 centered")
            IJ.run("Crop")
            image = IJ.getImage()
            stack = image.getStack()
            title = image.getTitle()

            IJ.selectWindow(title)
            # create a duplicate of the cropped original that will be cropped again
            IJ.run("Duplicate...", "duplicate")
            image_2 = IJ.getImage()
            image_2.setTitle("duplicate_spot")

            # we crop a 50x50px area centered at the bead
            IJ.run(
                image_2, "Specify...", "width=50 height=50 x=" +
                str(x / image.getCalibration().getX(1)) + " y=" +
                str(y / image.getCalibration().getY(1)) + " slice=1 centered")
            IJ.run("Crop")

            # just generating some useful string auxiliary variables
            filename = os.path.join(
                str(srcFile),
Ejemplo n.º 51
0
IJ.log("-----------------------------------------------------------------------------------------------------------------")
IJ.log("Batch started " + str(start_time))
setting = "min._peak_amplitude=50 min._peak_distance=0.0015 min._value=190 max._value=0 exclude list"
IJ.log("BAR Find Peaks settings: " + setting)
results = [("Sample ID", "Filename", "Scan", "Duty 1", "Duty 2", "Scan stdev1", "Scan stdev2", "Peaks", "Max Duty", "Min Duty")]
csvpath = str(output_dir) + "\\Duty " + str(folder) + "\\"
os.mkdir(csvpath)
num_scans = int(input_scans)
num_scans += 1
IJ.log("Input image directory: " + str(input_dir))
IJ.log("Output results directory: " + str(csvpath))
IJ.log("Number of scans per image: " + str(input_scans))
IJ.log("File types: " + str(file_types))
IJ.log("Filters: " + str(filters))
IJ.log("Horizontal grating lines: " + str(do_horizontal))
IJ.selectWindow("Log")
IJ.saveAs("Text", csvpath + "Duty_Log.txt")

def sort_table(table, col=0):
    return sorted(table, key=operator.itemgetter(col))

def duty_cycle(i, horizontal):
	IJ.open(i)
	IJ.run("Enhance Contrast...", "saturated=0.3 equalize")
	IJ.run("Smooth", "")
	'IJ.run("Anisotropic Diffusion 2D", "number=20 smoothings=1 keep=20 a1=0.50 a2=0.90 dt=20 edge=5")     # use instead of smooth for better results, slower
	imp = IJ.getImage()
	ImageConverter(imp).convertToGray8()
	file_base = str(imp.title)								# convert name into string
	file_base = file_base.split('.', 1)[0]					# remove all characters including and after .
	sample_id = file_base.split('_', 1)[0]
Ejemplo n.º 52
0
def getImage(title):
	IJ.selectWindow(title)
	return IJ.getImage() 
Ejemplo n.º 53
0
def duty_cycle(i, horizontal):
	IJ.open(i)
	IJ.run("Enhance Contrast...", "saturated=0.3 equalize")
	IJ.run("Smooth", "")
	'IJ.run("Anisotropic Diffusion 2D", "number=20 smoothings=1 keep=20 a1=0.50 a2=0.90 dt=20 edge=5")     # use instead of smooth for better results, slower
	imp = IJ.getImage()
	ImageConverter(imp).convertToGray8()
	file_base = str(imp.title)								# convert name into string
	file_base = file_base.split('.', 1)[0]					# remove all characters including and after .
	sample_id = file_base.split('_', 1)[0]
	height = imp.height
	width = imp.width
	IJ.run(imp, "Set Scale...", "distance=5000 known=1 pixel=1 unit=cm")
	IJ.setTool("line")
	for scan in range(1, num_scans):
		row_count = 0
		data=[]
		data2=[]
		last = 0
		filename = file_base + "_" + str(scan)
		
		if not horizontal:
			IJ.makeLine(0, scan*height/num_scans, width, scan*height/num_scans)				# horizontal line to measure vertical grating profile		
		else:
			IJ.makeLine(width*scan/num_scans, 9*height/10, width*scan/num_scans, 0)			# vertical line to measure horizontal grating profile
		
		IJ.run(imp, "Plot Profile", "")
		imp_plot = IJ.getImage()
		IJ.run(imp, "Find Peaks", setting)	# nw07 params: min._peak_amplitude=60 min._peak_distance=0 min._value=100 max._value=0 exclude list
		IJ.saveAs("Results", csvpath + filename + "_raw.csv")
		imp_plot.close()
		imp_plot = IJ.getImage()
		IJ.saveAs("Png", csvpath + "Peaks in Plot of " + filename + ".png")
		imp_plot.close()
		IJ.selectWindow(filename + "_raw.csv")
		IJ.run("Close")
		
		with open(csvpath + filename + "_raw.csv", "rb") as fin, open(csvpath + filename + "_peaks.csv", "wb") as fout:  
		    writer = csv.writer(fout)            
		    for row in csv.reader(fin):
		        if not row[2] == '':
		             writer.writerow(row)

		with open(csvpath + filename + "_peaks.csv", "rb") as File:
		    reader = csv.reader(File)
		    for row in reader:
		        row_count += 1
			if row_count == 1:
				continue
			data.append(tuple(row))								# Append all non-header rows into a list of data as a tuple of cells
		for row in sort_table(data, 2):
			data2.append(tuple(row))
		if len(data2) < 3:
			IJ.log(filename + " no peaks detected, skipping...")
			continue
		else:
			peaks = len(data2)
			last = data2[0]
			last = last[2]
			
			row_count = 0
			diff = 0
			colG = []
			blank = ""
			duty = zip(*data2)
			for row in data2:
				row_count += 1
				if row_count == 1:
					continue
				else:
					print row[2]
					print last
					diff = float(row[2]) - float(last)
					colG.append(diff)
					last = row[2]
			a, b = colG[::2], colG[1::2]
			avga = sum(a)/len(a)
			avgb = sum(b)/len(b)
			a_len_dev = len(a) - 1
			b_len_dev = len(b) - 1
			if b_len_dev > 1:
				a_stdev = sqrt(sum((x - avga)**2 for x in a) / a_len_dev)
				b_stdev = sqrt(sum((x - avgb)**2 for x in b) / b_len_dev)
			else:
				a_stdev = 1
				b_stdev = 1
			
			duty_cyc = avga/(avga+avgb)
			perc = duty_cyc*100
			invperc = 100 - perc
			inv_duty = 1 - duty_cyc
			duty_max = max(duty_cyc, inv_duty)
			duty_min = min(duty_cyc, inv_duty)
			percs = round(perc)
			percs = int(percs)
			percs = str(percs)
			invpercs = round(invperc)
			invpercs = int(invpercs)
			invpercs = str(invpercs)
		
			colG.insert(0, blank)
			a.insert(0, blank)
			b.insert(0, blank)
			b.insert(1, blank)
			
			i = 0
			while i < len(a):
					i += 2
					a.insert(i, blank)
			
			i = 1
			while i < len(b):
					i += 2
					b.insert(i, blank)
			
			duty.append(colG)
			duty.append(a)
			duty.append(b)	
			duty = zip(*duty)
			result = [sample_id, file_base, scan, duty_cyc, inv_duty, a_stdev, b_stdev, peaks, duty_max, duty_min]
			header = ["X0", "Y0", "X1", "Y1", "X2", "Y2", "diff", "a", "b"]
			results.append(result)
			with open(csvpath + filename + "_duty.csv", 'wb') as myfile:
				wr = csv.writer(myfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
				wr.writerow(header)
				wr.writerows(duty)
			print(filename + " duty cycle is " + percs + "/" + invpercs + "%.")
			IJ.log(filename + " duty cycle is " + percs + "/" + invpercs + "% (" + str(peaks) + " peaks found)")
			with open(csvpath + "results.csv", 'wb') as myfile:
				wr = csv.writer(myfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
				wr.writerows(results)		# Write the result data from all images into a single csv file
Ejemplo n.º 54
0
from ij import IJ
import sys
from java.lang.System import getProperty
sys.path.append(getProperty("fiji.dir") + "/plugins/NordenTools")
import NordenTools as nt

from setup import *

for timepointstring in time_points:
  IJ.log("Processing " + timepointstring + "...")
  project = Project.openFSProject(trakem_dir + timepointstring + ".xml", True)
  Thread.sleep(2000)
  # EXPORT RAW
  windowName = nt.openStack()
  IJ.log(">> "+windowName)
  IJ.selectWindow(windowName);
  IJ.run("Save", "save="+output_dir+"raw_"+timepointstring+".tif");
  IJ.run("Close")
  # EXPORT MASK
  nt.exportMask()
  IJ.selectWindow("Labels");
  IJ.run("Save", "save="+output_dir+"labels_"+timepointstring+".tif");
  IJ.run("Close")
  # EXPORT SEGMENTATION
  nt.exportSegmentation()
  IJ.selectWindow("Segmentation");
  IJ.run("Save", "save="+output_dir+"seg_"+timepointstring+".tif");
  IJ.run("Close")
  # CLOSE PROJECT
  Thread.sleep(1000)
  project.getLoader().setChanged(False) # avoid dialog at closing
Ejemplo n.º 55
0
def runOneFile(fullFilePath):

    global gNumChannels

    if not os.path.isfile(fullFilePath):
        bPrintLog(
            '\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n',
            0)
        return 0

    bPrintLog(
        time.strftime("%H:%M:%S") + ' starting runOneFile(): ' + fullFilePath,
        1)

    enclosingPath = os.path.dirname(fullFilePath)
    head, tail = os.path.split(enclosingPath)
    enclosingPath += '/'

    #make output folders
    destFolder = enclosingPath + tail + '_channels/'
    if not os.path.isdir(destFolder):
        os.makedirs(destFolder)
    destMaxFolder = destFolder + 'max/'
    if not os.path.isdir(destMaxFolder):
        os.makedirs(destMaxFolder)

    if gDoAlign:
        destAlignmentFolder = destFolder + 'alignment/'
        if not os.path.isdir(destAlignmentFolder):
            os.makedirs(destAlignmentFolder)

    if gSave8bit:
        eightBitFolder = destFolder + 'channels8/'
        if not os.path.isdir(eightBitFolder):
            os.makedirs(eightBitFolder)
        eightBitMaxFolder = eightBitFolder + 'max/'
        if not os.path.isdir(eightBitMaxFolder):
            os.makedirs(eightBitMaxFolder)

    # open image
    imp = Opener().openImage(fullFilePath)

    # get parameters of image
    (width, height, nChannels, nSlices, nFrames) = imp.getDimensions()
    bitDepth = imp.getBitDepth()
    infoStr = imp.getProperty("Info")  #get all .tif tags
    if not infoStr:
        infoStr = ''

    msgStr = 'w:' + str(width) + ' h:' + str(height) + ' slices:' + str(nSlices) \
       + ' channels:' + str(nChannels) + ' frames:' + str(nFrames) + ' bitDepth:' + str(bitDepth)
    bPrintLog(msgStr, 1)

    path, filename = os.path.split(fullFilePath)
    shortName, fileExtension = os.path.splitext(filename)

    #this is too much work for ScanImage4
    #try and guess channels if it is a scanimage file
    #scanImage3 = string.find(infoStr, 'scanimage') != -1
    #scanimage4 = find(infoStr, 'scanimage.SI4.channelSave = ')
    #print 'scanimage4:', scanimage4

    #
    # look for num channels in ScanImage infoStr
    if gGetNumChanFromScanImage:
        for line in infoStr.split('\n'):
            #scanimage.SI4.channelsSave = [1;2]
            scanimage4 = find(line, 'scanimage.SI4.channelsSave =') == 0
            #state.acq.numberOfChannelsSave=2
            scanimage3 = find(line, 'state.acq.numberOfChannelsSave=') == 0
            if scanimage3:
                #print 'line:', line
                equalIdx = find(line, '=')
                line2 = line[equalIdx + 1:]
                if gGetNumChanFromScanImage:
                    gNumChannels = int(line2)
                    bPrintLog(
                        'over-riding gNumChannels with: ' + str(gNumChannels),
                        2)
            if scanimage4:
                #print '   we have a scanimage 4 file ... now i need to exptract the number of channel'
                #print 'line:', line
                equalIdx = find(line, '=')
                line2 = line[equalIdx + 1:]
                for delim in ';[]':
                    line2 = line2.replace(delim, ' ')
                if gGetNumChanFromScanImage:
                    gNumChannels = len(line2.split())
                    bPrintLog(
                        'over-riding gNumChannels with: ' + str(gNumChannels),
                        2)

    # show
    imp.show()

    infoStr += 'bAlignBatch6=' + time.strftime("%Y%m%d") + '\n'
    #
    # crop
    if gDoCrop:
        bPrintLog('making cropping rectangle (left,top,width,height) ', 1)
        bPrintLog(
            str(gCropLeft) + ' ' + str(gCropTop) + ' ' + str(gCropWidth) +
            ' ' + str(gCropHeight), 2)
        roi = Roi(gCropLeft, gCropTop, gCropWidth,
                  gCropHeight)  #left,top,width,height
        imp.setRoi(roi)

        #time.sleep(1)

        #bPrintLog('cropping', 1)
        IJ.run('Crop')
        infoStr += 'cropping=' + str(gCropLeft) + ',' + str(
            gCropTop) + ',' + str(gCropWidth) + ',' + str(gCropHeight) + '\n'

    #
    # remove negative (<0) pixel values
    #ip = imp.getProcessor()
    #pixels = ip.getPixels()  # this returns a reference (not a copy)
    #for i in xrange(len(pixels)):
    #	if pixels[i] < 0:
    #		pixels[i] = 0
    # or this, for each pixel 'x', if  x<0 then 0 else x
    #pixels = map(lambda x: 0 if x<0 else x, pixels)

    #set our new values (without pixels <0) back into original (I hope this handles stacks and channels???)
    #ip.setPixels(pixels)

    #
    # remove calibration
    if gRemoveCalibration:
        cal = imp.getCalibration()
        calCoeff = cal.getCoefficients()
        if calCoeff:
            msgStr = 'Calibration is y=a+bx' + ' a=' + str(
                calCoeff[0]) + ' b=' + str(calCoeff[1])
            bPrintLog(msgStr, 1)

            #remove calibration
            bPrintLog('\tRemoving Calibration', 2)
            imp.setCalibration(None)

            #get and print out min/max
            origMin = StackStatistics(imp).min
            origMax = StackStatistics(imp).max
            msgStr = '\torig min=' + str(origMin) + ' max=' + str(origMax)
            bPrintLog(msgStr, 2)

            #msgStr = 'adding calCoeff[0]='+str(calCoeff[0]) + ' to stack.'
            #bPrintLog(msgStr, 2)
            #subArgVal = 'value=%s stack' % (calCoeff[0],)
            #IJ.run('Add...', subArgVal)

            # 20150701, 'shift everybody over by linear calibration intercept calCoeff[0]'
            if 1:
                # [1] was this
                #msgStr = 'Subtracting original min '+str(origMin) + ' from stack.'
                #bPrintLog(msgStr, 2)
                #subArgVal = 'value=%s stack' % (origMin,)
                #IJ.run('Subtract...', subArgVal)
                # [2] now this
                #msgStr = 'Adding calCoeff[0] '+str(calCoeff[0]) + ' from stack.'
                #bPrintLog(msgStr, 2)
                #addArgVal = 'value=%s stack' % (int(calCoeff[0]),)
                #IJ.run('Add...', addArgVal)
                # [3] subtract a magic number 2^15-2^7 = 32768 - 128
                magicNumber = 32768 - 128
                msgStr = 'Subtracting a magic number ' + str(
                    magicNumber) + ' from stack.'
                bPrintLog(msgStr, 2)
                subArgVal = 'value=%s stack' % (origMin, )
                IJ.run('Subtract...', subArgVal)

            # 20150701, set any pixel <0 to 0
            if 0:
                ip = imp.getProcessor()  # returns a reference
                pixels = ip.getPixels()  # returns a reference
                msgStr = '\tSet all pixels <0 to 0. This was added 20150701 ...'
                bPrintLog(msgStr, 2)
                pixels = map(lambda x: 0 if x < 0 else x, pixels)
                bPrintLog('\t\t... done', 2)

            #get and print out min/max
            newMin = StackStatistics(imp).min
            newMax = StackStatistics(imp).max
            msgStr = '\tnew min=' + str(newMin) + ' max=' + str(newMax)
            bPrintLog(msgStr, 2)

            #without these, 8-bit conversion goes to all 0 !!! what the f**k !!!
            #bPrintLog('calling imp.resetStack() and imp.resetDisplayRange()', 2)
            imp.resetStack()
            imp.resetDisplayRange()

            #append calibration to info string
            infoStr += 'calibCoeff_a = ' + str(calCoeff[0]) + '\n'
            infoStr += 'calibCoeff_b = ' + str(calCoeff[1]) + '\n'
            infoStr += 'origMin = ' + str(origMin) + '\n'
            infoStr += 'origMax = ' + str(origMax) + '\n'

    #
    # set up
    if gNumChannels == 1:
        impWinStr = imp.getTitle()  #use this when only one channel
        impWin = WindowManager.getWindow(impWinStr)  #returns java.awt.Window

    if gNumChannels == 2:
        winTitle = imp.getTitle()
        bPrintLog('Deinterleaving 2 channels...', 1)
        IJ.run('Deinterleave',
               'how=2 keep')  #makes ' #1' and ' #2', with ' #2' frontmost
        ch1WinStr = winTitle + ' #1'
        ch2WinStr = winTitle + ' #2'
        ch1Imp = WindowManager.getImage(ch1WinStr)
        ch2Imp = WindowManager.getImage(ch2WinStr)
        ch1File = destFolder + shortName + '_ch1.tif'
        ch2File = destFolder + shortName + '_ch2.tif'

    #
    # alignment
    if gDoAlign and gNumChannels == 1 and imp.getNSlices() > 1:
        infoStr += 'AlignOnChannel=1' + '\n'
        #snap to middle slice
        if gAlignOnMiddleSlice:
            middleSlice = int(
                math.floor(imp.getNSlices() /
                           2))  #int() is necc., python is f*****g picky
        else:
            middleSlice = gAlignOnThisSlice
        imp.setSlice(middleSlice)

        transformationFile = destAlignmentFolder + shortName + '.txt'

        bPrintLog('MultiStackReg aligning:' + impWinStr, 1)
        stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' % (
            impWin, transformationFile)
        IJ.run('MultiStackReg', stackRegParams)
        infoStr += 'AlignOnSlice=' + str(middleSlice) + '\n'
    if gDoAlign and gNumChannels == 2 and ch1Imp.getNSlices(
    ) > 1 and ch2Imp.getNSlices() > 1:
        #apply to gAlignThisChannel
        alignThisWindow = ''
        applyAlignmentToThisWindow = ''
        if gAlignThisChannel == 1:
            infoStr += 'AlignOnChannel=1' + '\n'
            transformationFile = destAlignmentFolder + shortName + '_ch1.txt'
            alignThisWindow = ch1WinStr
            applyAlignmentToThisWindow = ch2WinStr
        else:
            infoStr += 'AlignOnChannel=2' + '\n'
            transformationFile = destAlignmentFolder + shortName + '_ch2.txt'
            alignThisWindow = ch2WinStr
            applyAlignmentToThisWindow = ch1WinStr

        alignThisImp = WindowManager.getImage(alignThisWindow)
        #snap to middle slice
        if gAlignOnMiddleSlice:
            middleSlice = int(
                math.floor(alignThisImp.getNSlices() /
                           2))  #int() is necc., python is f*****g picky
        else:
            middleSlice = gAlignOnThisSlice
        alignThisImp.setSlice(middleSlice)

        infoStr += 'AlignOnSlice=' + str(middleSlice) + '\n'

        bPrintLog('MultiStackReg aligning:' + alignThisWindow, 1)
        stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' % (
            alignThisWindow, transformationFile)
        IJ.run('MultiStackReg', stackRegParams)

        #apply alignment to other window
        bPrintLog(
            'MultiStackReg applying alignment to:' +
            applyAlignmentToThisWindow, 1)
        applyAlignThisImp = WindowManager.getImage(applyAlignmentToThisWindow)
        stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' % (
            applyAlignmentToThisWindow, transformationFile)
        IJ.run('MultiStackReg', stackRegParams)
    elif gDoAlign:
        bPrintLog('Skipping alignment, there may be only one slice?', 3)

    #
    # save
    if gNumChannels == 1:
        imp.setProperty("Info", infoStr)
        impFile = destFolder + shortName + '.tif'
        #bPrintLog('Saving:' + impFile, 1)
        bSaveStack(imp, impFile)
        #max project
        bSaveZProject(imp, destMaxFolder, shortName)

    if gNumChannels == 2:
        #ch1
        ch1Imp.setProperty("Info", infoStr)
        #bPrintLog('Saving:' + ch1File, 1)
        bSaveStack(ch1Imp, ch1File)
        #max project
        bSaveZProject(ch1Imp, destMaxFolder, shortName + '_ch1')

        #ch2
        ch2Imp.setProperty("Info", infoStr)
        #bPrintLog('Saving:' + ch2File, 1)
        bSaveStack(ch2Imp, ch2File)
        #max project
        bSaveZProject(ch2Imp, destMaxFolder, shortName + '_ch2')

#
    # post convert to 8-bit and save
    if gSave8bit:
        if bitDepth == 16:
            if gNumChannels == 1:
                bPrintLog('Converting to 8-bit:' + impWinStr, 1)
                IJ.selectWindow(impWinStr)
                #IJ.run('resetMinAndMax()')
                IJ.run("8-bit")
                impFile = eightBitFolder + shortName + '.tif'
                bPrintLog('Saving 8-bit:' + impFile, 2)
                bSaveStack(imp, impFile)
                #max project
                bSaveZProject(imp, eightBitMaxFolder, shortName)

            if gNumChannels == 2:
                #
                bPrintLog('Converting to 8-bit:' + ch1WinStr, 1)
                IJ.selectWindow(ch1WinStr)
                #IJ.run('resetMinAndMax()')

                #ch1Imp.resetStack()
                #ch1Imp.resetDisplayRange()

                IJ.run("8-bit")
                impFile = eightBitFolder + shortName + '_ch1.tif'
                bPrintLog('Saving 8-bit:' + impFile, 2)
                bSaveStack(ch1Imp, impFile)
                #max project
                bSaveZProject(ch1Imp, eightBitMaxFolder, shortName + '_ch1')

                #
                bPrintLog('Converting to 8-bit:' + ch2WinStr, 1)
                IJ.selectWindow(ch2WinStr)
                #IJ.run('resetMinAndMax()')
                IJ.run("8-bit")
                impFile = eightBitFolder + shortName + '_ch2.tif'
                bPrintLog('Saving 8-bit:' + impFile, 2)
                bSaveStack(ch2Imp, impFile)
                #max project
                bSaveZProject(ch2Imp, eightBitMaxFolder, shortName + '_ch2')

    #
    # close original window
    imp.changes = 0
    imp.close()

    #
    # close ch1/ch2
    if 1 and gNumChannels == 2:
        ch1Imp.changes = 0
        ch1Imp.close()
        ch2Imp.changes = 0
        ch2Imp.close()

    bPrintLog(
        time.strftime("%H:%M:%S") + ' finished runOneFile(): ' + fullFilePath,
        1)
Ejemplo n.º 56
0
def runOneFile(fullFilePath):

	global gNumChannels
	
	if not os.path.isfile(fullFilePath):
		bPrintLog('\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n',0)
		return 0

	bPrintLog(time.strftime("%H:%M:%S") + ' starting runOneFile(): ' + fullFilePath, 1)
	
	enclosingPath = os.path.dirname(fullFilePath)
	head, tail = os.path.split(enclosingPath)
	enclosingPath += '/'
	
	#make output folders
	destFolder = enclosingPath + tail + '_channels/'
	if not os.path.isdir(destFolder):
		os.makedirs(destFolder)
	destMaxFolder = destFolder + 'max/'
	if not os.path.isdir(destMaxFolder):
		os.makedirs(destMaxFolder)

	if gDoAlign:
		destAlignmentFolder = destFolder + 'alignment/'
		if not os.path.isdir(destAlignmentFolder):
			os.makedirs(destAlignmentFolder)
			
	if gSave8bit:
		eightBitFolder = destFolder + 'channels8/'
		if not os.path.isdir(eightBitFolder):
			os.makedirs(eightBitFolder)
		eightBitMaxFolder = eightBitFolder + 'max/'
		if not os.path.isdir(eightBitMaxFolder):
			os.makedirs(eightBitMaxFolder)
	
	# open image
	imp = Opener().openImage(fullFilePath)

	# get parameters of image
	(width, height, nChannels, nSlices, nFrames) = imp.getDimensions()
	bitDepth = imp.getBitDepth()
	infoStr = imp.getProperty("Info") #get all .tif tags
	if not infoStr:
		infoStr = ''
		
	msgStr = 'w:' + str(width) + ' h:' + str(height) + ' slices:' + str(nSlices) \
				+ ' channels:' + str(nChannels) + ' frames:' + str(nFrames) + ' bitDepth:' + str(bitDepth)
	bPrintLog(msgStr, 1)
	
	path, filename = os.path.split(fullFilePath)
	shortName, fileExtension = os.path.splitext(filename)

	#this is too much work for ScanImage4
	#try and guess channels if it is a scanimage file
	#scanImage3 = string.find(infoStr, 'scanimage') != -1
	#scanimage4 = find(infoStr, 'scanimage.SI4.channelSave = ')
	#print 'scanimage4:', scanimage4
	
	#
	# look for num channels in ScanImage infoStr
	if gGetNumChanFromScanImage:
		for line in infoStr.split('\n'):
			#scanimage.SI4.channelsSave = [1;2]
			scanimage4 = find(line, 'scanimage.SI4.channelsSave =') == 0
			#state.acq.numberOfChannelsSave=2
			scanimage3 = find(line, 'state.acq.numberOfChannelsSave=') == 0
			if scanimage3:
				#print 'line:', line
				equalIdx = find(line, '=')
				line2 = line[equalIdx+1:]
				if gGetNumChanFromScanImage:
					gNumChannels = int(line2)
					bPrintLog('over-riding gNumChannels with: ' + str(gNumChannels), 2)
			if scanimage4:
				#print '   we have a scanimage 4 file ... now i need to exptract the number of channel'
				#print 'line:', line
				equalIdx = find(line, '=')
				line2 = line[equalIdx+1:]
				for delim in ';[]':
					line2 = line2.replace(delim, ' ')
				if gGetNumChanFromScanImage:
					gNumChannels = len(line2.split())
					bPrintLog('over-riding gNumChannels with: ' + str(gNumChannels), 2)

	# show
	imp.show()

	infoStr += 'bAlignBatch6=' + time.strftime("%Y%m%d") + '\n'
	#
	# crop
	if gDoCrop:
		bPrintLog('making cropping rectangle (left,top,width,height) ',1)
		bPrintLog(str(gCropLeft) + ' ' + str(gCropTop) + ' ' +str(gCropWidth) + ' ' +str(gCropHeight), 2)
		roi = Roi(gCropLeft, gCropTop, gCropWidth, gCropHeight) #left,top,width,height
		imp.setRoi(roi)
		
		#time.sleep(1)
		
		#bPrintLog('cropping', 1)
		IJ.run('Crop')
		infoStr += 'cropping=' + str(gCropLeft) + ',' + str(gCropTop) + ',' + str(gCropWidth) + ',' + str(gCropHeight) + '\n'
	
	#
	# remove negative (<0) pixel values
	#ip = imp.getProcessor()
	#pixels = ip.getPixels()  # this returns a reference (not a copy)
	#for i in xrange(len(pixels)):  
	#	if pixels[i] < 0:  
	#		pixels[i] = 0
	# or this, for each pixel 'x', if  x<0 then 0 else x
	#pixels = map(lambda x: 0 if x<0 else x, pixels)
	
	#set our new values (without pixels <0) back into original (I hope this handles stacks and channels???)
	#ip.setPixels(pixels)
	
	#
	# remove calibration
	if gRemoveCalibration:
		cal = imp.getCalibration()
		calCoeff = cal.getCoefficients()
		if calCoeff:
			msgStr = 'Calibration is y=a+bx' + ' a=' + str(calCoeff[0]) + ' b=' + str(calCoeff[1])
			bPrintLog(msgStr, 1)
			
			#remove calibration
			bPrintLog('\tRemoving Calibration', 2)
			imp.setCalibration(None)
				
			#get and print out min/max
			origMin = StackStatistics(imp).min
			origMax = StackStatistics(imp).max
			msgStr = '\torig min=' + str(origMin) + ' max=' + str(origMax)
			bPrintLog(msgStr, 2)
			
			#msgStr = 'adding calCoeff[0]='+str(calCoeff[0]) + ' to stack.'
			#bPrintLog(msgStr, 2)
			#subArgVal = 'value=%s stack' % (calCoeff[0],)
			#IJ.run('Add...', subArgVal)

			# 20150701, 'shift everybody over by linear calibration intercept calCoeff[0]'
			if 1:
				# [1] was this
				#msgStr = 'Subtracting original min '+str(origMin) + ' from stack.'
				#bPrintLog(msgStr, 2)
				#subArgVal = 'value=%s stack' % (origMin,)
				#IJ.run('Subtract...', subArgVal)
				# [2] now this
				#msgStr = 'Adding calCoeff[0] '+str(calCoeff[0]) + ' from stack.'
				#bPrintLog(msgStr, 2)
				#addArgVal = 'value=%s stack' % (int(calCoeff[0]),)
				#IJ.run('Add...', addArgVal)
				# [3] subtract a magic number 2^15-2^7 = 32768 - 128
				magicNumber = 32768 - 128
				msgStr = 'Subtracting a magic number '+str(magicNumber) + ' from stack.'
				bPrintLog(msgStr, 2)
				subArgVal = 'value=%s stack' % (origMin,)
				IJ.run('Subtract...', subArgVal)
				
			# 20150701, set any pixel <0 to 0
			if 0:
				ip = imp.getProcessor() # returns a reference
				pixels = ip.getPixels() # returns a reference
				msgStr = '\tSet all pixels <0 to 0. This was added 20150701 ...'
				bPrintLog(msgStr, 2)
				pixels = map(lambda x: 0 if x<0 else x, pixels)
				bPrintLog('\t\t... done', 2)
				
			#get and print out min/max
			newMin = StackStatistics(imp).min
			newMax = StackStatistics(imp).max
			msgStr = '\tnew min=' + str(newMin) + ' max=' + str(newMax)
			bPrintLog(msgStr, 2)
			
			#without these, 8-bit conversion goes to all 0 !!! what the f**k !!!
			#bPrintLog('calling imp.resetStack() and imp.resetDisplayRange()', 2)
			imp.resetStack()
			imp.resetDisplayRange()

			#append calibration to info string
			infoStr += 'calibCoeff_a = ' + str(calCoeff[0]) + '\n'
			infoStr += 'calibCoeff_b = ' + str(calCoeff[1]) + '\n'
			infoStr += 'origMin = ' + str(origMin) + '\n'
			infoStr += 'origMax = ' + str(origMax) + '\n'

	#
	# set up
	if gNumChannels == 1:
		impWinStr = imp.getTitle() #use this when only one channel
		impWin = WindowManager.getWindow(impWinStr) #returns java.awt.Window
	
	if gNumChannels == 2:
		winTitle = imp.getTitle()
		bPrintLog('Deinterleaving 2 channels...', 1)
		IJ.run('Deinterleave', 'how=2 keep') #makes ' #1' and ' #2', with ' #2' frontmost
		ch1WinStr = winTitle + ' #1'
		ch2WinStr = winTitle + ' #2'
		ch1Imp = WindowManager.getImage(ch1WinStr)
		ch2Imp = WindowManager.getImage(ch2WinStr)
		ch1File = destFolder + shortName + '_ch1.tif'
		ch2File = destFolder + shortName + '_ch2.tif'
		
	#
	# alignment
	if gDoAlign and gNumChannels == 1 and imp.getNSlices()>1:
		infoStr += 'AlignOnChannel=1' + '\n'
		#snap to middle slice
		if gAlignOnMiddleSlice:
			middleSlice = int(math.floor(imp.getNSlices() / 2)) #int() is necc., python is f*****g picky
		else:
			middleSlice = gAlignOnThisSlice
		imp.setSlice(middleSlice)
		
		transformationFile = destAlignmentFolder + shortName + '.txt'
		
		bPrintLog('MultiStackReg aligning:' + impWinStr, 1)
		stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' %(impWin,transformationFile)
		IJ.run('MultiStackReg', stackRegParams)
		infoStr += 'AlignOnSlice=' + str(middleSlice) + '\n'
	if gDoAlign and gNumChannels == 2 and ch1Imp.getNSlices()>1 and ch2Imp.getNSlices()>1:
		#apply to gAlignThisChannel
		alignThisWindow = ''
		applyAlignmentToThisWindow = ''
		if gAlignThisChannel == 1:
			infoStr += 'AlignOnChannel=1' + '\n'
			transformationFile = destAlignmentFolder + shortName + '_ch1.txt'
			alignThisWindow = ch1WinStr
			applyAlignmentToThisWindow = ch2WinStr
		else:
			infoStr += 'AlignOnChannel=2' + '\n'
			transformationFile = destAlignmentFolder + shortName + '_ch2.txt'
			alignThisWindow = ch2WinStr
			applyAlignmentToThisWindow = ch1WinStr
	
		alignThisImp = WindowManager.getImage(alignThisWindow)
		#snap to middle slice
		if gAlignOnMiddleSlice:
			middleSlice = int(math.floor(alignThisImp.getNSlices() / 2)) #int() is necc., python is f*****g picky
		else:
			middleSlice = gAlignOnThisSlice
		alignThisImp.setSlice(middleSlice)

		infoStr += 'AlignOnSlice=' + str(middleSlice) + '\n'
		
		bPrintLog('MultiStackReg aligning:' + alignThisWindow, 1)
		stackRegParams = 'stack_1=[%s] action_1=Align file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body] save' %(alignThisWindow,transformationFile)
		IJ.run('MultiStackReg', stackRegParams)
	
		#apply alignment to other window
		bPrintLog('MultiStackReg applying alignment to:' + applyAlignmentToThisWindow, 1)
		applyAlignThisImp = WindowManager.getImage(applyAlignmentToThisWindow)
		stackRegParams = 'stack_1=[%s] action_1=[Load Transformation File] file_1=[%s] stack_2=None action_2=Ignore file_2=[] transformation=[Rigid Body]' %(applyAlignmentToThisWindow,transformationFile)
		IJ.run('MultiStackReg', stackRegParams)		
	elif gDoAlign:
		bPrintLog('Skipping alignment, there may be only one slice?',3)
						
	#
	# save
	if gNumChannels == 1:
		imp.setProperty("Info", infoStr);
		impFile = destFolder + shortName + '.tif'
		#bPrintLog('Saving:' + impFile, 1)
		bSaveStack(imp, impFile)
		#max project
		bSaveZProject(imp, destMaxFolder, shortName)

	if gNumChannels == 2:
		#ch1
		ch1Imp.setProperty("Info", infoStr);
		#bPrintLog('Saving:' + ch1File, 1)
		bSaveStack(ch1Imp, ch1File)
		#max project
		bSaveZProject(ch1Imp, destMaxFolder, shortName+'_ch1')

		#ch2
		ch2Imp.setProperty("Info", infoStr);
		#bPrintLog('Saving:' + ch2File, 1)
		bSaveStack(ch2Imp, ch2File)
 		#max project
		bSaveZProject(ch2Imp, destMaxFolder, shortName+'_ch2')
		
 	#
	# post convert to 8-bit and save
	if gSave8bit:
		if bitDepth == 16:
			if gNumChannels == 1:
				bPrintLog('Converting to 8-bit:' + impWinStr, 1)
				IJ.selectWindow(impWinStr)
				#IJ.run('resetMinAndMax()')
				IJ.run("8-bit")
				impFile = eightBitFolder + shortName + '.tif'
				bPrintLog('Saving 8-bit:' + impFile, 2)
				bSaveStack(imp, impFile)
				#max project
				bSaveZProject(imp, eightBitMaxFolder, shortName)
				
			if gNumChannels == 2:
				#
				bPrintLog('Converting to 8-bit:' + ch1WinStr, 1)
				IJ.selectWindow(ch1WinStr)
				#IJ.run('resetMinAndMax()')
				
				#ch1Imp.resetStack()
				#ch1Imp.resetDisplayRange()
				
				IJ.run("8-bit")
				impFile = eightBitFolder + shortName + '_ch1.tif'
				bPrintLog('Saving 8-bit:' + impFile, 2)
				bSaveStack(ch1Imp, impFile)
				#max project
				bSaveZProject(ch1Imp, eightBitMaxFolder, shortName+'_ch1')

				#
				bPrintLog('Converting to 8-bit:' + ch2WinStr, 1)
				IJ.selectWindow(ch2WinStr)
				#IJ.run('resetMinAndMax()')
				IJ.run("8-bit")
 				impFile = eightBitFolder + shortName + '_ch2.tif'
				bPrintLog('Saving 8-bit:' + impFile, 2)
				bSaveStack(ch2Imp, impFile)
				#max project
				bSaveZProject(ch2Imp, eightBitMaxFolder, shortName+'_ch2')
				
	#
	# close original window
	imp.changes = 0
	imp.close()

	#
	# close ch1/ch2
	if 1 and gNumChannels == 2:
		ch1Imp.changes = 0
		ch1Imp.close()
		ch2Imp.changes = 0
		ch2Imp.close()

	bPrintLog(time.strftime("%H:%M:%S") + ' finished runOneFile(): ' + fullFilePath, 1)
Ejemplo n.º 57
0
	def __settings(self, imgName) :
		"""
		Lets the user to choose different measures to make, and displays it following the choice of the user.
		
		"""

		try : dico=self.__dictCells[imgName]
		except KeyError : 
			try : dico=self.__dictCells[imgName[:-4]]
			except KeyError : return False
			else : imgName=imgName[:-4]
		
		dico=self.__dictCells[imgName]
		for cellname in dico.keys() :
			self.__dictMeasures[dico[cellname]]={}
			
		# Represents the datas on a diagram
		def diagrambuttonPressed(event) :
			IJ.showMessage("Push 'Auto' button each time you want to see the diagram")
			x1=10
			y1=20
			x2=100
			y2=50
			x3=60
			y3=30
			xr=10
			yr=20
			wr=20
			hr=20

			
			rect=Rectangle(xr,yr,wr,hr)
			
			#img=IJ.getImage()
			#nbslices=self.__img.getImageStackSize()
			nbslices=self.__maxLife
			IJ.run("Hyperstack...", "title=Diagram type=32-bit display=Color width="+str(x2+(nbslices+1)*x3)+" height="+str(y2+y3*len(dico))+" channels=1 slices="+str(len(self.__measures))+" frames=1")
			im=IJ.getImage()
			ip=im.getProcessor()
			for i in range(len(self.__measures)) :
				indiceligne=0
				maxvalue=0
				minvalue=1000000
				im.setPosition(1,i+1,1)
				for cellname in self.__listcellname :
					indiceligne+=1
					for indicecolonne in range(1,nbslices+1):
						rect.setLocation(x2+indicecolonne*x3+int(x3/6),(y1+indiceligne*y3-int(y3/2)))
						# we create at the first iteration a dictionary with the rectangles (for a future use)
						if i==0 :
							self.__gridrectangle[(indiceligne,indicecolonne)]=Rectangle(rect)
						im.setRoi(rect)
						ipr=im.getProcessor()
						# we find the min and max values of the datas for a measure given.
						if self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]>maxvalue :
							maxvalue=self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]
						if self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]<minvalue :
							minvalue=self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1]
						# we fill the rectangle with the value of the measure
						ipr.setValue(self.__dictMeasures[dico[cellname]][self.__measures[i]][indicecolonne-1])
						ipr.fill()
				# we write the names and the n of slices on the image with the maxvalue.
				ip.setValue(maxvalue)
				ip.moveTo(x1,y1)
				ip.drawString(self.__measures[i])
				for j in range(1,nbslices+1) :
					ip.moveTo(x2+j*x3,y1)
					ip.drawString("Slice "+str(j))
				j=0
				for cellname in self.__listcellname :
					ip.moveTo(x1,y2+j*y3)
					ip.drawString(cellname)
					j+=1
			im.killRoi()
			im=IJ.run(im,"Fire","")
			IJ.run("Brightness/Contrast...", "")
			#im.setMinAndMax(minvalue,maxvalue)
			#im.updateImage()
			
			#we add a mouse listener in order to be able to show the roi corresponding to a rectangle when the user clicks on it.
			listener = ML()
			listener.name=imgName
			for imp in map(WindowManager.getImage, WindowManager.getIDList()):
				if imp.getTitle().startswith("Diagram") : 
					win = imp.getWindow()
 					if win is None:
						continue
					win.getCanvas().addMouseListener(listener)
		
		# Represents the datas on a series of graphs.
		def graphbuttonPressed(event) :
			
			colors=[]
			#img=IJ.getImage()
			#nbslices=self.__img.getImageStackSize()
			nbslices=self.__maxLife

			acell=dico.values()[0]
			if self.__useTime : 
				x = acell.getListTimes()
				namex="Time sec"
			else : 
				x = range(1,nbslices+1)
				namex = "Frame"
			maxx=max(x)
			minx=min(x)
			
			#x=[i for i in range(1,nbslices+1)]
			font=Font("new", Font.BOLD, 14)
			tempname = WindowManager.getUniqueName(self.__img.getShortTitle())
			for i in range(len(self.__measures)) :
				#print "i", i, self.__measures[i]
				yarray=[]
				flag=True
				miny=10000000000
				maxy=-1000000000
				#we find the min and max values in order to set the scale.
				for cellname in self.__listcellname :	
					colors.append(dico[cellname].getColor())
					yarray.append(self.__dictMeasures[dico[cellname]][self.__measures[i]])
					#for meas in self.__dictMeasures[dico[cellname]][self.__measures[i]] :
					for meas in yarray[-1] :
						if (meas<miny) and (Double.isNaN(meas)==False) :
							miny=meas
					if max(yarray[-1])>maxy : maxy=max(yarray[-1])
				
				miny-=0.1*miny
				maxy+=0.1*maxy
				count=0.05
				
				for j in range(len(yarray)) :
					if j==0 :
						if len(self.__measures)>1 :
							plot=Plot("Plots-"+str(self.__measures[i]),namex,str(self.__measures[i]),x,yarray[j])
							
						else : 
							plot=Plot("Plot-"+tempname,namex,str(self.__measures[i]),x,yarray[j])
							
						plot.setLimits(minx,maxx,miny,maxy)
						plot.setColor(colors[j])
						plot.changeFont(font)
						plot.addLabel(0.05, count, self.__listcellname[j])
					else :
						plot.setColor(colors[j])
						plot.setLineWidth(3)
						plot.addPoints(x,yarray[j],Plot.LINE)
						plot.addLabel(0.05, count, self.__listcellname[j])

					count+=0.05
						
				plot.setColor(colors[0])
				plot.show()
				
			if len(self.__measures)>1 :
				IJ.run("Images to Stack", "name="+tempname+"-plots title=Plots- use")

		#def histbuttonPressed(event) :
		#	
		#	pass

		# Represents the values in a tab.
		def tabbuttonPressed(event) :
		
			tab="\t"
			headings=[]
			measures=[]
			#img=IJ.getImage()
			#for i in range(self.__img.getImageStackSize()+1) :
			for i in range(self.__maxLife+1) :
				headings.append("Slice "+str(i))
			
			headings[0]=WindowManager.getUniqueName(self.__img.getShortTitle())
			#for m in self.__measurescompl :
			for m in self.__dictMeasures[dico[self.__listcellname[0]]].keys() :
				
				headstring=""
				for head in headings: 
					headstring+=head+tab
				tw=TextWindow(self.__listfiles[0]+"-"+m,headstring,"",800,600)
				tp=tw.getTextPanel()
				#for cellname in dico.keys() :
				for cellname in self.__listcellname :
					line=[]
					line=[str(meas)+tab for meas in self.__dictMeasures[dico[cellname]][m]]
					line.insert(0, cellname+tab)
					linestr=""
					for s in line: linestr+=s
					tp.appendLine(linestr)
				tp.updateDisplay()

			if self.__measuresparambool_global[0] :
				tw=TextWindow("Latency","cell\tLatency", "",800,600)
				tp=tw.getTextPanel()
				for i in range(len(self.__listcellname)) :
					#if latencies[i][0] : line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					#else : line=self.__listcellname[i]+"\t"+"NaN"
					line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					tp.appendLine(line)
				tp.updateDisplay() 
				
		def helpbuttonPressed(event) :

			IJ.showMessage("TO DO")

		def newsetPressed(event) :
			gd0.dispose()
			self.__settings()

		def alignbuttonPressed(event) :
			IJ.showMessage("TO DO")


		def mergebuttonPressed(event) :
			IJ.showMessage("TO DO")

		def saveResults() :
			
			#if len(self.__listcellname) == 0 :
			
			nbslices=self.__maxLife
			acell=dico.values()[0]
			if self.__useTime : 
				x = acell.getListTimes()
				namex="Time_sec"
			else : 
				x = range(1,nbslices+1)
				namex = "Frame"
							
			if not path.exists(self.__rootpath+"Results"+os.path.sep) : os.makedirs(self.__rootpath+os.path.sep+"Results"+os.path.sep, mode=0777)
			tab="\t"
			nl="\n"
			measures=[]
			headstring=""
			#if self.__savemode : mode = "a"
			#else : mode ="w"
			mode = "a"
			
			#for i in range(1, self.__maxLife+1) :headstring += "Slice_"+str(i)+tab
			for i in range(self.__maxLife) :headstring += str(x[i])+tab
			
			#for m in self.__measurescompl :
			for m in self.__dictMeasures[dico[self.__listcellname[0]]].keys() :
				f = open(self.__rootpath+"Results"+os.path.sep+m+".txt", mode)
				#f.write(m+nl)
				f.write(imgName+"-"+self.__time+"-"+m+"-"+namex+tab+headstring+nl)
				if len(self.__listcellname) == 0 : f.write("no cells")
				else : 
					for cellname in self.__listcellname :
						linestr=cellname+tab
						for measure in self.__dictMeasures[dico[cellname]][m] :
							#print m, cellname, measure 
							linestr += str(measure)+tab
						linestr+=nl
						f.write(linestr)
				f.close()

			if self.__measuresparambool_global[0] :
				m = "Latency"
				f = open(self.__rootpath+"Results"+os.path.sep+m+".txt", mode)
				f.write(imgName+"-"+self.__time+"-"+m+nl)
				for i in range(len(self.__listcellname)) :
					#if latencies[i][0] : line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					#else : line=self.__listcellname[i]+"\t"+"NaN"
					line=self.__listcellname[i]+"\t"+str(latencies[i][1])
					line+=nl
					f.write(line)
				f.close()
				
			

			

		#
		# ----------- main measures dialog -------------------------
		#
     		# Allows the user to choose the measures to make, etc..
		
		measureslabels_indep=["MaxFeret","MinFeret","AngleFeret","XFeret","YFeret","Area","Angle","Major","Minor","Solidity","AR","Round","Circ","XC","YC","FerCoord","FerAxis","MidAxis"]
		measureslabels_dep=["Mean","StdDev","IntDen","Kurt","Skew","XM","YM","Fprofil","MidProfil","NFoci","ListFoci","ListAreaFoci","ListPeaksFoci","ListMeanFoci"]
		measureslabels_global=["Latency", "velocity", "cumulatedDist"]
		measureslabels_dep_tabonly=set(["MidAxis","FerCoord","FerAxis","Fprofil","MidProfil","ListFoci","ListAreaFoci","ListPeaksFoci","ListMeanFoci"])
		ens_measures_global=set(measureslabels_global)
		ens_measures_indep=set(measureslabels_indep)
		ens_measures_dep=set(measureslabels_dep)
		measureslabels=[]
		
		for label in measureslabels_indep :
			measureslabels.append(label)

		for label in measureslabels_dep :
			measureslabels.append(label)

		#self.__defaultmeasures=[False for i in range(len(measureslabels))]
		#self.__defaultmeasures_global=[False for i in range(len(measureslabels_global))]

		gdmeasures=NonBlockingGenericDialog("MeasuresChoice")
		gdmeasures.setFont(Font("Courrier", 1, 10))
		gdmeasures.addMessage("*******     TIME SETTINGS     *******")
		gdmeasures.addCheckbox("Only starting at begining  :", self.__onlystart)				# 1 only start
		gdmeasures.addNumericField("Minimal Lifetime  : ",self.__minLife,0)
		gdmeasures.addNumericField("Maximal Lifetime  : ",self.__maxLife,0)
		#gdmeasures.addNumericField("Maximal Lifetime  : ",self.__img.getImageStackSize(),0)
		gdmeasures.addCheckbox("x axis in seconds", self.__useTime)				# 2 use time
		gdmeasures.addMessage("")
		gdmeasures.addMessage("")
		gdmeasures.addMessage("Choose the measures to make on the cells : ")			
		gdmeasures.addMessage("*******     TIME MEASURES     *******")
		gdmeasures.addCheckboxGroup(4,8,measureslabels,self.__defaultmeasures)
		gdmeasures.addMessage("")
		gdmeasures.addMessage("*******     GLOBAL MEASURES     *******")
		gdmeasures.addMessage("PLEASE : If you have selected movement parameters you MUST to select XC and YC !")
		gdmeasures.addCheckboxGroup(3,1,measureslabels_global,self.__defaultmeasures_global)
		gdmeasures.addNumericField("Noise value for maxima finder: ",self.__noise,0)
		gdmeasures.addMessage("")	
		gdmeasures.addMessage("*******     OPTIONS     *******")
		gdmeasures.addCheckbox("Select the cells in next dialog ?", self.__onlyselect)			# 3 only select
		gdmeasures.addCheckbox("Save results to text files ?", self.__savetables)			# 4 save files
		#gdmeasures.addCheckbox("Append mode ?", self.__savemode)					# 5 append mode
		gdmeasures.addCheckbox("Analyse in batch mode ?", self.__batchanalyse)				# 6 analysis batch mode
		gdmeasures.addCheckbox("Update overlay ?", self.__updateoverlay)				# 7 update overlay
		gdmeasures.addMessage("")
		gdmeasures.addMessage("")
		help_panel=Panel()
		helpbutton=Button("HELP")
		helpbutton.actionPerformed = helpbuttonPressed
		help_panel.add(helpbutton)	
		gdmeasures.addPanel(help_panel)	
		gdmeasures.hideCancelButton()

		if not self.__batchanalyse :
			gdmeasures.showDialog()
			self.__onlystart=gdmeasures.getNextBoolean() 						# 1 only start
			self.__minLife=gdmeasures.getNextNumber()
			self.__maxLife=gdmeasures.getNextNumber()
			self.__useTime=gdmeasures.getNextBoolean()						# 2 use time

			self.__measuresparambool=[]
			self.__measuresparambool_global=[]
			for i in range(len(measureslabels)) : 
				self.__measuresparambool.append(gdmeasures.getNextBoolean())
				self.__defaultmeasures[i]=self.__measuresparambool[-1]
			for i in range(len(measureslabels_global)) : 
				self.__measuresparambool_global.append(gdmeasures.getNextBoolean())
				self.__defaultmeasures_global[i] = self.__measuresparambool_global[i]
 
			self.__noise=gdmeasures.getNextNumber()
			self.__onlyselect=gdmeasures.getNextBoolean()						# 3 only select
			self.__savetables = gdmeasures.getNextBoolean()						# 4 save files
			#self.__savemode = gdmeasures.getNextBoolean()						# 5 append mode
			self.__batchanalyse = gdmeasures.getNextBoolean()					# 6 analyse mode
			self.__updateoverlay = gdmeasures.getNextBoolean()					# 7 update overlay

		# we update a list of all cells that have a lifetime corresponding to what the user chose.
		if len (self.__allcells) == 0 :
			for cellname in dico.keys() :
				if dico[cellname].getLifeTime()>=self.__minLife : #and dico[cellname].getLifeTime()<=self.__maxLife :
					if self.__onlystart :
						if dico[cellname].getSlideInit()<2 : self.__allcells.append(cellname)
						else : self.__allcells.append(cellname)

		
		if self.__noise == 0 : self.__noise = None
		if self.__batchanalyse : self.__onlyselect = False
		
		if self.__onlyselect : 
			
			try : 
				self.__gw
			except AttributeError :
				if not path.exists(self.__pathdir+"Selected-Cells"+os.path.sep) : os.makedirs(self.__pathdir+os.path.sep+"Selected-Cells"+os.path.sep, mode=0777)				
				self.__gw = CellsSelection()
				self.__gw.setTitle(imgName)
				self.__gw.run(self.__allcells, self.__pathdir+"ROIs"+os.path.sep)
				self.__gw.show()
				self.__gw.setSelected(self.__allcells)
				while not self.__gw.oked and self.__gw.isShowing() : 
					self.__gw.setLabel("Validate selection with OK !!")
					self.__listcellname = list(self.__gw.getSelected())
				self.__gw.resetok()
				self.__gw.setLabel("...")
				self.__gw.hide()
			else : 
				if self.__gw.getTitle() == imgName :
					self.__gw.show()
					self.__gw.setSelected(self.__listcellname)
					self.__listcellname[:]=[]
					while not self.__gw.oked and self.__gw.isShowing() : 
						self.__gw.setLabel("Validate selection with OK !!")
						self.__listcellname = list(self.__gw.getSelected())
					
					self.__gw.resetok()
					self.__gw.setLabel("...")
					self.__gw.hide()

				else : 
					self.__gw.dispose()
					if not path.exists(self.__pathdir+"Selected-Cells"+os.path.sep) : os.makedirs(self.__pathdir+os.path.sep+"Selected-Cells"+os.path.sep, mode=0777)				
					self.__gw = CellsSelection()
					self.__gw.setTitle(imgName)
					self.__gw.run(self.__allcells, self.__pathdir+"ROIs"+os.path.sep)
					self.__gw.show()
					self.__gw.setSelected(self.__allcells)
					self.__listcellname[:]=[]
					while not self.__gw.oked and self.__gw.isShowing() : 
						self.__gw.setLabel("Validate selection with OK !!")
						self.__listcellname = list(self.__gw.getSelected())
					self.__gw.resetok()
					self.__gw.setLabel("...")
					self.__gw.hide()

			filestodelet=glob.glob(self.__pathdir+"Selected-Cells"+os.path.sep+"*.cell")
			for f in filestodelet : os.remove(f)
			for cell in self.__listcellname :
				sourcestr = self.__pathdir+"Cells"+os.path.sep+cell+".cell"
				deststr =  self.__pathdir+"Selected-Cells"+os.path.sep+cell+".cell"
				#os.system("copy "+sourcestr+", "+deststr) 
				#shutil.copy(self.__pathdir+"Cells"+os.path.sep+cell+".cell",self.__pathdir+"Selected-Cells"+os.path.sep+cell+".cell")
				shutil.copy(sourcestr,deststr)

			self.__dictNcells[imgName] = len(self.__listcellname)
		
		else : 
			self.__listcellname = list(self.__allcells)
			self.__dictNcells[imgName] = len(self.__listcellname)

		if len(self.__listcellname) == 0 : 
			self.__dictNcells[imgName] = 0
			return False
		
		self.__img.hide()
		
		# we make the measures.
		for i in range(len(measureslabels)) :
			IJ.showProgress(i, len(measureslabels))
			if  self.__measuresparambool[i]==True :
				
				self.__measurescompl.append(measureslabels[i])
				
				if (measureslabels[i] in measureslabels_dep_tabonly)==False :
					self.__measures.append(measureslabels[i])
				
				if (i<18) and (measureslabels[i] in ens_measures_indep) :
					self.__measureAll(self.__img,measureslabels[i],False, imgName, self.__noise)
					ens_measures_indep.discard(measureslabels[i])
					
				if i>=18 :
					self.__measureAll(self.__img,measureslabels[i],True, imgName, self.__noise)
					
		if self.__measuresparambool_global[0] : # calculate latency
			latencies=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				latencies.append(self.latencie(self.__listcellname[i], self.__img, imgName, self.__useTime))

		if self.__measuresparambool_global[1] : # calculate velocity
			self.__measures.append("velocity")
			#velocities=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				self.__measureVelocity(self.__img,imgName)

		if self.__measuresparambool_global[2] : # calculate cumulatedDistance
			self.__measures.append("cumulatedDist")
			#velocities=[]
			for i in range(len(self.__listcellname)) : 
				IJ.showProgress(i, len(self.__listcellname))
				self.__measurecumulDist(self.__img,imgName)	
				
		
		self.__img.show()

		self.__img.getProcessor().resetThreshold()		

		
		if self.__updateoverlay :
			if self.__img.getOverlay() is not None : self.__img.getOverlay().clear()
		
			outputrois=[]
			cellnames=[]
			self.__img.hide()
			for cellname in self.__listcellname :
				
				for r in dico[cellname].getListRoi():
					if isinstance(r,Roi) : 
						pos=r.getPosition()
						#print "MC overlay", cellname, r.getName(), pos
						#r.setPosition(0)
						#overlay.add(r)
						outputrois.append(r)
						if "cell" in r.getName() : cellnames.append(r.getName())
						else : cellnames.append(str(pos)+"-"+cellname)
						#print cellnames[-1]

			rm = RoiManager.getInstance()
			if (rm==None): rm = RoiManager()
			rm.show()
			self.__img.show()
			IJ.selectWindow(self.__img.getTitle())
			rm.runCommand("reset")
			for i in range(len(outputrois)) :
				outputrois[i].setName(cellnames[i])
				rm.addRoi(outputrois[i])
				rm.select(rm.getCount()-1)
				rm.runCommand("Rename", cellnames[i])
			
			IJ.run("Show Overlay", "")
			rm.runCommand("UseNames", "true")
			rm.runCommand("Associate", "true")
			IJ.run(self.__img, "Labels...", "color=red font=12 show use")
			IJ.run(self.__img, "From ROI Manager", "")
			rm.runCommand("Show None")
			rm.runCommand("Show All")


		# ----------- batch analyse ------------------------
		if self.__batchanalyse :
			if self.__savetables :  saveResults()
			self.__dictMeasures.clear()
     			self.__allcells[:]=[]
     			self.__measurescompl[:]=[]
     			self.__measures[:]=[] 
			return False
			
		# ---------- display methodes dialog ----------------
		# Allows the user to choose how to see the results of the measures.		
		
		gd0=NonBlockingGenericDialog("Display")

		gd0.addMessage("How do you want to see the results ?")
		
		panel0=Panel()
		
		diagrambutton=Button("Diagram")
		diagrambutton.actionPerformed = diagrambuttonPressed
		panel0.add(diagrambutton)

		graphbutton=Button("Graph")
		graphbutton.actionPerformed = graphbuttonPressed
		panel0.add(graphbutton)

		tabbutton=Button("Tab")
		tabbutton.actionPerformed = tabbuttonPressed
		panel0.add(tabbutton)
		gd0.addPanel(panel0)
		gd0.addCheckbox("Analyse next stack ?", self.__nextstack)
		gd0.hideCancelButton()	
		gd0.showDialog()

		self.__nextstack = gd0.getNextBoolean()

		# ---------- save tables ---------------------------
		if self.__savetables :  saveResults()
		
		# --------- re-start analysis -------------------
		
     		self.__dictMeasures.clear()
     		#self.__listcellname[:]=[]
     		self.__allcells[:]=[]
     		self.__measurescompl[:]=[]
     		self.__measures[:]=[]

     		if self.__nextstack : return False
     		else : return True
Ejemplo n.º 58
0
	x2  = list_x2[i] 	
	x2_aux = x2.duplicate()
	x2_aux.setTitle('x2_aux')
	#run("3D OC Options", "volume surface nb_of_obj._voxels nb_of_surf._voxels integrated_density mean_gray_value std_dev_gray_value median_gray_value minimum_gray_value maximum_gray_value centroid mean_distance_to_surface std_dev_distance_to_surface median_distance_to_surface centre_of_mass bounding_box show_masked_image_(redirection_requiered) dots_size=5 font_size=10 store_results_within_a_table_named_after_the_image_(macro_friendly) redirect_to=x1")
	arguments = "volume centroid bounding_box show_masked_image_(redirection_requiered) dots_size=5 font_size=10 store_results_within_a_table_named_after_the_image_(macro_friendly) redirect_to=x2_aux"
	IJ.run("3D OC Options", arguments)
	IJ.run(x2, "3D Objects Counter", "threshold=0 slice=0 min.=" + repr(p3DOCmin)+" max.=" + repr(p3DOCmax)+ " exclude_objects_on_edges objects statistics")
	#Obtengo la salida estadística de 3D Objects Counter
	title_x2 = x2.getTitle()
	winStats =WindowManager.getFrame("Statistics for "+title_x2)#tomo la ventana con las estadísticas generadas
	textStats = winStats.getTextPanel()#tomo el texto de la ventana
    textStats.saveAs( resultsFileStats )#Guardo externamente la tabla y luego la levanto con GetParameters( resultsFileStats )
	index, vox, X, Y, Z, Bx, By, Bz, B-width, B-height, B-depth = GetParameters( resultsFileStats )
	
	#guardo la mascara en list_x3
	IJ.selectWindow("Objects map of x2_"+repr(i))		
	img = IJ.getImage()
	mask = img.duplicate()#al cerrar la ventana img al final del ciclo for se borran los datos que contiene img aunque no se avisa de esto, por lo tanto si se quiere guardar alguna ventana abierta hay que guardar un duplicado para no tener problemas
	mask.setTitle('mask_'+repr(i))
	list_x3.append( mask )#almaceno la mascara en la lista correspondiente
	#cierro ventanas que no preciso
	x2_aux.close()	
	img.close()
	#


	
#SKELETONIZE
for i in range(stepNumber):	
	skeleton = list_x3[i].duplicate()	
	skeleton.setTitle('skeleton_'+repr(i))
				IJ.run("3D OC Options", params)
				params = ("threshold=" + str(intThreshold) + 
						" slice=1 min.=" + str(sizeThreshold) + " max.=24903680 objects surfaces statistics")
				IJ.redirectErrorMessages(True)
				IJ.run(dataImage, "3D Objects Counter", params)
				dataImage.changes = False
				dataImage.close()

				## Saves the results table, surfaces image output, and run configuration
				surfacesImage = WindowManager.getImage("Surface map of " + dataImage.getTitle())
				IJ.run(surfacesImage,"8-bit","")
				surfacesImage = make_image_binary(surfacesImage)
				IJ.saveAsTiff(surfacesImage,parentLSMFilePath + "_tiles/surfaces/C" + str(analysisChannel) + "-tile_" + str(tile) + ".tif")
				surfacesImage.close()
				objectsImage = WindowManager.getImage("Objects map of " + dataImage.getTitle())
				IJ.run(objectsImage,"8-bit","")
				objectsImage = make_image_binary(objectsImage)
				IJ.saveAsTiff(objectsImage,parentLSMFilePath + "_tiles/maps/C" + str(analysisChannel) + "-tile_" + str(tile) + ".tif")
				objectsImage.close()
				IJ.selectWindow("Results")
				IJ.saveAs("Results",parentLSMFilePath + "_tiles/objects/C" + str(analysisChannel) + "-tile_" + str(tile) + ".csv")
			
			configData = ("Parent LSM file: " + parentLSMFilePath + "\n" +
						"Analysis channel: " + str(analysisChannel) + "\n" +
						"Bleeding channel: " + str(bleedingChannel) + "\n" +
						"Refractive correction reference channel: " + str(refChannel) + "\n" +
						"Intensity threshold (0-255): " + str(intThreshold) + "\n" +
						"Size threshold (voxels): " + str(sizeThreshold) + "\n" +
						"Process filter: " + str(processFilter) + "\n" +
						"Tiles: " + ','.join([str(i) for i in tileList]))
			IJ.saveString(configData,parentLSMFilePath+"_tiles/objects/runData-C" + str(analysisChannel) + ".txt")
Ejemplo n.º 60
0
	def run(self) :
		
		nextstep=self.__mainsettings()					# step 1
		if nextstep : nextstep = self.__selectionSettings()		# step 2
		
		else : 
			IJ.showMessage("Bye...")
			return False
		
		if nextstep : nextstep = self.__runMethode()			# step 3
		else : 
			IJ.showMessage("Bye...")
			return False

		f = open(self.__pathdir+self.__time+"-listpaths.txt", "w")
		
		for i in range(len(self.__imagesnames)) :
			name = self.__imagesnames[i]
			if name[-4:]!=".tif" : name=name+".tif"
			if not self.__batch : IJ.showMessage("Analysis of stack : "+name)
			self.__pathdir = self.__listpaths[i]
			while nextstep :
				if len(self.__imagesnames) > 1 : self.__activeTitle = name
				if self.__batch : 
					self.__img=WindowManager.getImage(name)
					IJ.selectWindow(self.__img.getID())
					nextstep = True
				else : nextstep = self.__selectMeasureStack()		# step 4
					
				self.__maxLife = self.__img.getImageStackSize()
				if nextstep : nextstep = self.__settings(name)
				else : 
					IJ.showMessage("Bye...")
					return False
			nextstep=True

			try : self.__dictCells[name]
			except KeyError : 
				try : self.__dictCells[name[:-4]]
				except KeyError :
					try : self.__dictCells[name+".tif"]
					except KeyError :
						print "error" 
						continue
					else: 
						name = name+".tif"
						if self.__dictNcells[name] > 0 : 
							f.write(self.__listpaths[i]+"\n")
							continue
				else : 
					name = name[:-4]
					if self.__dictNcells[name] > 0 : 
						f.write(self.__listpaths[i]+"\n")
						continue
					
			if self.__dictNcells[name] > 0 : 
				f.write(self.__listpaths[i]+"\n")
				continue
		

		f.close()
		return True