def bPrintLog(text, indent=0):
	msgStr = ''
	for i in (range(indent)):
		msgStr += '    '
		print '   ',
	print text #to command line
	IJ.log(msgStr + text)
Esempio n. 2
0
def main():
    # Tricky hack to get ImagePlus from IJ1 interface
    img = IJ.getImage()
    display = DefaultLegacyService().getInstance().getImageMap().lookupDisplay(img)
    dataset = DefaultImageDisplayService().getActiveDataset(display)
    imp = dataset.getImgPlus()

    # I don't really understand why sometime SCIFIO is not used
    # When it's not, we can't access to getMetadata()
    if not isinstance(imp, SCIFIOImgPlus):
        IJ.showMessage("This image has not been opened with SCIFIO")
        return

    # Get metadata
    metadata = imp.getMetadata()

    # Why the f**k this is needed ?
    while isinstance(metadata, AbstractMetadataWrapper):
        metadata = metadata.unwrap()

    # Check if metadata are OME or not
    if isinstance(metadata, Metadata):
        omeMeta = metadata.getOmeMeta()
    else:
        IJ.showMessage("This file does not contain OME metadata")
        return

    # Get xml string and print it with spaces indentation
    xml_string = DefaultOMEXMLService().getOMEXML(omeMeta.getRoot())
    xml = dom.parseString(xml_string)
    xml_string = xml.toprettyxml(indent="  ")

    IJ.log(xml_string)
def DirList(baseDir):
	r = ImageReader()
	imgStats = {}
	for root, dirs, files in os.walk(str(baseDir)):
		for f1 in files:
			if f1.endswith(".jpg") or f1.endswith(".jpe") or f1.endswith(".jpeg"):
				id = root + "/" +  f1
				r.setId(id)
				if r is None:
					print "Couldn\'t open image from file:", id
					continue
				w = r.getSizeX()
				h = r.getSizeY()
				imgStats[str(w) + "_" + str(h)] = imgStats.get(str(w) + "_" + str(h), 0)+1
				IJ.log("Found image: " + str(id))
				#counter += 1
	r.close()
	#print summary
	summary = ''
	for k, v in imgStats.iteritems():
		dim = k.split("_")
		ratio = float(dim[0])/float(dim[1])
		IJ.log("Found " + str(v) + " images of dimension " + str(dim[0]) + "x" + str(dim[1]) + " apect ratio " + str(round(ratio, 2)))
		summary = summary + "\nFound " + str(v) + " images of dimension " + str(dim[0]) + "x" + str(dim[1]) + " apect ratio " + str(round(ratio, 2))
	return summary
Esempio n. 4
0
def compute_frame_translations(imp, channel, frames = None):
	""" imp contains a hyper virtual stack, and we want to compute
	the X,Y,Z translation between every time point in it
	using the given preferred channel. """
	if frames is None:
		frames = range(1, imp.getNFrames()+1)
		
	t1_vs = extract_frame(imp, frames[0], channel)
	shifts = []
	# store the first shift: between t1 and t2
	shifts.append(Point3i(0, 0, 0))
	# append the rest:
	IJ.showProgress(0)
	i = 1
	for t in frames[1:]:
		IJ.log("Load frame " + str(t) + " up to " + str(frames[-1]))
		t2_vs = extract_frame(imp, t, channel)
		IJ.log("Compute difference " + str(t) + " to " + str(frames[0]))
		shift = compute_stitch(ImagePlus("1", t1_vs), ImagePlus("2", t2_vs))
		shifts.append(shift)
		t1_vs = t2_vs
		IJ.showProgress(i / float(imp.getNFrames()))
		i += 1
	IJ.showProgress(1)

	return shifts, frames
Esempio n. 5
0
 def saveMask(self, maskdir):
     imp = self.mask
     imp.getProcessor().invert()
     filebasename = os.path.basename(self.filename)
     maskfilename = os.path.join(maskdir, "mask_%s" % filebasename)
     IJ.save(imp, maskfilename)
     IJ.log("Mask image: %s\n" % maskfilename)
def run():
  projects = Project.getProjects()
  if projects is None or projects.isEmpty():
    IJ.log('No project open!')
    return
  ls = projects.get(0).getRootLayerSet()
  trees = ls.getZDisplayables(Treeline)
  trees.addAll(ls.getZDisplayables(AreaTree))
  if trees.isEmpty():
    IJ.log('No trees to process!')
    return
  dc = DirectoryChooser('Target folder')
  targetFolder = dc.getDirectory()
  if targetFolder is None:
    return # user canceled
  if targetFolder[len(targetFolder) -1] != '/':
    targetFolder += '/'
  fdir = File(targetFolder)
  for f in fdir.listFiles():
    if f.isHidden():
      continue
    yn = YesNoCancelDialog(IJ.getInstance(), "WARNING", "Folder not empty! Continue?")
    if yn.yesPressed():
      break
    else:
      return
  process(trees, targetFolder)
def translate_single_stack_using_imglib2(imp, dx, dy, dz):
  # wrap into a float imglib2 and translate
  #   conversion into float is necessary due to "overflow of n-linear interpolation due to accuracy limits of unsigned bytes"
  #   see: https://github.com/fiji/fiji/issues/136#issuecomment-173831951
  img = ImagePlusImgs.from(imp.duplicate())
  extended = Views.extendBorder(img)
  converted = Converters.convert(extended, RealFloatSamplerConverter())
  interpolant = Views.interpolate(converted, NLinearInterpolatorFactory())
  
  # translate
  if imp.getNDimensions()==3:
    transformed = RealViews.affine(interpolant, Translation3D(dx, dy, dz))
  elif imp.getNDimensions()==2:
    transformed = RealViews.affine(interpolant, Translation2D(dx, dy))
  else:
    IJ.log("Can only work on 2D or 3D stacks")
    return None
  
  cropped = Views.interval(transformed, img)
  # wrap back into bit depth of input image and return
  bd = imp.getBitDepth()
  if bd==8:
    return(ImageJFunctions.wrapUnsignedByte(cropped,"imglib2"))
  elif bd == 16:
    return(ImageJFunctions.wrapUnsignedShort(cropped,"imglib2"))
  elif bd == 32:
    return(ImageJFunctions.wrapFloat(cropped,"imglib2"))
  else:
    return None    
def core(imp):
	pntsA = parsePoints(imp)
	# Points must be passed to the Clusterer in Java List of Clusterable. 
	pntsAL = ArrayList()
	for apnt in pntsA:
		pntsAL.add(PosWrap(apnt[0], apnt[1], apnt[2]))
	
	awrap = pntsAL.get(0)
	pp = awrap.getPoint()
	#print pp
	
	clusterer = KMeansPlusPlusClusterer(Number_of_Cluster, Iteration)
	res = clusterer.cluster(pntsAL)
	outimp = imp.duplicate()
	for i in range(res.size()):
		if Verbose:
			IJ.log('Cluster: ' + str(i))
		for apnt in res.get(i).getPoints():
			xpos = apnt.getPoint()[0]
			ypos = apnt.getPoint()[1]
			zpos = apnt.getPoint()[2]
			if Verbose:
				IJ.log('... ' + str(xpos) + ', ' + str(ypos) + ', ' + str(zpos))
			outimp.getStack().getProcessor(int(zpos)+1).putPixel(int(xpos), int(ypos), i+1)
	return outimp
Esempio n. 9
0
def restore_metadata(input_dir,original_metadata,prefix):
	# restore original metadata and filename to tiles
	rewritten_data = glob.glob("%s*.tiff"%input_dir)
	for f,filename in enumerate(rewritten_data):
		new_filename = prefix+os.path.basename(filename)
		IJ.log("Rewriting original meta data in image %s"%os.path.basename(new_filename))
		replace_meta(original_metadata[f],filename)
		os.rename(filename,new_filename)
Esempio n. 10
0
    def actionPerformed(self, event):
        dlg = DirectoryChooser("Choose an output directory for the classifier")

        if os.path.exists(self.path):
            dlg.setDefaultDirectory(self.path)

        self.path = dlg.getDirectory()
        IJ.log("Added path: "+self.path)
Esempio n. 11
0
 def mousePressed(self, event):
     canvas = event.getSource()
     # imp = canvas.getImage()
     p = canvas.getCursorLoc()
     self.mouseWasPressed = True
     IJ.log("mouse was clicked at:" + str(p.x) + " " + str(p.y))
     self.x = p.x
     self.y = p.y
Esempio n. 12
0
 def saveResult(self, resdir, header):
     filebasename = os.path.basename(self.filename)
     resfilename = os.path.join(resdir, "res_%s.csv" % os.path.splitext(filebasename)[0])
     with codecs.open(resfilename, "w", "utf-8") as f:
         table = [",".join(header) + "\n"]
         table += ["%s, %s\n" % (filebasename, row.asRow()) for row in self.result]
         f.writelines(table)
     IJ.log("Result: %s" % resfilename)
def extract_stack_under_arealist():
	# Check that a Display is open
	display = Display.getFront()
	if display is None:
		IJ.log("Open a TrakEM2 Display first!")
		return
	# Check that an AreaList is selected and active:
	ali = display.getActive()
	if ali is None or not isinstance(ali, AreaList):
		IJ.log("Please select an AreaList first!")
		return

	# Get the range of layers to which ali paints:
	ls = display.getLayerSet()
	ifirst = ls.indexOf(ali.getFirstLayer())
	ilast = ls.indexOf(ali.getLastLayer())
	layers = display.getLayerSet().getLayers().subList(ifirst, ilast +1)

	# Create a stack with the dimensions of ali
	bounds = ali.getBoundingBox()
	stack = ImageStack(bounds.width, bounds.height)

	# Using 16-bit. To change to 8-bit, use GRAY8 and ByteProcessor in the two lines below:
	type = ImagePlus.GRAY16
	ref_ip = ShortProcessor(bounds.width, bounds.height)

	for layer in layers:
		area = ali.getArea(layer)
		z = layer.getZ()
		ip = ref_ip.createProcessor(bounds.width, bounds.height)
		if area is None:
			stack.addSlice(str(z), bp)
			continue

		# Create a ROI from the area of ali at layer:
		aff = ali.getAffineTransformCopy()
		aff.translate(-bounds.x, -bounds.y)
		roi = ShapeRoi(area.createTransformedArea(aff))

		# Create a cropped snapshot of the images at layer under ali:
		flat = Patch.makeFlatImage(type, layer, bounds, 1.0, layer.getDisplayables(Patch), Color.black)
		b = roi.getBounds()
		flat.setRoi(roi)
		ip.insert(flat.crop(), b.x, b.y)

		# Clear the outside of ROI (ShapeRoi is a non-rectangular ROI type)
		bimp = ImagePlus("", ip)
		bimp.setRoi(roi)
		ip.setValue(0)
		ip.setBackgroundValue(0)
		IJ.run(bimp, "Clear Outside", "")

		# Accumulate slices
		stack.addSlice(str(z), ip)

	imp = ImagePlus("AreaList stack", stack)
	imp.setCalibration(ls.getCalibrationCopy())
	imp.show()
def compute_and_update_frame_translations_dt(imp, channel, dt, process, shifts = None):
  """ imp contains a hyper virtual stack, and we want to compute
  the X,Y,Z translation between every t and t+dt time points in it
  using the given preferred channel. 
  if shifts were already determined at other (lower) dt 
  they will be used and updated.
  """
  nt = imp.getNFrames()
  # get roi (could be None)
  roi = imp.getRoi()
  if roi:
    print "ROI is at", roi.getBounds()   
  # init shifts
  if shifts == None:
    shifts = []
    for t in range(nt):
      shifts.append(Point3f(0,0,0))
  # compute shifts
  IJ.showProgress(0)
  for t in range(dt, nt+dt, dt):
    if t > nt-1: # together with above range till nt+dt this ensures that the last data points are not missed out
      t = nt-1 # nt-1 is the last shift (0-based)
    IJ.log("      between frames "+str(t-dt+1)+" and "+str(t+1))      
    # get (cropped and processed) image at t-dt
    roi1 = shift_roi(imp, roi, shifts[t-dt])
    imp1 = extract_frame_process_roi(imp, t+1-dt, channel, process, roi1)
    # get (cropped and processed) image at t-dt
    roi2 = shift_roi(imp, roi, shifts[t])
    imp2 = extract_frame_process_roi(imp, t+1, channel, process, roi2)
    if roi:
      print "ROI at frame",t-dt+1,"is",roi1.getBounds()   
      print "ROI at frame",t+1,"is",roi2.getBounds()   
    # compute shift
    local_new_shift = compute_stitch(imp2, imp1)
    if roi: # total shift is shift of rois plus measured drift
      print "correcting measured drift of",local_new_shift,"for roi shift:",shift_between_rois(roi2, roi1)
      local_new_shift = add_Point3f(local_new_shift, shift_between_rois(roi2, roi1))
    # determine the shift that we knew alrady
    local_shift = subtract_Point3f(shifts[t],shifts[t-dt])
    # compute difference between new and old measurement (which come from different dt)   
    add_shift = subtract_Point3f(local_new_shift,local_shift)
    print "++ old shift between %s and %s: dx=%s, dy=%s, dz=%s" % (int(t-dt+1),int(t+1),local_shift.x,local_shift.y,local_shift.z)
    print "++ add shift between %s and %s: dx=%s, dy=%s, dz=%s" % (int(t-dt+1),int(t+1),add_shift.x,add_shift.y,add_shift.z)
    # update shifts from t-dt to the end (assuming that the measured local shift will presist till the end)
    for i,tt in enumerate(range(t-dt,nt)):
      # for i>dt below expression basically is a linear drift predicition for the frames at tt>t
      # this is only important for predicting the best shift of the ROI 
      # the drifts for i>dt will be corrected by the next measurements
      shifts[tt].x += 1.0*i/dt * add_shift.x
      shifts[tt].y += 1.0*i/dt * add_shift.y
      shifts[tt].z += 1.0*i/dt * add_shift.z
      print "updated shift till frame",tt+1,"is",shifts[tt].x,shifts[tt].y,shifts[tt].z
    IJ.showProgress(1.0*t/(nt+1))
  
  IJ.showProgress(1)
  return shifts
	def call(self):
		self.thread_used = threading.currentThread().getName()
		self.started = time.time()
		try:
			applyLayerTransformToPatch(self.patch, self.transform)
			print self.patch.getTitle() + " patch transformed\n"
		except Exception, ex:
			self.exception = ex
			print str(ex)
			IJ.log(str(ex))
def isFrames(imp):
    """Determine whether the stack has >1 slices or >1 frames"""
    NSlices = imp.getNSlices
    NFrames = imp.getNFrames
    #print "number of slices:", NSlices
    #print "number of frames:", NFrames
    if NSlices == 1 and NFrames != 1:
        return True
    elif NSlices != 1 and NFrames == 1:
        return False
    else:
        IJ.log("stack dimension error!")
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
Esempio n. 18
0
def concatenateImagePlus(files, outfile):
    """Concatenate images contained in files and save in outfile"""

    options = ImporterOptions()
    options.setId(files[0])
    options.setVirtual(1)
    options.setOpenAllSeries(1)
    options.setQuiet(1)
    images = BF.openImagePlus(options)
    imageG = images[0]
    nrPositions = len(images)
    options.setOpenAllSeries(0)

    nslices = imageG.getNSlices()
    nframes = len(files)
    nchannels = imageG.getNChannels()
    luts = imageG.getLuts()

    for i in range(0, nrPositions):
        concatImgPlus = IJ.createHyperStack(
            "ConcatFile", imageG.getWidth(), imageG.getHeight(),
            imageG.getNChannels(), imageG.getNSlices(),
            len(files), imageG.getBitDepth())


        concatStack = ImageStack(imageG.getWidth(), imageG.getHeight())
        IJ.showStatus("Concatenating files")
        for file_ in files:
            try:
                print '...', basename(file_)
                options.setSeriesOn(i, 1)
                options.setId(file_)
                image = BF.openImagePlus(options)[0]
                imageStack = image.getImageStack()

                sliceNr = imageStack.getSize()
                for j in range(1, sliceNr+1):
                    concatStack.addSlice(imageStack.getProcessor(j))
                image.close()
                options.setSeriesOn(i, 0)
            except Exception, e:
                IJ.log("ERROR")
                IJ.log(file_ + str(e))
                raise
            IJ.showProgress(files.index(file_), len(files))

        concatImgPlus.setStack(concatStack, nchannels, nslices, nframes)
        concatImgPlus.setCalibration(image.getCalibration())
        concatImgPlus.setOpenAsHyperStack(True)
        concatImgPlus.setLuts(luts)
        concatImgPlus.close()
        IJ.saveAs(concatImgPlus, "Tiff",  outfile)
def write_object_db(objectDB, path):
	try:
		f = open(path,"w")
		for tile in objectDB:
			for obj in tile:
				stringVersion = [str(x) for x in obj]
				cereal = ','.join(stringVersion)
				#print cereal
				f.write(cereal+"\n")
	except:
		IJ.log("Could not write updated object file")
	finally:
		f.close()
Esempio n. 20
0
    def measure(self):
        imp = IJ.openImage(self.filename)
        IJ.log("Input file: %s" % self.filename)

        ImageConverter(imp).convertToGray8()

        res = Auto_Threshold().exec(imp, self.myMethod, self.noWhite, self.noBlack, self.doIwhite, self.doIset, self.doIlog, self.doIstackHistogram)

        rt = ResultsTable()
        rt.showRowNumbers(False)
        pa = PA(self.options, PA.AREA + PA.PERIMETER + PA.CIRCULARITY, rt, self.MINSIZE, self.MAXSIZE)
        pa.analyze(imp)
        self.result = self.rtToResult(rt)
        self.mask = imp
Esempio n. 21
0
def saveStack(destFolder,file_name,imp):	
	#rename the result and save it to subfolder
	if not os.path.isdir(destFolder):
		os.makedirs(destFolder)
	fullname=os.path.join(destFolder,file_name)
	#print (fullname)
	fs = FileSaver(imp)
	#print 'bSaveStack()', fullPath, 'nslices=', sr_imp.getNSlices()
	print('save result to: ',fullname)
	msgStr = "Dimension:" + str(imp.width) + " X " + str(imp.height) + " X " + str(imp.getNSlices())
	print (msgStr)
	IJ.log("   -Save "+file_name+" to "+destFolder)
	IJ.log("      -"+msgStr)
	fs.saveAsTiffStack(fullname)
def CZI_convert(nucleus_channel):
	# Convert CZI to IDS files
    NbSeries = Z1_metadata(sourcefile)
    IJ.log(INpath + " contains " + str(NbSeries) + " views")
    options = "open=[" + INpath + \
        "] stack_order=XYCZT color_mode=Composite view=Hyperstack"
    for k in range(1, NbSeries + 1):
        imp = IJ.run("Bio-Formats Importer", options + " series_" + str(k))
        output = "view" + str(k) + ".ids"
        IJ.run(imp, "Bio-Formats Exporter", "save=" +
               os.path.join(folder1, output))
		preprocessing(imp,nucleus_channel,output)
        IJ.run("Close")
        IJ.log("View " + str(k) + " Converted")
Esempio n. 23
0
def run_stitch(filePath):
	basePath,baseName = os.path.split(filePath)
	imagePrefix = os.path.splitext(baseName)[0]
	resizeName = basePath + "/" + baseName + "_tiles/resized/"
	checkName = basePath + "/" + baseName + "_tiles/resized/" + imagePrefix + "_seq/"
	activeName = basePath + "/" + baseName + "_tiles"
	IJ.log("Stitching " + filePath + "...")
	if (not os.path.isdir(checkName)):
		thread = Thread.currentThread()
		originalThread = thread.getName()
		thread.setName("Run$_stitch_process")
		options = "choose=" + resizeName + " select=" + activeName + "/tile_info.txt image_prefix=" + imagePrefix
		Macro.setOptions(Thread.currentThread(),options)
		try:
			IJ.run("Stitch wrapper",options)
			IJ.log("succeeded")
			returnVal = 0
		except:
			IJ.log("failed")
			os.rmdir(checkName)
			returnVal = 1
		thread.setName(originalThread)
		Macro.setOptions(thread,None)
	else:
		IJ.log("skipped")
		returnVal = 2

	return returnVal
def selectZrange(infile, Qmin, Qmax):
    infile = filename(infile)
    data = retrieve_seeds(infile)
    spotsZ = []
    for row in data:
        spotsZ.append(float(row[4]))
    spotsZ = sorted(spotsZ)
    if len(spotsZ) > 10:
        Zmin = float(percentile(spotsZ, Qmin))
        Zmax = float(percentile(spotsZ, Qmax))
    else:
        Zmin = 1
        Zmax = 3
    IJ.log(infile + ' zmin=' + str(Zmin) + ' zmax=' + str(Zmax))
    return Zmin, Zmax
Esempio n. 25
0
def orthoStackFrom4D(imp):
	stkA = ArrayList()
	for i in range(1, imp.getNFrames()+1):
	   e4d = Extractfrom4D()
	   e4d.setGstarttimepoint(i)
	   IJ.log("current time point" + str(i))
	   aframe = e4d.coreheadless(imp, 3)
	   ortho = XYZMaxProject(aframe)
	   orthoimp = ortho.getXYZProject()
	   stkA.add(orthoimp)
	   #orthoimp.show()
	stk = ImageStack(stkA.get(0).getWidth(), stkA.get(0).getHeight())
	for item in stkA:
   		stk.addSlice("slcie", item.getProcessor())
	out = ImagePlus("out", stk)
	return out
Esempio n. 26
0
def run():
  global cal, pw, ph
  projects = Project.getProjects()
  if projects is None or projects.isEmpty():
    IJ.log('No project open!')
    return
  p = projects.get(0)
  ls = p.getRootLayerSet()
  cal = ls.getCalibrationCopy()
  pw = float(cal.pixelWidth)
  ph = float(cal.pixelHeight)
  rpt = p.getRootProjectThing()

  add_recursively(rpt,None)

  add_connectors_recursively(rpt)
Esempio n. 27
0
 def run(self):
     IJ.resetEscape()
     IJ.setTool("point")
     listener = ML()
     self.imp.show()
     canvas = self.imp.getWindow().getCanvas()
     canvas.addMouseListener(listener)
     # wait for mouse click
     while (not listener.mouseWasPressed) and (not IJ.escapePressed()):
         Thread.sleep(200)  # todo: how to make this better?
     canvas.removeMouseListener(listener)
     if IJ.escapePressed():
         IJ.log("command has been aborted")
     else:
         print listener.x, listener.y
         self.pos = [listener.x, listener.y]
def retrieve_seeds(infile):
    # Retrieve detected nucleus spots from csv files
    data = {}
    name = re.sub('.ids', '.csv', infile)
    with open(os.path.join(folder5, name), 'rb') as f:
        reader = csv.reader(f, delimiter=',', quotechar='"',
                            skipinitialspace=True)
        header = reader.next()
        for name in header:
            data[name] = []
        for row in reader:
            for i, value in enumerate(row):
                data[header[i]].append(value)
    output = zip(data['spotID'], data['roundID'], data['X'], data['Y'], data[
                 'Z'], data['QUALITY'], data['SNR'], data['INTENSITY'])
    IJ.log('Loading ' + str(len(output)) + ' seed spots from ' + name)
    return output
def run():
    helpText = "This program will batch convert .swc files to " + \
               "SVG vector graphs.\n\n" + \
               ">> Press OK to Select a directory of .swc traces."
    MessageDialog(IJ.getInstance(),"Batch SWC to SVG Guide", helpText)


    d = DirectoryChooser("Chose Traces Dir").getDirectory()
    if d is None:
        IJ.log("Choose Dir Canceled!")
        return

    swc_files = [ os.path.join(d,x) for x in os.listdir(d) if re.search('(?i)\.swc$',x) ]
     
    pafm = PathAndFillManager(10240, # width
                              10240, # height
                              1, # depth
                              1, # x spacing
                              1, # y spacing
                              1, # z spacing
                              "pixel")

    for swc_file in swc_files:
        out_file = swc_file + ".svg"
     
        if not pafm.importSWC(swc_file,False): # second parameter is ignoreCalibration
            IJ.error("Failed to load: "+swc_file)
     
        for i in range(pafm.size()):
            path = pafm.getPath(i)
            
            f = open(out_file, "wb")
            f.write(toSvgString_polyline(path))
            f.close()

            f = open(swc_file + "-path.svg", "wb")
            f.write(toSvgString_path(path))
            f.close()

            f = open(swc_file + "-points.csv",'wb')
            writer = csv.writer(f)
            writer.writerow(["x", "y"])
            writer.writerows(toListOfPoints(path))
            f.close()
Esempio n. 30
0
def segmentChannel_Weka(image, **kwargs):
	""" SegmentChannel using a Weka Classification"""
	ch = kwargs['channel']
	if ch > len(image): 
		raise Exception('Expecting at least ' + str(ch) + ' channels. Image has only ' + str(len(imageC)) + ' channel(s)')
	imp = image[ch-1].duplicate()
	ws = WekaSegmentation(imp)	# create an instance
	ws.loadClassifier(kwargs['clspath']) # load classifier
	impProb  = ws.applyClassifier(imp, 0, True)
	impMetaProb = extractChannel(impProb,1,1)
	impMetaProb.setTitle("MetaProb")
	# segmentation
	impBW = threshold(impMetaProb, kwargs['probThr'])
	impMetaProb.show()
	IJ.run("Set Measurements...", " mean center shape area redirect=MetaProb decimal=2");
	
	# particle analysis
	IJ.run(impBW, "Analyze Particles...", "size=10-10000 pixel area circularity=0.00-1.00 display exclude clear stack add");
	rt = Analyzer.getResultsTable()
	validParticles = []
	roim = RoiManager.getInstance()
	if roim == None:
		raise Exception('Fiji error segmentNuclei.py: no RoiManager!')
	if roim.getCount() > 0:
		rois = roim.getRoisAsArray()
	else:
		IJ.log("# particles = 0")
		return impMetaProb, impBW, None, None
	X = rt.getColumn(rt.getColumnIndex("XM"))
	Y = rt.getColumn(rt.getColumnIndex("YM"))
	Mean = rt.getColumn(rt.getColumnIndex("Mean"))
	Circ = rt.getColumn(rt.getColumnIndex("Circ."))
	Area = rt.getColumn(rt.getColumnIndex("Area"))
	print "# particles = " + str(len(Mean))
	for i in range(len(Mean)):
		valid = (Mean[i]>kwargs['minProb']) and (Circ[i]<kwargs['maxCirc']) # filter particles post detection
		if(valid):
			validParticles.append([i, X[i], Y[i]])
	random.shuffle(validParticles)
	IJ.log("# valid particles = %d " % len(validParticles))
	if len(validParticles) == 0:
		validParticles = None
	return impMetaProb, impBW, validParticles, rois
Esempio n. 31
0
def getMatchingResults(features1, features2):
    candidates = ArrayList()
    inliers = ArrayList()
    FeatureTransform.matchFeatures(features1, features2, candidates, 0.92)
    # FeatureTransform.matchFeatures(features1, features2, candidates, 0.95)
    model = AffineModel2D()
    try:
        modelFound = model.filterRansac(
            candidates, inliers, 1000, 10, 0, 7
        )  # (candidates, inliers, iterations, maxDisplacement, ratioOfConservedFeatures, minNumberOfConservedFeatures)
    except NotEnoughDataPointsException, e:
        modelFound = False
        IJ.log('NotEnoughDataPointsException')
        return None
    if not modelFound:
        IJ.log('model not found ')
        return None
    else:
        IJ.log('model found')
        return [model, inliers]


def getScalingFactors(aff):
    m = pythonToJamaMatrix([[aff.getScaleX(), aff.getShearX()],
                            [aff.getShearY(), aff.getScaleY()]])
    SVD = SingularValueDecomposition(m)
    S = SVD.getS().getArrayCopy()
    return S[0][0], S[1][1]


def computeRegistration():
Esempio n. 32
0
try:  # look in priority for sectionOrder, which means that it has already been processed
    orderPath = os.path.join(
        MagCFolder,
        filter(lambda x: 'sectionOrder' in x, os.listdir(MagCFolder))[0])
except Exception, e:
    orderPath = os.path.join(
        MagCFolder,
        filter(lambda x: 'solution' in x, os.listdir(MagCFolder))[0])

sectionOrder = fc.readOrder(orderPath)

BIBMode = True
if BIBMode:
    sectionOrder = [o / 2 for o in sectionOrder[::2]]

IJ.log('sectionOrder: ' + str(sectionOrder))

MagCParams = fc.readMagCParameters(MagCFolder)

executeLM = MagCParams[namePlugin]['executeLM']
executeEM = MagCParams[namePlugin]['executeEM']

##########################
##########  LM  ##########
##########################
if executeLM:
    sourceLMDataFolder = os.path.join(MagCFolder, 'LMData')
    targetLMDataFolder = os.path.join(MagCFolder, 'LMDataReordered')

    try:
        os.makedirs(targetLMDataFolder)
        print "Output directory exists already, data might be overwritten"

    #crop images ?

    #get c-Fos
    ListCfos = getCfosImages(In_dir)
    #if it is empty stop
    if len(ListCfos) == 0:
        os.rmdir(Out_dir)
        sys.exit('No c-Fos images found')

    #get unique MouseIDs
    MouseIDs = UniqueMouseIDs(ListCfos)

    for MouseID in MouseIDs:
        IJ.log("\nProcessing mouse " + MouseID)
        #get the list of cFos images for a specific mouse
        MouseIDcFos = getMouseCfos(ListCfos, MouseID)
        #find the threshold values using the quantiles
        percentiles = [98.5, 99.5, 99.9]
        thresholds = FindThreholds(In_dir, MouseIDcFos, percentiles)
        IJ.log('Thresholds for percentiles ' + str(percentiles) +
               ' selected to ' + str(thresholds))
        #threshold and save images for each threshold value
        for i, threshold in enumerate(thresholds):
            # create directory
            Perc_Out_dir = Out_dir + "percentile_" + str(percentiles[i]) + "/"
            if not os.path.exists(Perc_Out_dir):
                os.makedirs(Perc_Out_dir)
            IJ.log('Processing ' + MouseID + ' for percentile ' +
                   str(percentiles[i]))
def processFile():
	# start logging
	IJ.log("\n______________________________\n\n\t\tOlympus DM correction\n\t\tVersion " + pluginVersion +"\n______________________________\n")

	# ask user for file
	ofd = OpenDialog("Choose a file", None)  
	filename = ofd.getFileName()  
  
	if filename is None:  
  		IJ.log("User canceled the dialog!\nImage processing canceled!\n")
  		return

  	directory = ofd.getDirectory()  
  	filepath = directory + filename  
  	IJ.log("File path: " + filepath)

	if not filename.endswith(".oir"):
		IJ.log("Not an Olympus (.oir) file.\nNo image to process.\n")
		return

	filenameExExt = os.path.splitext(filename)[0]
      
	# parse metadata
	reader = ImageReader()
	omeMeta = MetadataTools.createOMEXMLMetadata()
	reader.setMetadataStore(omeMeta)
	reader.setId(filepath)
	numChannels = reader.getSizeC()
	numSlices = reader.getSizeZ()
	numFrames = reader.getSizeT()
	seriesCount = reader.getSeriesCount()

	globalMetadata = reader.getGlobalMetadata()
	seriesMetadata = reader.getSeriesMetadata()

	objLensName = globalMetadata['- Objective Lens name #1']

	areaRotation = float(seriesMetadata['area rotation #1'])
	acquisitionValueRotation = float(seriesMetadata['acquisitionValue rotation #1'])
	if 'regionInfo rotation #1' in seriesMetadata:
		regionInfoRotation = float(seriesMetadata['regionInfo rotation #1'])
	else:
		regionInfoRotation = float(0)

	totalRotation = areaRotation + regionInfoRotation
	physSizeX = omeMeta.getPixelsPhysicalSizeX(0)
	physSizeY = omeMeta.getPixelsPhysicalSizeY(0)
	pxSizeX = physSizeX.value(UNITS.MICROM)
	pxSizeY = physSizeY.value(UNITS.MICROM)

	# log metadata
	IJ.log("\nMETADATA")
	#IJ.log("Filename: " + filepath)
	IJ.log("Number of series: " + str(seriesCount))
	IJ.log("Number of channels: " + str(numChannels))
	IJ.log("Number of frames: " + str(numFrames))
	IJ.log("Number of slices: " + str(numSlices))
	IJ.log("Objective lens: " + objLensName)
	IJ.log("FOV rotation: " + str(areaRotation))
	IJ.log("ROI rotation: " + str(regionInfoRotation))
	IJ.log("Total rotation: " + str(totalRotation))
	IJ.log("Pixel size:")
	IJ.log("\t\tX = " + str(physSizeX.value()) + " " + physSizeX.unit().getSymbol())
	IJ.log("\t\tY = " + str(physSizeY.value()) + " " + physSizeY.unit().getSymbol())

	# ask user to identify dichroic mirror used for each channel  
	gdDM = GenericDialog("Dichroic mirrors")
	DMs = ["DM1", "DM2", "DM3", "DM4", "DM5"] 
	for i in range(numChannels):
		gdDM.addChoice("Channel " + str(i+1), DMs, DMs[0])
	gdDM.addCheckbox("Merge channels", False) 
	gdDM.showDialog()
	if gdDM.wasCanceled():
		IJ.log("User canceled the dialog!\nImage processing canceled!\n")
		return
	dichroics = []
	for i in range(numChannels):
		dichroics.append(gdDM.getNextChoice())
	merge = gdDM.getNextBoolean()
	IJ.log("\nUser selected dichroic mirrors")
	for i in range(numChannels):
		IJ.log("\t\tChannel " + str(i+1) + ": " + dichroics[i])	

	if merge:
		channels = []
		chDict = {}
		for i in range(numChannels):
			chName = "Channel"+str(i+1)
			channels.append(chName)
			chDict[chName] = i
		channels.append("NONE")
		colourChoices = ["red", "green", "blue", "gray", "cyan", "magenta", "yellow"]
		gdMerge = GenericDialog("Merge channels")
		for c in colourChoices:
			gdMerge.addChoice(c + ":", channels, channels[numChannels])
		gdMerge.showDialog()
		if gdMerge.wasCanceled():
			IJ.log("User canceled the dialog!\nImage processing canceled!\n")
			return
		IJ.log("\nUser selected channel colours")
		mergeList = []
		for i in range(len(colourChoices)):
			ch = gdMerge.getNextChoice()
			if ch == "NONE":
				mergeList.append(None)
			else:
				mergeList.append(chDict[ch])
				IJ.log("\t\t" + colourChoices[i] + ": " + ch)

	# ask user for an output directory
	dc = DirectoryChooser("Choose folder for output")  
	od = dc.getDirectory()    
	if od is None:  
		IJ.log("User canceled the dialog!\nImage processing canceled!\n")  
		return  
  
	if merge:
		tifDir = od + "." + str(datetime.now()).replace(" ", "").replace(":", "") + "/"
		if not os.path.exists(tifDir):
			os.makedirs(tifDir)
			IJ.log("\nCreated temporary folder: " + tifDir + "\n")
		else:
			IJ.log("Unable to create temporary folder!\n")
	else:
		tifDir = od + filenameExExt + "/"
		if not os.path.exists(tifDir):
			os.makedirs(tifDir)
			IJ.log("\nCreated subfolder: " + tifDir + "\n")
		else:
			IJ.log("\nSubfolder " + tifDir +  " already exists")

	# correct images
	tifFilePaths = []
	for i in range(numChannels):
		ip = extractChannel(oirFile=filepath, ch=i)
		if dichroics[i] == "DM1":
			IJ.log("Channel " + str(i+1) + " was imaged using DM1, so no correction required.")
		else:
			offsets = getOffset(obj=objLensName,dm=dichroicDict[dichroics[i]])
			xom = offsets['x']
			yom = offsets['y']
			if abs(totalRotation) > 0.1:
				rotOff = rotateOffset(x=xom, y=yom, angle=-totalRotation)
				xom = rotOff['x']
				yom = rotOff['y']
			xop = int(round(xom/pxSizeX))
			yop = int(round(yom/pxSizeY))
			IJ.log("Channel " + str(i+1) + " offsets")
			IJ.log("\t\tMicrometres")
			IJ.log("\t\t\t\tx = " + str(xom))
			IJ.log("\t\t\t\ty = " + str(yom))
			IJ.log("\t\tPixels")
			IJ.log("\t\t\t\tx = " + str(xop))
			IJ.log("\t\t\t\ty = " + str(yop))
			IJ.run(ip, "Translate...", "x=" + str(-xop) + " y=" + str(-yop) + " interpolation=None stack")

		tifFilePath = tifDir + filenameExExt + "_ch_"+str(i+1)+".tif"
		tifFilePaths.append(tifFilePath)
		if os.path.exists(tifFilePath):
			IJ.log("\nOutput file exists: " + tifFilePath)
			IJ.log("Rerun plugin choosing a different output folder")
			IJ.log("or delete file and then rerun plugin.")
			IJ.log("Image processing terminated!\n")
			return
		FileSaver(ip).saveAsTiff(tifFilePath)

	if merge:
		for i in range(len(mergeList)):
			if mergeList[i] != None:
				mergeList[i] = readSingleChannelImg(tifFilePaths[mergeList[i]])
		merged = RGBStackMerge.mergeChannels(mergeList, False)
		mergedChannelFilepath = od + filenameExExt + ".tif"
		if os.path.exists(mergedChannelFilepath):
			IJ.log("\nOutput file exists: " + mergedChannelFilepath)
			IJ.log("Rerun plugin choosing a different output folder")
			IJ.log("or delete file and then rerun plugin.")
			IJ.log("Image processing terminated!\n")
		FileSaver(merged).saveAsTiff(mergedChannelFilepath)
		for tf in tifFilePaths:
			os.remove(tf)
		os.rmdir(tifDir)
			
	IJ.log("\nFinished processing file:\n" + filepath + "\n")
	if merge:
		IJ.log("Image file with channels aligned:\n" + od + filenameExExt + ".tif\n")
	else:
		IJ.log("Aligned images (one tiff file for each channel) can be found in:\n" + tifDir + "\n")
Esempio n. 35
0
    return y * nX + (nX - x - 1)

namePlugin = 'assembly_EM'
MagCFolder = fc.startPlugin(namePlugin)
MagCParameters = fc.readMagCParameters(MagCFolder)

ControlWindow.setGUIEnabled(False)
MagC_EM_Folder = os.path.join(MagCFolder, 'MagC_EM','')

# read metadata
EMMetadataPath = fc.findFilesFromTags(MagCFolder,['EM_Metadata'])[0]
EMMetadata = fc.readParameters(EMMetadataPath)
numTilesX = EMMetadata['numTilesX']

# reading transforms from the low-resolution montage
IJ.log('reading the affine transform parameters from the affine montage')
transformsPath = os.path.join(MagC_EM_Folder, 'assembly_lowEM_Transforms.txt')
with (open(transformsPath, 'r')) as f:
    transforms = f.readlines()
nLayers = max([int(transforms[i]) for i in range(1, len(transforms),8) ]) + 1 # why not, could simply read the EM_Metadata parameters ...

# getting downsamplingFactor
downsamplingFactor = MagCParameters['downsample_EM']['downsamplingFactor']
factorString = str(int(1000000*downsamplingFactor)).zfill(8)

# create the normal resolution project
IJ.log('Creating project with the full size EM images')
projectPath = fc.cleanLinuxPath(os.path.join(MagC_EM_Folder,'EMProject.xml'))
projectFolder = fc.cleanLinuxPath(os.path.dirname(projectPath))
project, loader, layerset, _ = fc.getProjectUtils(fc.initTrakem(projectFolder, 1))
project.saveAs(projectPath, True)
Esempio n. 36
0
def process(imp):
    IJ.log("Processing " + str(imp.title) + "...")
    #impOut = imp.duplicate()
    impOut = imp
    impOut.show()

    # Prepare Roi Manager
    rm = RoiManager.getInstance()
    if rm is not None:
        rm.reset()

    ### STEP 1 (Coralline, Tunicate) ###

    # Coralline
    UrchinCoral.identifyCoralline(impOut)
    roiCount = rm.getCount()
    coralline = UrchinTag.delete(impOut, rm, roiCount)
    IJ.log("Coralline: " + str(coralline))

    # Tunicate
    UrchinTunicate.identifyTunicate(impOut)
    roiCount = rm.getCount()
    tunicate = UrchinTag.delete(impOut, rm, roiCount)
    IJ.log("Tunicate: " + str(tunicate))

    ### STEP 2 (Red, Macro) ###

    # Red
    UrchinRed.identifyRed(impOut)
    roiCount = rm.getCount()
    red = UrchinTag.delete(impOut, rm, roiCount)
    IJ.log("Red: " + str(red))

    # Macro
    UrchinMacro.identifyMacro(impOut)
    roiCount = rm.getCount()
    macro = UrchinTag.delete(impOut, rm, roiCount)
    IJ.log("Macro: " + str(macro))

    ### STEP 3 (Stragglers) ###

    straggler = UrchinStraggler.learn(impOut)
    coralline = coralline + straggler[0]
    tunicate = tunicate + straggler[1]
    red = red + straggler[2]
    macro = macro + straggler[3]

    # New values
    IJ.log("New values")
    IJ.log("Coralline: " + str(coralline))
    IJ.log("Tunicate: " + str(tunicate))
    IJ.log("Red: " + str(red))
    IJ.log("Macro: " + str(macro))

    impOut.changes = False
    impOut.close()

    # Format String for output
    return UrchinFF.formatData(coralline, tunicate, red, macro)
Esempio n. 37
0
from net.clearcontrol.easyscopy import EasyScopy
from ij import IJ

IJ.log("Supported microscopes:")
for lMicroscopeClass in EasyScopy.listEasyScopes():
    IJ.log(" * " + str(lMicroscopeClass))
            if states[i][j] == states[i][j + 1]:
                events[i].append("{}".format(states[i][j + 1]))
            elif states[i][j] == "growth" and states[i][j + 1] == "shrink":
                events[i].append("gs")
            elif states[i][j] == "growth" and states[i][j + 1] == "pause":
                events[i].append("gp")
            elif states[i][j] == "pause" and states[i][j + 1] == "shrink":
                events[i].append("ps")
            elif states[i][j] == "pause" and states[i][j + 1] == "growth":
                events[i].append("pg")
            elif states[i][j] == "shrink" and states[i][j + 1] == "growth":
                events[i].append("sg")
            elif states[i][j] == "shrink" and states[i][j + 1] == "pause":
                events[i].append("sp")

IJ.log("\\Clear")  # logのclear command
IJ.log("indx" + "\t" + "id" + "\t" + "dt_s" + "\t" + "dlength_um" + "\t" +
       "velocity_um/min" + "\t" + "state" + "\t" + "event" + "\t" +
       "event_bool")

for i in range(len(vels)):
    for j in range(len(vels[i])):
        IJ.log(
            str(j) + "\t" + str(i) + "\t" + str(dts[i][j]) + "\t" +
            str(dls[i][j]) + "\t" + str(vels[i][j]) + "\t" +
            str(states[i][j]) + "\t" + str(events[i][j]) + "\t" + str("TRUE"))

# logの結果をsave
from ij import IJ
import os
from ij import WindowManager as wm
        os.makedirs(Out_dir)
    else:
        print("Output directory exists already, data might be overwritten")

    # get tif files
    ListTif = getTifImages(In_dir)
    # if it is empty stop
    if len(ListTif) == 0:
        os.rmdir(Out_dir)
        sys.exit('No .tif images found, bye')

    # get unique MouseIDs
    MouseIDs = UniqueMouseIDs(ListTif)

    for MouseID in MouseIDs:
        IJ.log("\nProcessing mouse " + MouseID)
        # get the list of cFos images for a specific mouse
        MouseIDFiles = getMouseFiles(ListTif, MouseID)
        # calculate the number of channels
        number_of_channels_in_mouse = getNumberOfChannels(MouseIDFiles)
        print(
            str(MouseID) + " contains " + str(number_of_channels_in_mouse) +
            " distinct channels")
        # run the function for each of the channels
        for channel in range(1, (number_of_channels_in_mouse + 1)):
            channel_files = getChannelFiles(MouseIDFiles, channel)
            # get the full path
            chf_fpaths = [path.join(In_dir, x) for x in channel_files]
            # get the minimum and maximum pixel value
            min_pixval, max_pixval = get_enhance_bounds(
                chf_fpaths, low_theshold, high_threshold)
Esempio n. 40
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"));
Esempio n. 41
0
def process_time_points(root, files, outdir):
	'''Concatenate images and write ome.tiff file. If image contains already multiple time points just copy the image'''
	concat = 1
	files.sort()
	options = ImporterOptions()
	options.setId(files[0])
	options.setVirtual(1)
	image = BF.openImagePlus(options)
	image = image[0]
	if image.getNFrames() > 1:
		IJ.log(files[0] + " Contains multiple time points. Can only concatenate single time points! Don't do anything!")
		image.close()
		return
	
	width  = image.getWidth()
	height = image.getHeight()
	for patt in pattern:
		outName = re.match(patt, os.path.basename(files[0]))
		if outName is None:
			continue
		if outdir is None:
			outfile = os.path.join(root, outName.group(1) + '.ome.tif')
		else:
			outfile =  os.path.join(outdir, outName.group(1) + '.ome.tif')
		reader = ImageReader()
		reader.setMetadataStore(MetadataTools.createOMEXMLMetadata())
		reader.setId(files[0])
		timeInfo = []
		omeOut = reader.getMetadataStore()
		omeOut = setUpXml(omeOut, image, files)
		reader.close()
		image.close()
		IJ.log ('Concatenates ' + os.path.join(root, outName.group(1) + '.ome.tif'))
		itime = 0
		try:
			for ifile, fileName in enumerate(files):
				print fileName
				omeMeta = MetadataTools.createOMEXMLMetadata()
	
				reader.setMetadataStore(omeMeta)
				reader.setId(fileName)
				#print omeMeta.getPlaneDeltaT(0,0)
				#print omeMeta.getPixelsTimeIncrement(0)
				
				if fileName.endswith('.czi'):
					if ifile == 0:
						T0 = omeMeta.getPlaneDeltaT(0,0).value()
					dT = omeMeta.getPlaneDeltaT(0,0).value() - T0
					unit =  omeMeta.getPlaneDeltaT(0,0).unit()
				else:
					timeInfo.append(getTimePoint(reader, omeMeta))
	 				unit = omeMeta.getPixelsTimeIncrement(0).unit()
					try:
						dT = round(timeInfo[files.index(fileName)]-timeInfo[0],2)
					except:
						dT = (timeInfo[files.index(fileName)]-timeInfo[0]).seconds
				
				nrImages = reader.getImageCount()
	
	
				for i in range(0, reader.getImageCount()):
	
					try:
						omeOut.setPlaneDeltaT(dT, 0, i + itime*nrImages)
					except TypeError:
						omeOut.setPlaneDeltaT(Time(dT, unit),0, i + itime*nrImages)
					omeOut.setPlanePositionX(omeOut.getPlanePositionX(0,i), 0, i + itime*nrImages)
					omeOut.setPlanePositionY(omeOut.getPlanePositionY(0,i), 0, i + itime*nrImages)
					omeOut.setPlanePositionZ(omeOut.getPlanePositionZ(0,i), 0, i + itime*nrImages)
					omeOut.setPlaneTheC(omeOut.getPlaneTheC(0,i), 0, i + itime*nrImages)
					omeOut.setPlaneTheT(NonNegativeInteger(itime), 0, i + itime*nrImages)
					omeOut.setPlaneTheZ(omeOut.getPlaneTheZ(0,i), 0, i + itime*nrImages)
				itime = itime + 1
				reader.close()
	
				IJ.showProgress(files.index(fileName), len(files))
			try:
				incr = float(dT/(len(files)-1))
			except:
				incr = 0
			
			try:
				omeOut.setPixelsTimeIncrement(incr, 0)
			except TypeError:
				#new Bioformats >5.1.x
				omeOut.setPixelsTimeIncrement(Time(incr, unit),0)
			
			outfile = concatenateImagePlus(files, outfile)
			if outfile is not None:
				filein = RandomAccessInputStream(outfile)
				fileout = RandomAccessOutputStream(outfile)
				saver = TiffSaver(fileout, outfile)
				saver.overwriteComment(filein,omeOut.dumpXML())
				fileout.close()
				filein.close()
	
	
		except:
			traceback.print_exc()
		finally:
			#close all possible open files
			try:
				reader.close()
			except:
				pass
			try:
				filein.close()
			except:
				pass
			try:
				fileout.close()
			except:
Esempio n. 42
0
    for l, layer in enumerate(layerset.getLayers()):
        layerFolder = os.path.join(registrationFolder,
                                   'layer_' + str(l).zfill(4))
        registeredFolder = os.path.join(layerFolder, 'registered')
        MLSTPath = os.path.join(registeredFolder, 'MLST.xml')
        if os.path.isfile(MLSTPath):
            MLSTransform = CoordinateTransformXML().parse(MLSTPath)
            affineCroppedImPath = os.path.join(
                affineCroppedFolder,
                'affineCropped_' + channel + '_' + str(l).zfill(4) + '.tif')
            patch = Patch.createPatch(p, affineCroppedImPath)
            layer.add(patch)
            patch.setCoordinateTransform(
                MLSTransform
            )  # does the order matter ? apparently yes, but I have to be sure that it is not an offset problem
            IJ.log('Setting the mlsTransform in layer ' + str(l) + ' ' +
                   str(MLSTransform))
            patch.updateBucket()

            if idChannel < len(channels) - 2:  # if it is a fluochannel
                MLSTransformedFolder = fc.mkdir_p(
                    os.path.join(LMFolder, 'MLS_Transformed_' + str(channel),
                                 ''))
                imp = loader.getFlatImage(layer, roiExport, 1, 0x7fffffff,
                                          ImagePlus.GRAY8, Patch,
                                          layer.getAll(Patch), True,
                                          Color.black, None)
                impPath = os.path.join(
                    MLSTransformedFolder, 'MLSTransformed_' + channel + '_' +
                    str(l).zfill(4) + '.tif')
                IJ.save(imp, impPath)
	else:
		IJ.log("Analysis Done!")
	counter+=1

def measure_gd(src_folder,file_names):
	from javax.swing import JButton
	gd = NonBlockingGenericDialog("Loci to compartment")
	gd.setResizable(True)
	gd.pack()
	gd.addMessage("Draw a freehand ROI aound loci and closest \n compartment(e.g. speckle) and press 0 on keyboard.")
	gd.addMessage("To load next image press Next Image button.")
	next_imp_bt = JButton('Next Image', actionPerformed=load_next_image)
	gd.add(next_imp_bt)
	gd.setLocation(10,10)
	gd.setAlwaysOnTop(True)
	gd.hideCancelButton()
	gd.showDialog()  
	#  
	if gd.wasOKed():  
		IJ.log( "Measurement done! You're welcome!")

##MAIN
counter=0
images_path=get_files(src_dir,ext="*"+file_extension) # regex pattern to look in the folder.
if len(images_path)==0:
	IJ.log("There are no images in the specified folder")
else:
	measure_gd(src_dir,images_path)


Esempio n. 44
0
def computeRegistration():
    while atomicI.get() < nSections:
        k = atomicI.getAndIncrement()
        if k < nSections:
            l = k
            IJ.log('Computing EM/LM registration for layer ' + str(l).zfill(4))

            layerFolder = fc.mkdir_p(
                os.path.join(registrationFolder, 'layer_' + str(l).zfill(4)))
            toRegisterFolder = fc.mkdir_p(
                os.path.join(layerFolder, 'toRegister'))
            registeredFolder = fc.mkdir_p(
                os.path.join(layerFolder, 'registered'))

            # Applying appropriate filters to make lowresEM and LM look similar for layer l
            imLM = IJ.openImage(imPaths['LM'][l])
            imLM = fc.localContrast(imLM)
            imLMPath = os.path.join(toRegisterFolder,
                                    'imLM_' + str(l).zfill(4) + '.tif')
            IJ.save(imLM, imLMPath)

            imEM = IJ.openImage(imPaths['EM'][l])
            imEM = fc.localContrast(imEM)
            imEMPath = os.path.join(toRegisterFolder,
                                    'imEM_' + str(l).zfill(4) + '.tif')
            IJ.save(imEM, imEMPath)

            # Compute first a simple affine registration on the non-cropped images
            IJ.log(
                'Computing affine and moving least squares alignment for layer '
                + str(l).zfill(4))
            firstStepRegistered = False

            # registration at first step with 1step/octave (less features)
            pLowRes = getSIFTMatchingParameters(nOctaves[0], 1.6, 16, 4000, 8,
                                                4)

            featuresLM = getFeatures(imLMPath, pLowRes)
            featuresEM = getFeatures(imEMPath, pLowRes)

            matchingResults = getMatchingResults(featuresLM, featuresEM)
            if matchingResults is None:
                IJ.log(
                    'No registration matching at low resolution matching step 1 in layer '
                    + str(l).zfill(4))
            else:
                model, inliers = matchingResults
                distance = PointMatch.meanDistance(
                    inliers
                )  # mean displacement of the remaining matching features
                IJ.log('---Layer ' + str(l).zfill(4) + ' distance ' +
                       str(distance) + ' px with ' + str(len(inliers)) +
                       ' inliers')
                if distance > matchingThreshold[0]:
                    IJ.log(
                        'Matching accuracy is lower than the threshold at the low resolution step 1 - '
                        + str(l).zfill(4) + ' - distance - ' + str(distance))
                else:
                    affTransform = model.createAffine()
                    s1, s2 = getScalingFactors(affTransform)
                    IJ.log('Layer ' + str(l).zfill(4) +
                           ' scaling factors - step 1 - ' + str(s1) + ' - ' +
                           str(s2) + '--' + str(s1 * s2) + ' affDeterminant ' +
                           str(affTransform.getDeterminant()) + ' nInliers ' +
                           str(len(inliers)))
                    if (abs(s1 - 1) < 0.2) and (
                            abs(s2 - 1) < 0.2
                    ):  # scaling in both directions should be close to 1
                        IJ.log('First step ok - layer ' + str(l).zfill(4))
                        firstStepRegistered = True
                        loaderZ.serialize(
                            affTransform,
                            os.path.join(registeredFolder, 'affineSerialized'))

            if not firstStepRegistered:
                IJ.log(
                    'First step registration in layer ' + str(l).zfill(4) +
                    ' with few features has failed. Trying with more features.'
                )
                # registration at first step with 3steps/octave (more features)
                # pLowRes = getSIFTMatchingParameters(3, 1.6, 64, 4000, 8, 4)
                pLowRes = getSIFTMatchingParameters(nOctaves[0], 1.6, 16, 4000,
                                                    8, 4)  # for BIB

                featuresLM = getFeatures(imLMPath, pLowRes)
                featuresEM = getFeatures(imEMPath, pLowRes)

                matchingResults = getMatchingResults(featuresLM, featuresEM)
                if matchingResults is None:
                    IJ.log(
                        'No registration matching at low resolution matching step 1bis in layer '
                        + str(l).zfill(4))
                else:
                    model, inliers = matchingResults
                    distance = PointMatch.meanDistance(
                        inliers
                    )  # mean displacement of the remaining matching features
                    IJ.log('---Layer ' + str(l).zfill(4) + ' distance ' +
                           str(distance) + ' px with ' + str(len(inliers)) +
                           ' inliers')
                    if distance > matchingThreshold[0]:
                        IJ.log(
                            'Matching accuracy is lower than the threshold at the high resolution step 1bis - '
                            + str(l).zfill(4) + ' - distance - ' +
                            str(distance))
                    else:
                        affTransform = model.createAffine()
                        s1, s2 = getScalingFactors(affTransform)
                        IJ.log('Layer ' + str(l).zfill(4) +
                               ' scaling factors - step 1bis - ' + str(s1) +
                               ' - ' + str(s2) + '--' + str(s1 * s2) +
                               ' affDeterminant ' +
                               str(affTransform.getDeterminant()) +
                               ' nInliers ' + str(len(inliers)))
                        if (abs(s1 - 1) < 0.2) and (
                                abs(s2 - 1) < 0.2
                        ):  # scaling in both directions should be close to 1
                            IJ.log('First step 1bis ok - layer ' +
                                   str(l).zfill(4))
                            firstStepRegistered = True
                            loaderZ.serialize(
                                affTransform,
                                os.path.join(registeredFolder,
                                             'affineSerialized'))

            if not firstStepRegistered:
                IJ.log('The two first step trials in layer ' +
                       str(l).zfill(4) + ' have failed')
            else:
                # Affine transform and crop the LM, and compute a high res MLS matching
                with lock:  # only one trakem working at a time
                    # apply affTransform
                    patch = Patch.createPatch(pZ, imLMPath)
                    layerZ.add(patch)
                    patch.setAffineTransform(affTransform)
                    patch.updateBucket()

                    # crop and export
                    bb = Rectangle(0, 0, widthEM, heightEM)
                    affineCroppedIm = loaderZ.getFlatImage(
                        layerZ, bb, 1, 0x7fffffff, ImagePlus.GRAY8, Patch,
                        layerZ.getAll(Patch), True, Color.black, None)
                    affineCroppedImPath = os.path.join(
                        toRegisterFolder,
                        'affineCroppedLM_' + str(l).zfill(4) + '.tif')
                    IJ.save(affineCroppedIm, affineCroppedImPath)
                    affineCroppedIm.close()

                    layerZ.remove(patch)
                    layerZ.recreateBuckets()

                pHighRes = getSIFTMatchingParameters(nOctaves[1], 1.6, 64,
                                                     4096, 8, 4)
                featuresLM = getFeatures(affineCroppedImPath, pHighRes)
                featuresEM = getFeatures(imEMPath, pHighRes)

                # get the MLS
                matchingResults = getMatchingResults(featuresLM, featuresEM)
                if matchingResults is None:
                    IJ.log(
                        'It cannot be, there should be a good match given that an affine was computed. Layer '
                        + str(l).zfill(4))
                else:
                    model, inliers = matchingResults
                    affTransform = model.createAffine()
                    s1, s2 = getScalingFactors(affTransform)
                    IJ.log('Second step determinant - layer ' +
                           str(l).zfill(4) + ' - determinant - ' +
                           str(affTransform.getDeterminant()) + ' nInliers ' +
                           str(len(inliers)) + 'Scaling factors - step 2 - ' +
                           str(s1) + ' - ' + str(s2))
                    if (abs(s1 - 1) < 0.2) and (abs(s2 - 1) < 0.2) and len(
                            inliers
                    ) > 50:  # scaling in both directions should be close to 1
                        distance = PointMatch.meanDistance(
                            inliers
                        )  # mean displacement of the remaining matching features
                        if distance > matchingThreshold[1]:
                            IJ.log(
                                'Weird: matching accuracy is lower than the threshold at the high resolution step 2 - '
                                + str(l).zfill(4) + ' - distance - ' +
                                str(distance))
                        else:
                            mlst = MovingLeastSquaresTransform()
                            mlst.setModel(AffineModel2D)
                            mlst.setAlpha(1)
                            mlst.setMatches(inliers)

                            xmlMlst = mlst.toXML('\t')
                            with open(
                                    os.path.join(registeredFolder, 'MLST.xml'),
                                    'w') as f:
                                f.write(xmlMlst)

                            loaderZ.serialize(
                                mlst,
                                os.path.join(registeredFolder,
                                             'mlstSerialized'))

                            registrationStats.append(
                                [l, distance, len(inliers)])
Esempio n. 45
0
def run():
    print "===== Batch Convert Scan Image 4 ====="

    # Expecting one argument: the file path
    if len(sys.argv) < 2:
        print "   We need a hard-drive folder with .tif stacks as input"
        print "	  Usage: ./fiji-macosx bBatchConvertTo8Bitv3 <folder-path>/"

        # Prompt user for a folder
        sourceFolder = DirectoryChooser(
            "Please Choose A Directory Of .tif Files").getDirectory()
        if not sourceFolder:
            return
    else:
        sourceFolder = sys.argv[1]  #assuming it ends in '/'

    destFolder = sourceFolder + "scanimage4/"
    destMaxFolder = destFolder + "max/"

    #make destination directory
    if not os.path.isdir(destFolder):
        os.makedirs(destFolder)

    #make max destination directory
    if not os.path.isdir(destMaxFolder):
        os.makedirs(destMaxFolder)

    print "   Processing source folder: ", sourceFolder
    print "   Saving to destination folder: ", destFolder
    IJ.log("   ====== Starting Batch Convert Scan Image 4 ======")
    IJ.log("   Processing source folder: " + sourceFolder)
    IJ.log("   Saving to destination folder: " + destFolder)

    numOpened = 0
    numSaved = 0

    for filename in os.listdir(sourceFolder):
        startWithDot = filename.startswith(".")
        isMax = filename.endswith("max.tif")
        isTif = filename.endswith(".tif")

        if (not startWithDot) and (not isMax) and (isTif):
            shortName, fileExtension = os.path.splitext(filename)

            #source .tif output (after conversion)
            outPath = destFolder + filename

            #max projection output
            outMaxPath = destMaxFolder + "max_" + filename

            #before we open, check if eventual dest exists
            if os.path.exists(outPath):
                msgStr = "   Destination file exists, not processing the image:" + filename
                print msgStr
                IJ.log(msgStr)
                continue  #with next iteration

            print "   ===================================="
            msgStr = "   -> Opening " + sourceFolder + filename
            print msgStr
            IJ.log(msgStr)
            imp = IJ.openImage(sourceFolder + filename)
            if imp is None:
                msgStr = "	     ERROR: Could not open image from file: " + filename
                print msgStr
                IJ.log(msgStr)
                continue  #with next iteration

            imp.show()
            numOpened += 1

            msgStr = "      Original Image is: " + str(
                imp.width) + " X " + str(imp.height) + " X " + str(
                    imp.getNSlices())
            print msgStr
            IJ.log(msgStr)
            if 1:
                msgStr = "      Removing Calibration From ScanImage 4 .tif"
                print msgStr
                IJ.log(msgStr)

                #20140810, I CAN'T BELIEVE I FINALLY FOUND THIS !!!
                infoStr = imp.getProperty("Info")
                #print infoStr

                #scanimage4 has a linear Calibration Function: y = a+bx
                #  a: -32768.000000
                #  b: 1.000000
                #  Unit: "Gray Value"
                #for some reason scanimage4 is setting a linear image calibration, we see negative values but there are NOT there
                cal = imp.getCalibration()
                calCoeff = cal.getCoefficients()
                msgStr = '        calibration is y=ax+b' + ' a=' + str(
                    calCoeff[0]) + ' b=' + str(calCoeff[1])
                print msgStr
                IJ.log(msgStr)

                #append calibration to info string
                imp.setCalibration(None)
                infoStr += 'calibCoeff_a = ' + str(calCoeff[0]) + '\n'
                infoStr += 'calibCoeff_b = ' + str(calCoeff[1]) + '\n'

                #i have appended to Info, update it
                #found this burried here: http://code.google.com/p/fiji-bi/source/browse/ij/ImagePlus.java?repo=imageja&name=imagej
                imp.setProperty("Info", infoStr)

                #get and print out min/max
                theMin = StackStatistics(imp).min
                theMax = StackStatistics(imp).max
                msgStr = '        min=' + str(theMin) + ' max=' + str(theMax)
                print msgStr
                IJ.log(msgStr)

                #subtract the linear calibration slope 'a' (what about intercept 'b' ?)
                #coefficient 'a' is normally negative, this is what we are using 'Add'
                #run("Subtract...", "value=32768 stack");
                subArgVal = 'value=%s stack' % (calCoeff[0], )
                IJ.run('Add...', subArgVal)

                #save file
                fs = FileSaver(imp)
                msgStr = "      Saving File to" + outPath
                print msgStr
                IJ.log(msgStr)

                numSlices = imp.getNSlices()

                if (numSlices > 1):
                    fs.saveAsTiffStack(outPath)
                else:
                    fs.saveAsTiff(outPath)
                numSaved += 1

                #max
                if (numSlices > 1):
                    maxCmdParams = 'start=1' + ' stop=' + str(
                        numSlices) + ' projection=[Max Intensity]'
                    IJ.run("Z Project...", maxCmdParams)

                impMax = IJ.getImage()
                fs = FileSaver(impMax)
                print "      Saving Max File to", outMaxPath
                fs.saveAsTiff(outMaxPath)

                #close max
                impMax.changes = 0
                impMax.close()

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

            else:
                print "   File was not 16 bit???"

            imp.close()  #close original

        else:
            if (not startWithDot) and isTif:
                #print "   ===================================="
                print filename
                msgStr = "   -> Ignoring .tif:" + filename
                print msgStr
                IJ.log(msgStr)

    msgStr = "   Batch Convert Scan Image 4 is Done, Number Opened " + str(
        numOpened) + ", Number Saved " + str(numSaved)
    print "   ==="
    print msgStr
    print "   ==="
    IJ.log(msgStr)
Esempio n. 46
0
MagCParameters = fc.readMagCParameters(MagCFolder)

downsamplingFactor = MagCParameters['downsample_EM']['downsamplingFactor']
factorString = str(int(1000000 * downsamplingFactor)).zfill(8)

# read some metadata
EMMetadataPath = fc.findFilesFromTags(MagCFolder, ['EM', 'Metadata'])[0]
EMMetadata = fc.readParameters(EMMetadataPath)
numTilesX = EMMetadata['numTilesX']
numTilesY = EMMetadata['numTilesY']
xPatchEffectiveSize = EMMetadata['xPatchEffectiveSize']
yPatchEffectiveSize = EMMetadata['yPatchEffectiveSize']
tileOverlapX = EMMetadata['tileOverlapX']
tileOverlapY = EMMetadata['tileOverlapY']
nbLayers = EMMetadata['nSections']
IJ.log('There are ' + str(nbLayers) + ' EM layers')

##########################################
# Stitching of the low-res EM project
##########################################
allPatchCoordinates = []

downsampledFolder = os.path.join(MagC_EM_Folder, 'MagC_EM_' + factorString)
IJ.log('downsampledFolder ' + downsampledFolder)

foldersToStitch = [
    os.path.join(downsampledFolder, folderName)
    for folderName in os.walk(downsampledFolder).next()[1]
]
foldersToStitch = fc.naturalSort(foldersToStitch)
IJ.log('foldersToStitch -------------  ' + str(foldersToStitch))
Esempio n. 47
0
import fijiCommon as fc

namePlugin = 'init_EM'
MagCFolder = fc.startPlugin(namePlugin)
ControlWindow.setGUIEnabled(False)

EMDataFolder = os.path.join(MagCFolder, 'EMData')
MagCEMFolder = fc.makeNeighborFolder(EMDataFolder, 'MagC_EM')

imageFolders = [
    os.path.join(EMDataFolder, sectionFolderName)
    for sectionFolderName in fc.naturalSort(os.walk(EMDataFolder).next()[1])
]

nSections = len(imageFolders)
IJ.log('There are ' + str(nSections) + ' EM layers')

# reading EM metadata
EMMetadataPath = os.path.join(MagCEMFolder, 'EM_Metadata.txt')
try:  # old Atlas format
    mosaicMetadata = os.path.join(
        imageFolders[0],
        filter(lambda x: 'Mosaic' in x, os.listdir(imageFolders[0]))[0])
    root = ET.parse(mosaicMetadata).getroot()

    pixelSize = float(root.find('PixelSize').text)
    tileinfo = root.find('TileInfo')
    tileWidth = int(tileinfo.find('TileWidth').text)
    tileHeight = int(tileinfo.find('TileHeight').text)
    tileOverlapX = float(tileinfo.find('TileOverlapXum').text)
    tileOverlapY = float(tileinfo.find('TileOverlapYum').text)
Esempio n. 48
0
        settings.trackerSettings = LAPUtils.getDefaultLAPSettingsMap()
        settings.trackerSettings[
            'LINKING_MAX_DISTANCE'] = 5.  # KEY PARAMETER: don't let nuclei move more than 5 um between frames
        settings.trackerSettings['ALLOW_GAP_CLOSING'] = True
        settings.trackerSettings['MAX_FRAME_GAP'] = 2
        settings.trackerSettings['GAP_CLOSING_MAX_DISTANCE'] = 5.
        settings.trackerSettings['ALLOW_TRACK_SPLITTING'] = False
        settings.trackerSettings['ALLOW_TRACK_MERGING'] = False

        #-------------------
        # Instantiate plugin
        #-------------------
        trackmate = TrackMate(model, settings)

        if not trackmate.checkInput() or not trackmate.process():
            IJ.log('Could not execute TrackMate: ' +
                   str(trackmate.getErrorMessage()))
        else:
            IJ.log('TrackMate completed successfully.')
            IJ.log('Found %d spots in %d tracks.' %
                   (model.getSpots().getNSpots(True),
                    model.getTrackModel().nTracks(True)))

        # Now open the output file & write a header with each field you need. Fields:
        # Spot_ID, which is unique for each identified object
        # Track_ID, which is unique for each 'track' - i.e. same object over time
        # Frame, which specifies the current frame
        # X-Y-Z, which are the spatial locations of the tracked object at the current frame.
        headerStr = '%10s %10s %10s %10s %10s %10s' % ('Spot_ID', 'Track_ID',
                                                       'Frame', 'X', 'Y', 'Z')
        rowStr = '%10d %10d %10d %10.1f %10.1f %10.1f'
        # Finally, we also want the mean intensity of each tracked object in each frame.
def run():
    print "===== bBatchConvertTo8Bitv3 ====="

    global numberOfChannels
    global replaceExisting

    # Expecting one argument: the file path
    if len(sys.argv) < 2:
        print "   We need a hard-drive folder with .tif stacks as input"
        print "	  Usage: ./fiji-macosx bBatchConvertTo8Bitv3 <folder-path>/"

        # Prompt user for a folder
        sourceFolder = DirectoryChooser(
            "Please Choose A Directory Of .tif Files").getDirectory()
        if not sourceFolder:
            return
    else:
        sourceFolder = sys.argv[1]  #assuming it ends in '/'

    #get user options
    okGo = getOptions()  # creates {numberOfChannels, replaceExisting}
    if okGo == -1:
        return 0

    destFolder = sourceFolder + "channels8/"
    destMaxFolder = sourceFolder + "max/"

    #make destination directory
    if not os.path.isdir(destFolder):
        os.makedirs(destFolder)

    #make max destination directory
    if not os.path.isdir(destMaxFolder):
        os.makedirs(destMaxFolder)

    print "   Processing source folder: ", sourceFolder
    print "   Saving to destination folder: ", destFolder
    IJ.log("   ====== Startin bBatchConvertTo8Bitv3 ======")
    IJ.log("   Processing source folder: " + sourceFolder)
    IJ.log("   Saving to destination folder: " + destFolder)

    numOpened = 0
    numSaved = 0

    for filename in os.listdir(sourceFolder):
        startWithDot = filename.startswith(".")
        isMax = filename.endswith("max.tif")
        isTif = filename.endswith(".tif")

        if (not startWithDot) and (not isMax) and (isTif):
            shortName, fileExtension = os.path.splitext(filename)
            outPath = destFolder + "/" + filename
            outPath1 = destFolder + "/" + shortName + "_ch1" + ".tif"
            outPath2 = destFolder + "/" + shortName + "_ch2" + ".tif"

            #max projection output
            outMaxPath = destMaxFolder + "/" + "max_" + filename
            outMaxPath1 = destMaxFolder + "/" + "max_" + shortName + "_ch1" + ".tif"
            outMaxPath2 = destMaxFolder + "/" + "max_" + shortName + "_ch2" + ".tif"

            #before we open, check if eventual dest exists
            if not replaceExisting:
                if numberOfChannels == 2 and os.path.exists(
                        outPath1) and os.path.exists(outPath2):
                    msgStr = "   8-Bit Destination file exists, not processing the image:" + filename
                    print msgStr
                    IJ.log(msgStr)
                    continue  #with next iteration
                if numberOfChannels == 1 and os.path.exists(outPath):
                    msgStr = "   8-Bit Destination file exists, not processing the image:" + filename
                    print msgStr
                    IJ.log(msgStr)
                    continue  #with next iteration

            print "   ===================================="
            msgStr = "   -> Opening " + sourceFolder + filename
            print msgStr
            IJ.log(msgStr)
            imp = IJ.openImage(sourceFolder + filename)
            if imp is None:
                msgStr = "	     ERROR: Could not open image from file: " + filename
                print msgStr
                IJ.log(msgStr)
                continue  #with next iteration

            imp.show()
            numOpened += 1

            #i can't get properties as long list of {key=value}
            #how do i then set each property in new imp1/imp2? Do IJ.openImagehave ot loop?
            #infoProperty = imp.getInfoProperty() #Returns the "Info" property string, java.lang.String
            #print 'infoProperty'
            #print infoProperty

            #.getProp(key) #Returns the value from the "Info" property string associated with 'key'

            #myProp = imp.getProperties() #returns java.util.Properties
            #print 'myProp (really long)'
            #print myProp

            #print 'patrick'
            #myList = str(myProp).split('\r')

            #I want' to strip out 'Info=ImageDescription: '
            #myList = re.sub('Info=ImageDescription: ', '', str(myList))

            #for i in range (0,len(myList)):
            #	myList[i] = myList[i].split('=')

            #print myList[0]
            #print myList[1]
            #print myList[2]
            #print myList[3]

            #imp.setProperty('myStr', 1)

            #try usinf ImageStack
            #myImageStack = imp.getImageStack()

            #eventuallly just call imp.getProp(str) which Returns the value from the "Info"

            #in the future IJ.openImagehavewant to have option to scale down to 512X512
            #run("Scale...", "x=- y=- z=1.0 width=512 height=512 depth=196 interpolation=Bilinear average process create title=20131007_a144_008_ch1-1.tif");

            msgStr = "      Original Image is: " + str(
                imp.width) + " X " + str(imp.height) + " X " + str(
                    imp.getNSlices())
            print msgStr
            IJ.log(msgStr)
            if imp.getBitDepth() == 16:
                msgStr = "      Converting to 8-bit..."
                print msgStr
                IJ.log(msgStr)
                IJ.run("8-bit")

                if numberOfChannels == 2:
                    msgStr = "      deinterleaving"
                    print msgStr
                    IJ.run("Deinterleave", "how=2")
                    #makes 2 window

                    #
                    #ch2
                    imp2 = IJ.getImage()
                    fs = FileSaver(imp2)
                    msgStr = "      ch2: Saving deinterleaved 8bit File to: " + outPath2
                    print msgStr
                    IJ.log(msgStr)

                    numSlices = imp2.getNSlices()
                    if (numSlices > 1):
                        fs.saveAsTiffStack(outPath2)
                    else:
                        fs.saveAsTiff(outPath2)

                    #max, ch2
                    if (numSlices > 1):
                        maxCmdParams = 'start=1' + ' stop=' + str(
                            numSlices) + ' projection=[Max Intensity]'
                        IJ.run("Z Project...", maxCmdParams)
                        #impMax2 = IJ.getImage()

                    print "      Saving 8bit Max File to", outMaxPath2
                    impMax2 = IJ.getImage()
                    fs = FileSaver(impMax2)
                    fs.saveAsTiff(outMaxPath2)

                    impMax2.changes = 0
                    impMax2.close()

                    numSaved += 1
                    imp2.changes = 0
                    imp2.close()

                    #
                    #ch1
                    imp1 = IJ.getImage()
                    fs = FileSaver(imp1)
                    msgStr = "      ch1: Saving deinterleaved 8bit File to" + outPath1
                    print msgStr

                    numSlices = imp1.getNSlices()
                    if (numSlices > 1):
                        fs.saveAsTiffStack(outPath1)
                    else:
                        fs.saveAsTiff(outPath1)

                    #max, ch1
                    if (numSlices > 1):
                        maxCmdParams = 'start=1' + ' stop=' + str(
                            numSlices) + ' projection=[Max Intensity]'
                        IJ.run("Z Project...", maxCmdParams)

                    impMax1 = IJ.getImage()
                    fs = FileSaver(impMax1)
                    msgStr = "      Saving 8bit Max File to" + outMaxPath1
                    print msgStr
                    IJ.log(msgStr)
                    fs.saveAsTiff(outMaxPath1)
                    impMax1.changes = 0
                    impMax1.close()

                    numSaved += 1
                    imp1.changes = 0
                    imp1.close()

                elif numberOfChannels == 1:  #single channel
                    fs = FileSaver(imp)
                    msgStr = "      Saving 8bit File to" + outPath
                    print msgStr
                    IJ.log(msgStr)

                    numSlices = imp.getNSlices()

                    if (numSlices > 1):
                        fs.saveAsTiffStack(outPath)
                    else:
                        fs.saveAsTiff(outPath)
                    numSaved += 1

                    #max
                    if (numSlices > 1):
                        maxCmdParams = 'start=1' + ' stop=' + str(
                            numSlices) + ' projection=[Max Intensity]'
                        IJ.run("Z Project...", maxCmdParams)

                    impMax = IJ.getImage()
                    fs = FileSaver(impMax)
                    print "      Saving 8bit Max File to", outMaxPath
                    fs.saveAsTiff(outMaxPath)
                    impMax.changes = 0
                    impMax.close()

                    imp.changes = 0
                    imp.close()

            else:
                print "   File was not 16 bit???"

            imp.close()  #close original

        else:
            if (not startWithDot) and isTif:
                #print "   ===================================="
                print filename
                msgStr = "   -> Ignoring .tif:" + filename
                print msgStr
                IJ.log(msgStr)

    msgStr = "   bBatchConvertTo8Bitv3.py is Done, Number Opened " + str(
        numOpened) + ", Number Saved " + str(numSaved)
    print "   ==="
    print msgStr
    print "   ==="
    IJ.log(msgStr)
Esempio n. 50
0
from ij import IJ
import sys

image = IJ.getImage()
if image == None:
	sys.exit("No open image")
	
roi = image.getRoi()
if roi == None:
	sys.exit("Image has no ROI")
	
polygon = roi.getPolygon()
if polygon == None:
	sys.exit("ROI has no polygon??")

IJ.log("ROI polygon has {} points".format(polygon.npoints))
for i in range(polygon.npoints):
	IJ.log("{} {}".format(polygon.xpoints[i], polygon.ypoints[i]))
        smtpObj = smtplib.SMTP("smtp.unibas.ch")
        smtpObj.sendmail(
            sender, recipient,
            message % (recipient, filename, total_execution_time_min))
        print "Successfully sent email"
    except smtplib.SMTPException:
        print "Error: unable to send email"


# start the process
execution_start_time = time.time()
source = fix_ij_dirs(source)
all_source_dirs = list_dirs_containing_filetype(source, filetype)

for source in all_source_dirs:
    IJ.log("now working on " + source)
    print "bigdata= ", str(bigdata)
    free_memory_bytes = MemoryTools().totalAvailableMemory()
    folder_size_bytes = get_folder_size(source)
    if free_memory_bytes / folder_size_bytes < 3.5:
        bigdata = True
        IJ.log("not enough free RAM, switching to BigData mode (slow)")

    allimages = list_all_filenames(source, filetype)
    ome_metadata = get_ome_metadata(source, allimages)
    write_tileconfig(source, ome_metadata[0], allimages, ome_metadata[4],
                     ome_metadata[5], ome_metadata[6])
    run_GC_stitcher(source)

    if bigdata is True:
        path = source + "temp/"
Esempio n. 52
0
def getArea(roi_array = RoiManager.getInstance().getRoisAsArray()):
    return [roi.getStatistics().area for roi in roi_array]

area = getArea()


def get_file_info(imp):
    img_dir = imp.getOriginalFileInfo().directory
    img_file = imp.getOriginalFileInfo().fileName
    if img_dir and img_file is not None:
        name, ext = os.path.splitext(img_file)
        return img_dir, name

img_dir, file_name = get_file_info(imp)

IJ.log("\\Clear")
IJ.log(
"directory"+ "\t" + 
"file_name"+ "\t" + 
"Roi_id" + "\t" + 
"frame_position" + "\t" +
"area" + "\t" +
"xcentroid" + "\t" +
"ycentroid" + "\t" +
"xpoint" + "\t" +
"ypoint"
)


def write_log(img_dir, file_name, roi_name, frame_position, area,  xcentroid, ycentroid, xpoint, ypoint):
    for i in range(len(roi_array)):
Esempio n. 53
0
def process_cell(cs):
    IJ.log('Cell at {}'.format(cs.center))
    cs.set_calibration()

    # filter the image
    if method != 'none':
        IJ.log('Applying ' + method + ' 3D filtering')
        filter_cellstack(cs, method=method, sigma=sigma)

    # cell stats
    loc_max = local_max(cs, cs.center)
    IJ.log('Local max in {}, value: {}'.format(loc_max, cs.get_voxel(loc_max)))

    if recenter:
        cs.center = loc_max

    loc_mean = local_mean(cs, r0=r0, r1=r1, r2=r2, weight=meanw)
    IJ.log('Local mean: ' + str(loc_mean))

    tab = radial_distribution_3D(cs, max_rad=max_rad)

    radius = radius_thresh(tab, loc_mean)
    IJ.log('Radius: ' + str(radius))

    # find local maxima in the whole image, even those far from the cell center
    peaks = find_maxima(cs, radius / 2, loc_mean)
    IJ.log('Peaks: ' + str(peaks))

    # run mean shift with maxima that are closer to the cell center
    IJ.log('Applying mean shift...')
    centroid = ms_center(cs, radius, peaks, ms_sigma, loc_mean)
    IJ.log('New center: ' + str(centroid))

    # update the centroid
    cs.center = centroid

    # apply local_mean thresh to radial distribution
    new_loc_mean = local_mean(cs,
                              r0=radius - 2,
                              r1=radius + 2,
                              r2=r2,
                              weight=meanw)
    IJ.log('New local mean: ' + str(new_loc_mean))

    new_tab = radial_distribution_3D(cs, max_rad=max_rad)

    new_radius = radius_thresh(new_tab, new_loc_mean)
    IJ.log('New radius: ' + str(new_radius))

    # apply a different look up table for display
    if cmap != 'default':
        apply_lut(cs, cmap)

    # show the cell stack positioned in the cell center
    cs.setSlice(cs.center[2] + 1)

    if circle:
        # circle_roi(cs, radius, Color.YELLOW)
        circle_roi(cs, new_radius, Color.RED)

    # draw point for new centroid
    # point = PointRoi(cs.center[0], cs.center[1])
    # point.setSize(2)
    # point.setColor(Color.RED)
    # cs.setRoi(point)

    cs.show()
    w = cs.getWindow()
    w.setLocationAndSize(1550, 400, 300, 300)
Esempio n. 54
0
fragments_group_name = "Isolated synaptic terminals"

# FIXME: And also hardcode the separation:

x_separation = 4.0
z_separation = 50.0

radius_node_class = Class.forName('ini.trakem2.display.Treeline$RadiusNode')

# Set up the JDBC connection:

try:
  Class.forName("org.postgresql.Driver")
except:
  IJ.log("Failed to find the postgresql driver...")
  raise

conf = {}
fp = open(os.path.join(os.environ['HOME'],'.catmaid-db'))
for line in fp:
  line = line.strip()
  if len(line) == 0:
    continue
  m = re.search('(\S*)\s*:\s*(\S*)', line)
  if m:
    conf[m.group(1)] = m.group(2)
fp.close()

database_url = "jdbc:postgresql://%s/%s" % (conf['host'], conf['database'])
Esempio n. 55
0
regParams.featuresModelIndex = 1

regParams.sift.fdBins = 8
regParams.sift.fdSize = 4
regParams.sift.initialSigma = 1.6
regParams.sift.maxOctaveSize = 1024
regParams.sift.minOctaveSize = 64
regParams.sift.steps = 6

regParams.interpolate = True
regParams.maxEpsilon = 25
regParams.minInlierRatio = 0
regParams.rod = 0.92

# perform alignment
if executeAlignment:
    fc.rigidAlignment(projectPath,
                      regParams,
                      name=namePlugin,
                      boxFactor=boxFactor)

# open the project and save all transforms of all tiles in all sections
IJ.log('Saving the coordinates transforms of each patch of each layer')
project, loader, layerset, nLayers = fc.openTrakemProject(projectPath)
transformsPath = os.path.join(os.path.dirname(projectPath),
                              namePlugin + 'transforms.txt')
fc.writeAllAffineTransforms(project, transformsPath)
fc.closeProject(project)

fc.terminatePlugin(namePlugin, MagCFolder)
    moptions = Measurements.MEAN | Measurements.AREA

    for roi in roi_array:

        roi_name = roi.getName()
        ip.setRoi(roi)
        stat = ImageStatistics.getStatistics(ip, moptions, cal)

        IJ.log(img_dir + "\t" + img_file + "\t" + roi_name + "\t" +
               str(stat.pixelCount) + "\t" +
               str(stat.pixelCount * stat.umean) + "\t" + str(stat.umean))
    rm.runCommand("delete")


def measure_multi_roiset(name_list, tif_list, roiset_list):
    if name_list and tif_list and roiset_list is not None:
        for name in name_list:
            for tif in tif_list:
                for roiset in roiset_list:
                    if name in roiset and name in tif:
                        measure_rm(tif, roiset)


IJ.log("\\Clear")

IJ.log("Directory" + "\t" + "File" + "\t" + "Roi_id" + "\t" + "Area" + "\t" +
       "Integrated_density" + "\t" + "Mean_intensity")

measure_multi_roiset(name_list, tif_list, roiset_list)
Esempio n. 57
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))
Esempio n. 58
0
def loadStacks():

    IJ.log(" ")
    IJ.log("oib_tiff_converter_ver1.0; 08/24/2018; [email protected]")
    IJ.log("tested with: ImageJ2; FIJI update on 8/24/2018")

    srcDir = DirectoryChooser("Choose directory").getDirectory()
    if not srcDir:
        return

    sId = ".oib"

    #stackType = getChoice("", ["normal stack", "virtual stack"])
    stackType = "normal stack"  # Concatenate seems not to work with virtual
    #filepath = srcDir +"tiff"
    #print(filepath)
    iStack = 0
    for root, directories, filenames in os.walk(srcDir):
        for filename in filenames:
            path = os.path.join(root, filename)
            if not (sId in filename):
                continue

            IJ.log("opening " + filename)

            if stackType == "virtual stack":
                IJ.run(
                    "Bio-Formats Importer", "open=" + path +
                    " color_mode=Default view=[Standard ImageJ] stack_order=Default use_virtual_stack"
                )
            else:
                IJ.run(
                    "Bio-Formats Importer", "open=" + path +
                    " color_mode=Default view=[Standard ImageJ] stack_order=Default"
                )

            # first stack
            if iStack == 0:
                imp = IJ.getImage()
                imp.setTitle(
                    filename +
                    ".tiff")  # in order of the combining to work additive
                nSlices = imp.getNSlices()
                nChannels = imp.getNChannels()
                nTimeFrames = imp.getNFrames()
                imp.setDimensions(nChannels, nSlices, nTimeFrames)
                comp = CompositeImage(imp, CompositeImage.COLOR)
                comp.show()
                fs = FileSaver(comp)
                fs.saveAsTiff(srcDir + filename + "_hyperstack" + ".tiff")

            else:
                imp = IJ.getImage()
                comp = CompositeImage(imp, CompositeImage.COLOR)
                comp.show()
                fs = FileSaver(comp)
                fs.saveAsTiff(srcDir + filename + "_hyperstack" + ".tiff")
            iStack = iStack + 1
            print(iStack)

        #IJ.log("nChannels = "+str(nChannels))
        #IJ.log("nSlices = "+str(nSlices))
        #IJ.log("nFrames = "+str(nTimeFrames*iStack))
        #IJ.run("Stack to Hyperstack...", "order=xyczt(default) channels="+str(nChannels)+" slices="+str(nSlices)+" frames="+str(nTimeFrames)+" display=Color");
        IJ.log(
            "convert back to normal stack: Image...Hyperstacks...Hyperstack to Stack"
        )
    original)  # duplicate the original image, only the CFOV
CFOV.setTitle("CFOV")
CFOV.show()

######### Nema process including Re-bin image to larger pixels ################################################################################
desired_pixel_width = getPixel(
)  # 6.4 mm default, remember tolerance is +/-30%
current_pixel_width = CFOV.getCalibration(
).pixelWidth  #get pixel width, 1.16 mm
shrink_factor = int(desired_pixel_width /
                    current_pixel_width)  # must be an integer

IJ.run(CFOV, "Bin...", "x=" + str(shrink_factor) + " y=" + str(shrink_factor) +
       " bin=Sum")  # run the bin plugin
IJ.run(CFOV, "Convolve...",
       "text1=[1 2 1\n2 4 2\n1 2 1\n] normalize")  # apply the nema filter

######## Analyse pixels
CFOVpixels = CFOV.getProcessor().convertToFloat().getPixels(
)  # access processor, get float array of pixels
CFOVmean = sum(CFOVpixels) / len(CFOVpixels)
#pixels_above_threshold = filter(lambda pix: pix > 0.75*mean, pixels)  # return a new array with values above zero, use anonymous function
CFOVunifiormity = getUniformity(min(CFOVpixels), max(CFOVpixels))

######## Print results
results_string = "The integral uniformity of the CFOV is: " + str(
    CFOVunifiormity) + "% for pixel size of " + str(
        desired_pixel_width) + " mm"
IJ.log(results_string)
IJ.showMessage(results_string)
Esempio n. 60
0
    gui.showDialog()
    HOST = gui.getNextString()
    PORT = int(gui.getNextString())

    gui = GenericDialogPlus("Parameters")
    gui.addFileField("Select an input file (*.tif) : ", "")
    gui.showDialog()
    if gui.wasOKed():
        LOCAL_IMAGE_FILENAME = gui.getNextString()

    LOCAL_RESULT_FILENAME = LOCAL_IMAGE_FILENAME + "_prediction.tif"

jsch = JSch()

# SSH Connection to DeepLearning server
IJ.log("-- Connection to Deep Learning Server")
time0 = time.time()
session = jsch.getSession("root", HOST, PORT)
session.setPassword("12345")
session.setConfig("StrictHostKeyChecking", "no")
session.connect()
IJ.log("Execution Time : " + str(time.time() - time0) + " seconds")

if (True):
    #Download results
    channel = session.openChannel("sftp")
    channel.connect()
    IJ.open(LOCAL_IMAGE_FILENAME)
    IJ.log("Opening : " + LOCAL_IMAGE_FILENAME)
    IJ.log('-- Uploading image to server ... please wait')
    channel.put(LOCAL_IMAGE_FILENAME, "/content/toprocess.tif")