def findclearcell(inDir, currentDir, fileName):
  print "Opening", fileName
  file_path= os.path.join(currentDir, fileName)
  options = ImporterOptions()
  options.setId(file_path)
  options.setSplitChannels(True)
  imps = BF.openImagePlus(options)
  for imp in imps:
  	imp.show()
  if not imps:
  	return
  IJ.selectWindow(fileName + " - C=2")
  IJ.run("Close")
  IJ.selectWindow(fileName + " - C=1")
  IJ.run("Close")
  IJ.selectWindow(fileName + " - C=0")
  IJ.run("Close")
  IJ.selectWindow(fileName + " - C=3")
  IJ.run("8-bit")
  IJ.run("Options...", "iterations=1 count=1 black edm=8-bit")
  IJ.setThreshold(62, 255)
  IJ.run("Convert to Mask", "method=Default backgorund=Dark black")
  Macro.setOptions("Stack position")
  for n in range(4,15):
	n+=1
	IJ.setSlice(n)
	IJ.run(imp, "Analyze Particles...", "size=7.2-9 circularity=0.7-0.95 display")
예제 #2
0
def createOutputData( jobs ):
    """ Reads out the meta data.
    """
    failedImages = []
    nJobs = len( jobs )
    for n, j in enumerate( jobs ):
        print( "Job " + str(n+1) + "/" + str( nJobs ) )
        # load every image
        metadata = []
        nImages = len( j.sourceImages )
        nChannels = -1
        for m, img in enumerate( j.sourceImages ):
            print( "\tReading image " + str(m+1) + "/" + str( nImages ) )
            imgPath = os.path.join( j.sourcePath, img )
            options = ImporterOptions()
            options.setId( imgPath )
            options.setSplitChannels( False )
            options.setWindowless( True )
            options.setVirtual( True )
            imps = BF.openImagePlus( options )
            if len(imps) == 0:
                failedImages.append( imgPath )
                print("t\tCould not load image: " + imgPath)
                continue
            # get the meta data
            data = imps[0]
            if nChannels == -1:
                nChannels = data.getNChannels() 
            imgInfo = Info();
            info = imgInfo.getImageInfo( data, data.getChannelProcessor() )
            metadata.append( imgPath )
            metadata.append( info )
        j.outputData = '\n\n>>> next source file >>>\n\n'.join( metadata )
        j.numChannels = nChannels
예제 #3
0
def open_image(imgfile):
	options = ImporterOptions()
	options.setId(imgfile)
	options.setSplitChannels(False)
	options.setColorMode(ImporterOptions.COLOR_MODE_COMPOSITE)
	imps = BF.openImagePlus(options)
	splitimps = [ImagePlus("%s-C-%i" % (imps[0].getTitle(), i),imps[0].getStack().getProcessor(i)) for i in range(1,imps[0].getNChannels()+1)] 
	for si in splitimps:
		si.setCalibration(imps[0].getCalibration().copy())
	return imps[0], splitimps
예제 #4
0
def import_image(filename,
                 color_mode='color',
                 split_c=False, split_z=False, split_t=False):
    """Open an image file using the Bio-Formats importer.

    Parameters
    ----------
    filename : str
        The full path to the file to be imported through Bio-Formats.
    color_mode : str, optional
        The color mode to be used for the resulting ImagePlus, one of 'color',
        'composite', 'gray' and 'default'.
    split_c : bool, optional
        Whether to split the channels into separate ImagePlus objects.
    split_z : bool, optional
        Whether to split the z-slices into separate ImagePlus objects.
    split_t : bool, optional
        Whether to split the time points into separate ImagePlus objects.

    Returns
    -------
    ij.ImagePlus[]
        A list of ImagePlus objects resulting from the import.
    """
    options = ImporterOptions()
    mode = {
        'color' : ImporterOptions.COLOR_MODE_COLORIZED,
        'composite' : ImporterOptions.COLOR_MODE_COMPOSITE,
        'gray' : ImporterOptions.COLOR_MODE_GRAYSCALE,
        'default' : ImporterOptions.COLOR_MODE_DEFAULT,
    }
    options.setColorMode(mode[color_mode])
    options.setSplitChannels(split_c)
    options.setSplitFocalPlanes(split_z)
    options.setSplitTimepoints(split_t)
    options.setId(filename)
    log.info("Reading [%s]", filename)
    orig_imps = BF.openImagePlus(options)
    log.debug("Opened [%s] %s", filename, type(orig_imps))
    return orig_imps
예제 #5
0
def saveMip(img, file_path):
    if mipPrefTIFF:
        FileSaver(img).saveAsTiff(file_path + ".tiff")
    if mipPrefJPG:
        FileSaver(img).saveAsJpeg(file_path + ".jpg")


for root, dirs, files in os.walk(inDir):
    for file in files:
        if file.endswith(fileExt):
            logging.info('Starting image #%i (%s)', imageCount, str(file))
            options = ImporterOptions()
            options.setAutoscale(True)
            options.setId(os.path.join(root, file))
            options.setSplitChannels(True)
            imps = BF.openImagePlus(options)
            imageCount += 1
            for imp in imps:
                reader = ImageReader()
                omeMeta = MetadataTools.createOMEXMLMetadata()
                reader.setMetadataStore(omeMeta)
                reader.setId(os.path.join(root, file))

                filename = str(imp)
                channel_id = int(re.findall("C=(\d)", filename)[0])
                channel_name = omeMeta.getChannelName(0, channel_id)
                out_name = filename.split('"')[1]
                out_name = out_name.split(fileExt)[0] + "_" + str(channel_name)
                out_name = out_name.replace(" ", "")
def main():

    Interpreter.batchMode = True

    if (lambda_flat == 0) ^ (lambda_dark == 0):
        print ("ERROR: Both of lambda_flat and lambda_dark must be zero,"
               " or both non-zero.")
        return
    lambda_estimate = "Automatic" if lambda_flat == 0 else "Manual"

    print "Loading images..."

    options = ImporterOptions()
    options.setId(str(filename))
    options.setOpenAllSeries(True)
    options.setConcatenate(True)
    options.setSplitChannels(True)
    imps = BF.openImagePlus(options)

    num_channels = len(imps)
    w = imps[0].getWidth()
    h = imps[0].getHeight()
    ff_imp = IJ.createImage("Flat-field", w, h, num_channels, 32);
    df_imp = IJ.createImage("Dark-field", w, h, num_channels, 32);

    basic = Basic()
    Basic_noOfSlices = Basic.getDeclaredField('noOfSlices')
    Basic_noOfSlices.setAccessible(True)

    for channel, imp in enumerate(imps):
        title = imp.getTitle()
        print "Processing:", title
        x, y, c, z, t = imp.getDimensions()
        assert z == 1 and c == 1
        imp.setDimensions(1, t, 1)

        WindowManager.setTempCurrentImage(imp)
        Basic_noOfSlices.setInt(basic, t)
        basic.exec(
            imp, None, None,
            "Estimate shading profiles", "Estimate both flat-field and dark-field",
            lambda_estimate, lambda_flat, lambda_dark,
            "Ignore", "Compute shading only"
        )
        ff_channel = WindowManager.getImage('Flat-field:' + title)
        ff_channel.copy()
        ff_imp.setSlice(channel + 1)
        ff_imp.paste()
        ff_channel.close()

        df_channel = WindowManager.getImage('Dark-field:' + title)
        df_channel.copy()
        df_imp.setSlice(channel + 1)
        df_imp.paste()
        df_channel.close()

        imp.close()

    # Setting the active slice back to 1 seems to fix an issue where
    # the last slice was empty in the saved TIFFs. Not sure why.
    ff_imp.setSlice(1)
    df_imp.setSlice(1)

    ff_filename = '%s/%s-ffp-basic.tif' % (output_dir, experiment_name)
    IJ.saveAsTiff(ff_imp, ff_filename)
    ff_imp.show()
    ff_imp.close()

    df_filename = '%s/%s-dfp-basic.tif' % (output_dir, experiment_name)
    IJ.saveAsTiff(df_imp, df_filename)
    df_imp.show()
    df_imp.close()

    print "Done!"
예제 #7
0
def imageprojector(channels, timelist_unsorted, dirs):
	""" Projects .lif timepoints and saves in a common directory,
	    as well as channel separated directories. """
	
	# Defines in path
	path = str(Experiment)

	# BF Importer
	options = ImporterOptions()
	
	try:
		options.setId(path)
	except Exception(e):
		print str(e)
		
	options.setOpenAllSeries(True)
	options.setSplitTimepoints(True)
	options.setSplitChannels(True)
	imps = BF.openImagePlus(options)

	timelist = [x for item in timelist_unsorted for x in repeat(item, channels)]
	timelist, imps = zip(*sorted(zip(timelist, imps)))

	
	counter_C0 = -1
	counter_C1 = -1
	counter_C2 = -1
	# Opens all images, splits channels, z-projects and saves to disk
	for imp in (imps):
		# Projection, Sum Intensity
   		project = ZProjector()
		project.setMethod(ZProjector.SUM_METHOD)
		project.setImage(imp)
		project.doProjection()
		impout = project.getProjection()
		projection = impout.getTitle()

		try:
			# Saves channels to disk, 
			# add more channels here if desired, 
			# remember to define new counters.
			if "C=0" in projection:
				counter_C0 += 1
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections"],
				          "Scan" + str(counter_C0).zfill(3) + "C0"))
                
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections_C0"],
				          "Scan" + str(counter_C0).zfill(3) + "C0"))		
			
			elif "C=1" in projection:
				counter_C1 += 1
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections"],
				          "Scan" + str(counter_C1).zfill(3) + "C1"))
                         
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections_C1"],
				          "Scan" + str(counter_C1).zfill(3) + "C1"))

			elif "C=2" in projection:
				counter_C2 += 1
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections"],
				          "Scan" + str(counter_C2).zfill(3) + "C2"))
                         
				IJ.saveAs(impout, "TIFF", os.path.join(dirs["Projections_C2"],
				          "Scan" + str(counter_C2).zfill(3) + "C2"))
		
		except IOException:
			print "Directory does not exist"
			raise

	IJ.log("Images projected and saved to disk")