示例#1
1
def main():
    # Open a .ome.tif image from the Flexoscope.
    impath = IJ.getFilePath("Choose .ome.tiff file")
    channels = Opener.openUsingBioFormats(impath)

    # Show image
    # imp.show() # straight to channels object sames memory.

    # Split channels.
    channels = ChannelSplitter().split(channels)

    # Process channel 1.
    # subtractzproject(imp, projectionMethod="Median")
    channels[1] = ImagePlus()
    channels.append(ImagePlus())
    channels[1] = subtractzproject(channels[0])
    IJ.run(channels[0], "Enhance Contrast...", "saturated=0.3 normalize process_all use")
    IJ.run(channels[0], "8-bit", "") 
    IJ.run(channels[1], "Square", "stack")
    IJ.run(channels[1], "Enhance Contrast...", "saturated=0.3 normalize process_all use")
    IJ.run(channels[1], "8-bit", "") 

    # Merge channels.
    merge = RGBStackMerge().mergeChannels(channels, True) # boolean keep
    merge.show()
def measureOneFile(nucfilepath):
  #parent = os.path.dirname(nucfilepath)
  #gparent = os.path.dirname(parent)
  #gparentname = os.path.basename(gparent)
  #ggparent = os.path.dirname(gparent)
  iodefectflag = 0
  op = Opener()
  filetype = op.getFileType(nucfilepath)
  if filetype == Opener.TIFF:
    imp = op.openImage(nucfilepath)
    imgtitle = imp.getTitle()
    imgstats = imp.getStatistics()
    intrange = imgstats.max - imgstats.min
    #print imgtitle, imp.getWidth(), 'x', imp.getWidth(), 'Max - Min', intrange, 'SD', imgstats.stdDev
    print imgtitle, imp.getWidth(), 'x', imp.getWidth(), 'Mean', imgstats.mean, 'SD', imgstats.stdDev

  #outfilename = gparentname + imgtitle + ".csv"
  #outdir = os.path.join(ggparent, 'outfiles')
  #if not os.path.isdir(outdir):
    #os.mkdir(outdir)
  #outpath = os.path.join(ggparent, 'outfiles', outfilename)
  #print outpath
  #outlist = ["'" + imgtitle + "'", intrange, imgstats.stdDev]
    outlist = ["'" + imgtitle + "'", imgstats.mean, imgstats.stdDev]
  else:
    iodefectflag = 1
    filename = os.path.basename(nucfilepath)
    print "****** Could not open:",filename 
    outlist = ["'" + filename + "'", 1.0, 1.0]
  return outlist, nucfilepath, iodefectflag
def import_multiple_rois(roi_files):
	rois = [f.getPath() for f in roi_files if f.exists() and f.getName().lower().endswith("roi")]
	opener = Opener()
	rm = RoiManager.getRoiManager()
	if not rm.getInstance():
		rm.reset()
	[rm.addRoi(opener.openRoi(r)) for r in rois]
示例#4
0
def resizeAndSave(filePaths, l):
	while l.get() < min(len(filePaths), currentWrittenLayer + nTilesAtATime + 1) :
		k = l.getAndIncrement()
		if k < min(len(filePaths), currentWrittenLayer + nTilesAtATime):

			filePath = filePaths[k]
			
			imageName = os.path.basename(filePath)
			resizedImageName = os.path.splitext(imageName)[0] + '_resized_' + factorString + os.path.splitext(imageName)[1]
			
			imageFolderName = os.path.basename(os.path.dirname(filePath))
			
			resizedFilePath = fc.cleanLinuxPath(os.path.join(downSampledEMFolder, imageFolderName, resizedImageName))
			
			im = Opener().openImage(filePath)
			IJ.log('Am I going to process the image: im.height = ' + str(im.height) + ' - tileHeight = ' + str(tileHeight) + ' tile number ' + str(k))
			if im.height == tileHeight: # crop a few lines at the top only if it has not already been done (sometimes the pipeline gets rerun)
				im = fc.crop(im,cropRoi)
				im = fc.normLocalContrast(im, normLocalContrastSize, normLocalContrastSize, 3, True, True)
				# IJ.run(im, 'Replace value', 'pattern=0 replacement=1') # only for final waferOverview
				FileSaver(im).saveAsTiff(filePath)
				
			if not os.path.isfile(resizedFilePath):
				im = fc.resize(im, scaleFactor)
				FileSaver(im).saveAsTiff(resizedFilePath)
				IJ.log('Image resized to ' + resizedFilePath)
			im.close()
def normalized_roi_length(roi_path, pixel_scaling, normalization_fn=None):
    '''
	Returns the scaled measure of the input roi performing the normalization
	function if provided. 
	'''
    opener = Opener()
    roi = opener.openRoi(roi_path)
    scaled_measure = roi.getLength() / pixel_scaling
    if callable(normalization_fn):
        return normalization_fn(scaled_measure)
    return measure
def file_opener(current_title, extension):
    for filename in os.listdir(dest):
        i = 0
        if filename.endswith(file_type):
            pass
            if filename != current_title:
                pass
                if not filename.startswith(extension) and i == 0:
                    O = Opener()
                    path = os.path.join(dest, filename)
                    O.open(path)
                    i += 1
                    break
示例#7
0
def combinestacks(directory, height=5):
    """Combine all tiff stacks in a directory to a panel.

    Args:
        directory: Path to a directory containing a collection of .tiff files.
        height: The height of the panel (integer). Defaults to 5. The width is spaces automatically.

    Returns:
        A combined stack of the input images.
    """

    IJ.log("\nCombining stacks...")
    files = [
        f for f in sorted(os.listdir(directory))
        if os.path.isfile(os.path.join(directory, f))
    ]
    IJ.log("Number of files: {}".format(len(files)))
    groups = chunks(files, height)

    horiz = []
    for group in groups:
        h = [Opener().openImage(directory, imfile) for imfile in group]
        h = _horcombine(h)
        # h.show()
        horiz.append(h)

    montage = _vercombine(horiz)
    montage.show()
示例#8
0
文件: fijipytools.py 项目: soyers/OAD
    def openjpg(imagefile, metainfo, method='IJ',
                                     series=0):

        if method == 'IJ':

            # using IJ static method
            imp = IJ.openImage(imagefile)

        if method == 'Opener':

            # Using Opener class
            imp = Opener().openImage(imagefile)

        if method == 'BF':

            # using BioFormats library
            imps = BF.openImagePlus(imagefile)

            # read image data using the specified pyramid level
            imp, slices, width, height, pylevel = ImageTools.getImageSeries(imps, series=series)
            metainfo['Output Slices'] = slices
            metainfo['Output SizeX'] = width
            metainfo['Output SizeY'] = height

        return imp, metainfo
示例#9
0
def main():
    # Open a .ome.tif image from the Flexoscope.
    impath = IJ.getFilePath("Choose .ome.tiff file")
    channels = Opener.openUsingBioFormats(impath)
    cal = channels.getCalibration()

    # Show image
    # imp.show() # straight to channels object sames memory.

    # Split channels.
    channels = ChannelSplitter().split(channels)

    # Process channel 1.
    # subtractzproject(imp, projectionMethod="Median")
    channels[0] = subtractzproject(channels[0])
    IJ.run(channels[0], "8-bit", "") 

    # Process channel 2.
    # glidingprojection(imp, startframe=1, stopframe=None, glidingFlag=True, no_frames_per_integral=3, projectionmethod="Median")
    channels[1] = glidingprojection(channels[1]) 
    IJ.run(channels[1], "8-bit", "") 

    # [Optional] Process channel 3, 4, etc.
    # subtractzproject(channels[3], projectionMethod="Median")
    # glidingprojection(channels[3], startframe=1, stopframe=None, glidingFlag=True, no_frames_per_integral=3, projectionmethod="Median")
    # IJ.run(channels[3], "8-bit", "") 

    # Merge channels.
    merge = RGBStackMerge().mergeChannels(channels, True) # boolean keep
    merge.setCalibration(cal)
    merge.show()
示例#10
0
def convert32to16(fullFilePath):  #overwrite the file!!!
    if not os.path.isfile(fullFilePath):
        bPrintLog(
            '\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n',
            0)
        return 0
    elif not fullFilePath.endswith('tif'):
        msg = fullFilePath + " is not a deconvoluted tif file"
        bPrintLog(msg, 2)
    else:
        bPrintLog(
            time.strftime("%H:%M:%S") +
            ' starting runOneFile()for overwrite: ' + fullFilePath, 1)

        #open and overwrite the deconvoluted file as 16 bit
        imp = Opener().openImage(fullFilePath)  #deconvoluted file
        if imp.getBitDepth() == 32:
            imp.show()
            msgStr = "Converting 32 to 16-bit..."
            bPrintLog(msgStr, 3)
            IJ.run("16-bit")

            msgStr = "Overwriting 32-bit with 16-bit File in" + fullFilePath
            bPrintLog(msgStr, 3)
            IJ.run(imp, "Save", "")  #save as replace without asking

        imp.close()
def get_enhance_bounds(chf_fpaths, low_theshold, high_threshold):
    # initialize the pixels array
    pix = []
    # open 100 images max (time consuming)
    if len(chf_fpaths) > 100:
        chf_fpaths = random.sample(chf_fpaths, 100)
    # create a for loop here
    counter = 1
    for image_path in chf_fpaths:
        # open the image
        print "Getting pixels in Image " + image_path
        print str(counter) + " / " + str(len(chf_fpaths))
        counter += 1
        imp_orig = Opener().openImage(image_path)
        # get the pixel values
        image_pix = list(imp_orig.getProcessor().getPixels())
        imp_orig.close()
        imp_orig.flush()
        # select randomly 10% of the pixels (maybe memory issues)
        image_pix_sel = random.sample(image_pix, int(len(image_pix) * 0.1))
        pix = pix + image_pix_sel

    # get the percentile values to threshold
    IJ.log('Quantifying pixel values for contrast enhancement...')
    low_pix = percentile(pix, low_theshold)
    high_pix = percentile(pix, high_threshold)

    return low_pix, high_pix
def FindThreholds(mainpath, listOfImages, quantArray):
    #initialize the pixels array
    pix = []
    #create a for loop here
    for image in listOfImages:
        #open the image
        IJ.log('Getting pixels in Image ' + image)
        imp_orig = Opener().openImage(mainpath + image)
        imp_GB = blurImage(imp_orig)
        imp_orig.close()
        imp_GB.hide()
        #get the pixel values
        pix = getPixelValues(imp_GB, pix)
        imp_GB.close()

    #get the percentile values to threshold
    IJ.log('Quantifying thresholds...')
    percs = []
    for q in quantArray:
        percs.append(percentile(pix, q))
    return percs
示例#13
0
def batch_profile_from_threshold(batch_parameters):
	'''
	Thresholds the desired channel using the threshold method specified and saves the
	roi profile in the csv_output.
	Rois will be set to the width in pixels specified by stroke_width.
	Provide a batch parameters dict to operate on images.

	WIP:
	PUT A BETTER ALGO IN PLACE TO DETERMINE THE CORRECT ROI TO USE.
	'''
	from ij.io import Opener
	from IBPlib.ij.Utils.Files import buildList

	opener = Opener()
	rois_folder, csvs_folder = setup_output_folders(batch_parameters.get("output_folder"))
	IJ.log("Plotting profiles...")

	for i, img in enumerate(batch_parameters.get("analysed_images")):
		progress = "{0}/{1}".format(i+1, len(batch_parameters.get("analysed_images")))
		IJ.log("\n# Progress: {0}\n".format(progress))

		imp = imageloader(img)
		#title = os.path.basename(os.path.splitext(img)[0])
		title = os.path.basename(img)
		IJ.log("\nMeasuring -> {0}".format(title))
		rois_path_list = buildList(rois_folder, extension=".roi")
		rois = [opener.openRoi(roi) for roi in rois_path_list if roi.find(title) > 0]
		if not rois:
			IJ.log("## No rois found for {0}".format(title))

		if not profile_from_threshold(imp, batch_parameters.get("analysis_ch"),
			rois, batch_parameters.get("stroke_width"),
			batch_parameters.get("th_method"), csvs_folder):
			IJ.log("Batch run canceled.")
			return

	IJ.log("Done ...")
	IJ.log("Results stored in '{0}'".format(csvs_folder))
示例#14
0
def main():
    indir = IJ.getDirectory("input directory")
    outdir = IJ.getDirectory("output directory")
    files = sorted(os.listdir(indir))
    IJ.log("files: {}".format(files))

    montages = []
    for imfile in files:

    	IJ.log("File: {}/{}".format(files.index(imfile)+1, len(files)))
        
        if imfile.endswith(".tif"):
            imp = Opener().openImage(indir, imfile)
            montage = makemontage(imp, hsize=6, vsize=6, increment=2)
            _saveimage(montage, outdir)
示例#15
0
def main():
    indir = IJ.getDirectory("input directory")
    outdir = IJ.getDirectory("output directory")
    files = sorted(os.listdir(indir))
    # IJ.log("files: {}".format(files))

    # montages = []
    for imfile in files:

        IJ.log("File: {}/{}".format(files.index(imfile) + 1, len(files)))

        if imfile.endswith(".tif"):
            imp = Opener().openImage(indir, imfile)
            channels = ChannelSplitter().split(imp)
            name = outdir + imfile + "_t001_c001.tif"
            IJ.run(channels[0], "Image Sequence... ",
                   "format=TIFF save={}".format(name))
示例#16
0
def main():
    # Get the wanted input and output directories.
    indir = IJ.getDirectory("input directory")
    outdir = IJ.getDirectory("output directory")

    # Collect all files in the import directory and sort on file name.
    files = sorted(os.listdir(indir))

    # Loop through all input files.
    montages = []
    for imfile in files:

        # Some optional feedback if you're impatient.
        IJ.log("File: {}/{}".format(files.index(imfile) + 1, len(files)))

        # Make montage of every .tiff file and save as .tiff in the output directory.
        if imfile.endswith(".tif"):
            imp = Opener().openImage(indir, imfile)
            montage = makemontage(imp, hsize=6, vsize=6, increment=2)
            saveimage(montage, outdir)
def iter_rois_fwhm(roi_path, img_path):
    roi = readRois(roi_path)
    img = Opener.openUsingBioFormats(img_path)
    title = str(img.getShortTitle())
    all_out = []
    for i in roi.getIndexes():
        roi.select(img, i)
        x, y = getXY(img)
        fwhm, r2, params = fit_curve(x, y)
        all_out.append({
            "fwhm": fwhm,
            "r2": r2,
            "roi_id": i,
            "ch_n": 2,
            "img_name": title,
            "ch_name": "NaV1.6",
        })
    roi.close()
    img.close()
    return all_out
def convert32to16(fullFilePath): #overwrite the file!!!
	if not os.path.isfile(fullFilePath):
		bPrintLog('\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n',0)
		return 0
	elif not fullFilePath.endswith('tif'):
		msg = fullFilePath +" is not a deconvoluted tif file"
		bPrintLog(msg,2)
	else:
		bPrintLog(time.strftime("%H:%M:%S") + ' starting runOneFile()for overwrite: ' + fullFilePath, 1)
	
		#open and overwrite the deconvoluted file as 16 bit
		imp = Opener().openImage(fullFilePath)	#deconvoluted file
		if imp.getBitDepth() == 32:
			imp.show()
			msgStr = "Converting 32 to 16-bit..."
			bPrintLog(msgStr,3)
			IJ.run("16-bit")
			
			msgStr = "Overwriting 32-bit with 16-bit File in" + fullFilePath
			bPrintLog(msgStr,3)
			IJ.run(imp,"Save","") #save as replace without asking
			
		imp.close()
示例#19
0
def tethered_cell(image_path, frame_number=100, frame_rate=100.0, CCW=1):
    """
    parameter setting; frame rate (frame/sec)

    CCW = 1 : the motor rotation direction and the cell rotation direction on the image are same
    CCW = -1: the motor rotation direction and the cell rotation direction on the image are different
    """
    opener = Opener()
    imp = opener.openImage(image_path)
    image_slice_number = imp.getNSlices()
    rm = RoiManager().getInstance()

    if image_slice_number < frame_number: # too short movie
        IJ.log('Number of frame of the movie is fewer than the number of frame that you selected')
        return False
    # create result directory
    result_path = image_path + '_tethered_cell_result'
    if os.path.lexists(result_path) is False:
        os.mkdir(result_path)

    #z projection; standard deviation, tethered cell shorws circle
    IJ.run(imp, 'Subtract Background...', 'rolling=5 light stack')
    IJ.run(imp, 'Median...', 'radius=2 stack')
    IJ.run(imp, 'Z Project...', 'stop=500 projection=[Standard Deviation]')
    zimp = IJ.getImage()
    IJ.saveAs(zimp, 'bmp', os.path.join(result_path,'STD_DEV.bmp'))
    # pick up tethered cell
    IJ.setAutoThreshold(zimp, 'MaxEntropy dark')
    IJ.run(zimp, 'Convert to Mask', '')
    IJ.run('Set Measurements...', "area centroid bounding shape feret's limit redirect=None decimal=3")
    IJ.run(zimp, 'Analyze Particles...', 'size=30-Infinity circularity=0.88-1.00 show=Nothing display exclude clear include')
    zrt = ResultsTable.getResultsTable()
    IJ.saveAs('Results', os.path.join(result_path,'RoiInfo.csv'))

    #tcX and tcY are xy coordinates of tethered cell, tcdia is outer diameter of rotating tethered cell
    #add ROI into stack image
    for i in range(zrt.getCounter()):
        tcX = zrt.getValue('X', i)
        tcY = zrt.getValue('Y', i)
        tcdia = zrt.getValue('Feret', i)
        rm.add(imp, OvalRoi(tcX - tcdia/2.0, tcY - tcdia/2.0, tcdia + 1, tcdia + 1), i)

    #calculate rotation speed by ellipse fitting
    IJ.setAutoThreshold(imp, 'Li')
    for roi_number in range(rm.getCount()):
        t = []
        XM = []
        YM = []
        theta = []
        rotation_speed = []
        area = []
        imp.setRoi(rm.getRoi(roi_number))
        cropped_imp = Duplicator().run(imp)
        IJ.run('Set Measurements...', 'area mean center fit limit redirect=None decimal=3')
        rm.select(roi_number)
        rt = rm.multiMeasure(imp)

        # check cell is present while analysis. Don't a cell gose anywhare?
        for i in range(frame_number):
            area.append(rt.getValue('Area1', i))
        if 0 in area:
            continue

        for i in range(frame_number):
            t.append((1/frame_rate)*i)
            XM.append(rt.getValue('XM1', i))
            YM.append(rt.getValue('YM1', i))
            theta.append(rt.getValue('Angle1', i)/180.0*math.pi)  # convert to radian
            if i == 0:
                rotation_speed.append(0)
            else:
                # phase treatment, theta should be -pi ~ pi
                temp_rotation_speed = [theta[i] - theta[i-1],
                          theta[i] - theta[i-1] + math.pi,
                          theta[i] - theta[i-1] - math.pi,
                          theta[i] - theta[i-1] + 2*math.pi,
                          theta[i] - theta[i-1] - 2*math.pi]
                temp_rotation_speed = sorted(temp_rotation_speed, key = lambda x :abs(x) )[0]
                rotation_speed.append(CCW*temp_rotation_speed/(2.0*math.pi)*frame_rate)

        # write csv
        # earch columns indicate 1:index, 2:time(sec), 3:X-coordinate of center of mass(pixel), 4:Y-coordinate of center of mass (pixel), 5:Angle(Radian), 6:Rotation Speed(Hz)
        with open(os.path.join(result_path,'Roi' + str(roi_number) + '.csv'), 'w') as f:
            writer = csv.writer(f)
            writer.writerow(['Index', 'time(s)', 'X', 'Y', 'Angle(rad)', 'Rotation Speed(Hz)'])
            for i in range(len(t)):
                writer.writerow([i, t[i], XM[i], YM[i], theta[i], rotation_speed[i]])
        # plot x-y, t-x, t-y, t-rotation speed, save plot as bmp
        plotRotation(roi_number, result_path, t, XM, YM, rotation_speed)
        IJ.saveAs(cropped_imp, 'tiff', os.path.join(result_path,'Roi' + str(roi_number) + '.tiff'))
        rt.reset()

    # get analysis date and time
    dt = datetime.datetime.today()
    dtstr = dt.strftime('%Y-%m-%d %H:%M:%S')

    # wtite analysis setting
    with open(os.path.join(result_path,'analysis_setting.csv'), 'w') as f:
        writer = csv.writer(f)
        writer.writerow(['Analysis Date','frame number','frame rate','CCW direction', 'Method','Auto threshold', 'Subtruct Background', 'Median filter'])
        writer.writerow([dtstr, frame_number, frame_rate, CCW, 'Ellipse', 'Li', '5.0', '2'])

    # save roi
    if rm.getCount() != 0:
        rm.runCommand('Save', os.path.join(result_path, 'Roi.zip'))

    zimp.close()
    imp.close()
    rm.close()
    zrt.reset()
示例#20
0
def runOneFile(fullFilePath):
	global gFileType
	global fileIndex
	
	if not os.path.isfile(fullFilePath):
		bPrintLog('\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n',0)
		return 0

	bPrintLog(time.strftime("%H:%M:%S") + ' starting runOneFile(): ' + fullFilePath, 1)
	bPrintLog('inputfile is:' + fullFilePath, 1)
	
	enclosingPath = os.path.dirname(fullFilePath)
	head, tail = os.path.split(enclosingPath) #tail is name of enclosing folder
	enclosingPath += '/'
	
	# make output folders
	destFolder = enclosingPath + tail + '_short/'
	if not os.path.isdir(destFolder):
		os.makedirs(destFolder)

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

	# get parameters of image
	(width, height, nChannels, nSlices, nFrames) = imp.getDimensions()
	bitDepth = imp.getBitDepth()
	infoStr = imp.getProperty("Info") #get all .tif tags
	#print 'original infoStr:', infoStr
	if not infoStr:
		infoStr = ''
	infoStr += 'ShortenNames_Version=' + str(gShortenVersion) + '\n'
	infoStr += 'ShortenNames_Time=' + time.strftime("%Y%m%d") + '_' + time.strftime("%H%M%S") + '\n'
		
	msgStr = 'w:' + str(width) + ' h:' + str(height) + ' slices:' + str(nSlices) \
				+ ' channels:' + str(nChannels) + ' frames:' + str(nFrames) + ' bitDepth:' + str(bitDepth)
	bPrintLog(msgStr, 1)
	
	path, filename = os.path.split(fullFilePath)
	shortName, fileExtension = os.path.splitext(filename)

	#output file name
	outFile = destFolder + tail + '_' + str(fileIndex) + '.tif'
	fileIndex += 1
	bPrintLog('output file is:' + outFile, 1)
	
	# put original name in header
	infoStr += 'ShortenNames_OriginalFile=' + fullFilePath + '\n'
	
	# put scanimage header back in
	imp.setProperty("Info", infoStr);

	#save
	bSaveStack(imp, outFile)

	#
	# close original window
	imp.changes = 0
	imp.close()
def runOneFile(fullFilePath):
	global gFileType
	global gNumChannels
	global gAlignBatchVersion
	
	if not os.path.isfile(fullFilePath):
		bPrintLog('\nERROR: runOneFile() did not find file: ' + fullFilePath + '\n',0)
		return 0

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

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

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

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

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

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

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

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

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

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

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

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

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

	bPrintLog(time.strftime("%H:%M:%S") + ' finished runOneFile(): ' + fullFilePath, 1)
示例#22
0
				"analyzeCmStack": analyzeCmStack,
				"rowNo": rowNo,
				"colNo": colNo,
				"nucMinSize": nucMinSize,
				"cmMinSize": cmMinSize,
				"allFileNames": allFileNames}
with open("savedSettings.json", "w+") as f:
  json.dump(jsonStoreDict, f)
reList = []
for fileName in allFileNames:
  match = re.match(formatString, fileName)
  if match is None: continue
  matchDict = match.groupdict()
  matchDict['fileName'] = match.string
  reList.append(matchDict)
opener = Opener()
bs = BackgroundSubtracter()
for outerPairs, group in getCombos(reList, groupBy).iteritems():
  print(group)
  nucIp, cmIp = openStitched(group, rowNo, colNo) if stitched else openUnstitched(group)
  if nucIp is None or cmIp is None: continue
  nucStack, cmStack = nucIp.getStack(), cmIp.getStack()
  nucIpMedian = calcMedian(nucIp)
  IJ.run(nucIp, "Subtract...", "value=" + str(nucIpMedian) + " stack")
  nucIpForMeasure = nucIp.duplicate()
  nucMaskIp = generateNucleusMask(nucIp, nucMethod, analyzeNucStack, nucMinSize)
  cmIp, cmMaskIp = generateCardiomyocyteMask(cmIp, cmMethod, analyzeCmStack, cmMinSize, brightfield)
  nucMaskIp.show()
  nucIpForMeasure.show()
  rm = RoiManager.getRoiManager()
  rm.runCommand("Associate", "true")
示例#23
0
def scaleandfilter(infile,outfile,scalex,scaley):
	
	print ("infile is: "+infile)
	
	imp = Opener().openImage(infile)
	print imp
	print "scalex = %f; scaley = %f" % (scalex,scaley)
	# Rescale
	ip = imp.getProcessor()
	ip.setInterpolate(True)
	sp = StackProcessor(imp.getStack(),ip);
	sp2=sp.resize(int(round(ip.width * scalex)), int(round(ip.height *scaley)));
	imp.setStack(imp.getTitle(),sp2);
	
	cal = imp.getCalibration()
	cal.pixelWidth /= scalex
	cal.pixelHeight /= scaley

	IJ.run(imp, "8-bit","")
	
	intif=infile+".tif"
	outtif=infile+"-filtered.tif"
	print("saving input file as "+intif)
	f=FileSaver(imp)
	f.saveAsTiffStack(intif)
	imp.close()

	# anisotropic filtering
	anisopts="-scanrange:10 -tau:2 -nsteps:2 -lambda:0.1 -ipflag:0 -anicoeff1:1 -anicoeff2:0 -anicoeff3:0"
	anisopts=anisopts+" -dx:%f -dy:%f -dz:%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth)
	
	if sys.version_info > (2, 4):
		#for testing
		# subprocess.check_call(["cp",intif,outtif])
		subprocess.check_call(["anisofilter"]+anisopts.split(' ')+[intif,outtif])
	else:
		os.system(" ".join(["anisofilter"]+anisopts.split(' ')+[intif,outtif]))

	# Hessian (tubeness)
	print("Opening output tif: "+outtif)
	imp = Opener().openImage(outtif)
	imp.setCalibration(cal)
	print("Running tubeness on tif: "+outtif)
	IJ.run(imp,"Tubeness", "sigma=1")
	IJ.run(imp, "8-bit","")

	# Save to PIC
	print("Saving as PIC: "+outfile)
	# IJ.saveAs("tiff","outtif")
	IJ.run(imp,"Biorad ...", "biorad="+outfile)
示例#24
0
def runOneFile(fullFilePath):

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

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

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

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

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

	# show
	imp.show()

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

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

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

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

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

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

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

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

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

	bPrintLog(time.strftime("%H:%M:%S") + ' finished runOneFile(): ' + fullFilePath, 1)
示例#25
0
		rois_path_list = buildList(rois_folder, extension=".roi")
		rois = [opener.openRoi(roi) for roi in rois_path_list if roi.find(title) > 0]
		if not rois:
			IJ.log("## No rois found for {0}".format(title))

		if not profile_from_threshold(imp, batch_parameters.get("analysis_ch"),
			rois, batch_parameters.get("stroke_width"),
			batch_parameters.get("th_method"), csvs_folder):
			IJ.log("Batch run canceled.")
			return

	IJ.log("Done ...")
	IJ.log("Results stored in '{0}'".format(csvs_folder))


if __name__ in ("__builtin__", "__main__"):
	from ij.io import Opener

	opener = Opener()
	roi_path = r"R:\Igor BP\Projects\Let-805\Raw Data\Microscopies\Yokogawa Spinning Disk\let-805(syb381)\L4\63x OIL\let-805 localization data\Reanalysis\rois\C2-1.tif_0.roi"
	imp = imageloader(r"R:\\Igor BP\\Projects\\Let-805\\Raw Data\\Microscopies\\Yokogawa Spinning Disk\\let-805(syb381)\\L4\\63x OIL\\zprojections\\Stiched\\1.tif")
	roi = opener.openRoi(roi_path)
	ch = 1
	rois = [roi]
	output = r"C:\Users\uqibonac\Desktop\test"
	th_method = "Li"
	analysis_ch = 2
	stroke_width = 5
	print("Running ...")
	print(profile_from_threshold(imp, analysis_ch, rois, stroke_width, th_method, output))
	print("Run finished...")
示例#26
0
                  straight_length, distance_from_stem_apical, angle,
                  convexfull_area)
col_name = [
    "file_path", "exec_times", "roi_id", "types", "curve_length",
    "straight_length", "distance_from_stem_apical", "angle", "convexfull_area"
]

csv_path = os.path.join(get_file_info()[0],
                        get_file_info()[1] + "_analyze.csv")

# ファイルに内容がある場合は何もせず, 内容がないときだけカラムを書き込む
with open(csv_path, "a") as f1:
    with open(csv_path, "r") as f2:
        s = f2.read()
    if s == "":
        with open(csv_path, "w") as f3:
            writer = csv.writer(f3)
            writer.writerow(col_name)

# 上書きモードで値を書き込む
with open(csv_path, "a") as f:
    writer = csv.writer(f)
    writer.writerows(for_csv_row)

# saveしたあとにoverlayに書き込んで線を青色に変える。
save_roi_set(imp=IJ.getImage())

# table上に表示する
op = Opener()
op.openTable(csv_path)
image_basenames = list(set(image_basenames))
print(image_basenames)
ImageJ()
for i in image_basenames:
    print(i)
    cur_images = []
    for j in image_list:
        m = re.search(i, j)
        if m:
            cur_images.append(j)

#    imp_c1 = IJ.openImage(cur_images[0])
#    imp_c2 = IJ.openImage(cur_images[1])
    image_path = image_directory + cur_images[2]
    imp_c3 = Opener.openUsingBioFormats(image_path)
    imp_c3.show()
    save_name = image_directory + '/Stacks/' + i + 'merged.tif'
    IJ.saveAsTiff(imp_c3, save_name)
    #    merge_string = "c1=" + cur_images[0] + " c2=" + cur_images[1] + " create";
    #    IJ.run("Merge Channels...", merge_string)
    IJ.run('Z Project...', 'projection=[Max Intensity] all')
    IJ.run('Enhance Contrast...', 'saturated=0.05')
    max_im = IJ.getImage()
    save_name = image_directory + '/MaxZProj/' + i + 'MaxZProj.tif'
    IJ.saveAsTiff(max_im, save_name)
    IJ.run('Close All')
    gc.collect()

IJ.run('Close All')
	def __init__(self, filepath):
		"""
		Load an image or stack from filepath.

		Args:
			filepath (str): Full path to an image file. Can be .tif, .lsm, .czi, etc
		"""
		
		if not os.path.isfile(filepath):
			bPrintLog('ERROR: bImp() did not find file: ' + filepath,0)
			return 0

		self.filepath = filepath
		folderpath, filename = os.path.split(filepath)
		self.filename = filename
		self.enclosingPath = folderpath
		self.enclosingfolder = os.path.split(folderpath)[1]

		self.dateStr = ''
		self.timeStr = ''
		
		self.imp = None
		
		tmpBaseName, extension = os.path.splitext(filename)
		isZeiss = extension in ['.czi', '.lsm']
		self.islsm = extension == '.lsm'
		self.isczi = extension == '.czi'
		istif = extension == '.tif'
				
		if istif:
			# scanimage3 comes in with dimensions: [512, 512, 1, 52, 1]) = [width, height, numChannels, numSlices, numFrames]
			self.imp = Opener().openImage(filepath)
			self.imp.show()
			
		elif isZeiss:
			#open lsm using LOCI Bio-Formats
			options = ImporterOptions()
			#options.setColorMode(ImporterOptions.COLOR_MODE_GRAYSCALE)
			options.setId(filepath)
			imps = BF.openImagePlus(options)
			for imp in imps:
				self.imp = imp #WindowManager.getImage(self.windowname)
				imp.show()

		if not self.imp:
			bPrintLog('ERROR: bImp() was not able to open file: '+ filepath,0)
    				
		self.windowname = filename
		#self.imp = WindowManager.getImage(self.windowname)

		# numChannels is not correct for scanimage, corrected in readTiffHeader()
		(width, height, numChannels, numSlices, numFrames) = self.imp.getDimensions()

		self.width = width # pixelsPerLine
		self.height = height # linesPerFrame
		self.numChannels = numChannels
		self.numSlices = numSlices
		self.numFrames = numFrames

		self.infoStr = self.imp.getProperty("Info") #get all tags
				
		self.voxelx = 1
		self.voxely = 1
		self.voxelz = 1
		#self.numChannels = 1
		#self.bitsPerPixel = 8
		self.zoom = 1

		self.motorx = None
		self.motory = None
		self.motorz = None

		self.scanImageVersion = ''
		self.msPerLine = None
		self.dwellTime = None
		
		# read file headers (date, time, voxel size)
		if isZeiss:
			self.readZeissHeader(self.infoStr)
		elif istif:
			self.readTiffHeader(self.infoStr)

		self.updateInfoStr()
		
		self.channelWindows = []
		self.channelImp = []

		if self.numChannels == 1:
			self.channelWindows.append(self.windowname)
			self.channelImp.append(self.imp)
		else:
			self.deinterleave()
# create list of match objects of .tiff files in directory
regEx = re.compile('(?!ppcd_)(?P<prefix>.+).tiff?$', re.IGNORECASE)
moFileList = []    # match object File list
for fileName in listdir(path):
   if regEx.match(fileName):   # if matches RE, add to list
      moFileList.append(regEx.match(fileName))

if moFileList == []:
   IJ.showMessage("Input Exception", "No unprocessed images found in the directory you selected.")
   raise IOError("No unpocessed TIFFs found in this folder.")

for image in moFileList:
   print "Processing cell " + image.group() + " (" + str(moFileList.index(image)+1) + "/" + str(len(moFileList)) + ")"
   IJ.log("Processing cell " + image.group() + " (" + str(moFileList.index(image)+1) + "/" + str(len(moFileList)) + ")")
   imp = Opener().openImage(path + image.group()) # open Image
   #if imp.getBitDepth() != 8:  # converting to 8 bit if 
   #   ImageConverter(imp).convertToGray8()
   roi = imp.roi
   imps = CS.split(imp)
   ppc = PPC()
   for aimp in imps:
      ppc.setImp(aimp)
      ppc.run()
      if roi != None:
         aimp.setRoi(roi)
         for n in range(1, aimp.getImageStackSize()+1):
            aimp.getImageStack().getProcessor(n).fillOutside(roi)
         aimp.killRoi()
   final = StackMerge.mergeChannels(imps, False)
   final.copyScale(imp) # copyscale from .copyscale
moFileList = []                                               # match object File list
for fileName in listdir(inputDir):
    if regEx.match(fileName):                                  # if matches RE, add to list
        moFileList.append(regEx.match(fileName))
print "Will process files ", moFileList

if moFileList == []:
    IJ.showMessage("Input Exception", "Directory does not contain any preprocessed images.")
    raise IOError("Input Exception: Directory does not contain any preprocessed images.")

if not pth.exists(saveFolder):   # check if directory for analysis-files is present 
    makedirs(saveFolder)

for image in moFileList: # get rid of 0!
    print "starting with cell " + image.group() + " " + "("+ str(moFileList.index(image)) + "/" + str(len(moFileList)) + ")"
    imp = Opener().openImage(inputDir + image.group()) # open Image
    # read calibration for later calculation of distances in um.
    calibration = imp.getCalibration()
    pxWidth = calibration.pixelWidth
    print "px depth", calibration.pixelDepth
    timeInterval = round(calibration.frameInterval)

    #start measurement
    splitCh = CS.split(imp)                        # split channels
    #try:
    ATA().segAndMeasure(splitCh[0], splitCh[1])    # perform segmentation and measurement 
    #else: go to next element in moFileList
    # move image to "segProblem" folder
    # continue

    WindowManager.getImage("binProjMerged").close()
示例#31
0
	for filename in filenames:
		match = re.search(pattern, filename)
		if match is not None:
			#print filename, match.group(3)
			GRlist.append(match.group(3))

print srcDir
print 'files: ', len(GRlist)

GRlist = sorted(GRlist)
timeseries = []

for timepoint in GRlist:
	thisfile = basename + '_R' + repetition + '_GR' + timepoint + '_B' + block + '_L' + location + '.lsm'
	print thisfile
	imp = Opener.openUsingBioFormats(os.path.join(srcDir, thisfile))
	imp.setOpenAsHyperStack(False)
	timeseries.append(imp)

newname = basename + '_R' + repetition + '_B' + block + '_L' + location + '.lsm'
calib = timeseries[0].getCalibration()
dimA = timeseries[0].getDimensions()
jaimp = array(timeseries, ImagePlus)
ccc = Concatenator()
#allimp = ccc.concatenateHyperstacks(jaimp, newname, False)
allimp = ccc.concatenate(jaimp, False)
allimp.setDimensions(dimA[2], dimA[3], len(GRlist))
allimp.setCalibration(calib)
allimp.setOpenAsHyperStack(True)
allimp.show()
示例#32
0
def runOneFile(fullFilePath):
    global gFileType
    global fileIndex

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

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

    enclosingPath = os.path.dirname(fullFilePath)
    head, tail = os.path.split(
        enclosingPath)  #tail is name of enclosing folder
    enclosingPath += '/'

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

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

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

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

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

    #output file name
    outFile = destFolder + tail + '_' + str(fileIndex) + '.tif'
    fileIndex += 1
    bPrintLog('output file is:' + outFile, 1)

    # put original name in header
    infoStr += 'ShortenNames_OriginalFile=' + fullFilePath + '\n'

    # put scanimage header back in
    imp.setProperty("Info", infoStr)

    #save
    bSaveStack(imp, outFile)

    #
    # close original window
    imp.changes = 0
    imp.close()
            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)
            IJ.log("Found pixel bounds " + str(min_pixval) + " and " +
                   str(max_pixval) + " for channel " + str(channel))
            counter = 1
            for chfile in chf_fpaths:
                # open file
                ch_img = Opener().openImage(chfile)
                ch_tit = ch_img.getTitle()
                # adjust contrast
                ch_img.getProcessor().setMinAndMax(min_pixval, max_pixval)
                # convert to 8-bit (which also applies the contrast)
                ImageConverter(ch_img).convertToGray8()
                # save
                IJ.saveAsTiff(ch_img, path.join(Out_dir, ch_tit))
                # close and flush
                ch_img.close()
                ch_img.flush()
                print("Image " + str(counter) + " of " + str(len(chf_fpaths)) +
                      " processed")
                counter += 1

        IJ.log('Mouse ' + MouseID + ' processed')
示例#34
0
def runOneFile(fullFilePath):

    global gNumChannels
    global gAlignBatchVersion

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        transformationFile = destAlignmentFolder + shortName + '.txt'

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    bPrintLog(
        time.strftime("%H:%M:%S") + ' finished runOneFile(): ' + fullFilePath,
        1)
示例#35
0
def main():
    # Prepare directory tree for output.
    indir = IJ.getDirectory("input directory")
    outdir = IJ.getDirectory(".csv output directory")
    c1dir = os.path.join(outdir, "Channel1")
    c2dir = os.path.join(outdir, "Channel2")
    c3dir = os.path.join(outdir, "Channel3")
    c4dir = os.path.join(outdir, "Channel4")
    channelsdir = os.path.join(outdir, "Channels")
    if not os.path.isdir(c1dir):
        os.mkdir(c1dir)
    if not os.path.isdir(c2dir):
        os.mkdir(c2dir)
    if not os.path.isdir(c3dir):
        os.mkdir(c3dir)
    if not os.path.isdir(c4dir):
        os.mkdir(c4dir)
    if not os.path.isdir(channelsdir):
        os.mkdir(channelsdir)

    # Collect all file paths in the input directory
    files = readdirfiles(indir)

    # Initialize the results tables.
    c1Results = ResultsTable()
    c2Results = ResultsTable()
    c3Results = ResultsTable()
    c4Results = ResultsTable()

    for file in files:

        IJ.log("File: {}/{}".format(files.index(file) + 1, len(files)))

        if file.endswith('.tif'):

            # Open .tiff file as ImagePlus.
            imp = Opener().openImage(file)
            imp = ZProjector.run(imp, "max")
            # imp = stackprocessor(file,
            #                        nChannels=4,
            #                        nSlices=7,
            #                        nFrames=1)
            channels = ChannelSplitter.split(imp)
            name = imp.getTitle()

            # For every channel, save the inverted channel in grayscale as .jpg.
            for channel in channels:
                IJ.run(channel, "Grays", "")
                IJ.run(channel, "Invert", "")
                jpgname = channel.getShortTitle()
                jpgoutfile = os.path.join(channelsdir,
                                          "{}.jpg".format(jpgname))
                IJ.saveAs(channel.flatten(), "Jpeg", jpgoutfile)
                IJ.run(channel, "Invert", "")

            # OPTIONAL - Perform any other operations (e.g. crossexcitation compensation tasks) before object count.
            c2name = channels[2].getTitle()
            cal = channels[2].getCalibration()
            channels[2] = ImagePlus(
                c2name,
                ImageCalculator().run("divide create 32-bit", channels[2],
                                      channels[3]).getProcessor(
                                      )  # This removes AF647 bleed-through
            )
            channels[2].setCalibration(cal)

            # Settings for channel1 threshold.
            c1 = countobjects(channels[0],
                              c1Results,
                              threshMethod="Triangle",
                              subtractBackground=True,
                              watershed=True,
                              minSize=0.00,
                              maxSize=100,
                              minCirc=0.00,
                              maxCirc=1.00)

            # Settings for channel2 threshold.
            c2 = countobjects(channels[1],
                              c2Results,
                              threshMethod="RenyiEntropy",
                              subtractBackground=True,
                              watershed=False,
                              minSize=0.00,
                              maxSize=30.00,
                              minCirc=0.00,
                              maxCirc=1.00)

            # Settings for channel3 threshold.
            c3 = countobjects(channels[2],
                              c3Results,
                              threshMethod="RenyiEntropy",
                              subtractBackground=True,
                              watershed=False,
                              minSize=0.00,
                              maxSize=30.00,
                              minCirc=0.00,
                              maxCirc=1.00)

            # Settings for channel4 threshold.
            c4 = countobjects(channels[3],
                              c4Results,
                              threshMethod="RenyiEntropy",
                              subtractBackground=True,
                              watershed=False,
                              minSize=0.20,
                              maxSize=100.00,
                              minCirc=0.00,
                              maxCirc=1.00)

            # Format filenames for thresholded .tiff files.
            outfileC1 = os.path.join(c1dir, "threshold_c1_{}".format(name))
            outfileC2 = os.path.join(c2dir, "threshold_c2_{}".format(name))
            outfileC3 = os.path.join(c3dir, "threshold_c3_{}".format(name))
            outfileC4 = os.path.join(c4dir, "threshold_c4_{}".format(name))

            # Save thresholded .tiff files.
            IJ.saveAs(c1.flatten(), "Tiff", outfileC1)
            IJ.saveAs(c2.flatten(), "Tiff", outfileC2)
            IJ.saveAs(c3.flatten(), "Tiff", outfileC3)
            IJ.saveAs(c4.flatten(), "Tiff", outfileC4)

    # Show results tables.


#    c1Results.show("channel1")
#    c2Results.show("channel2")
#    c3Results.show("channel3")
#    c4Results.show("channel4")

# Prepare results table filenames.
    c1out = os.path.join(outdir, "channel1.csv")
    c2out = os.path.join(outdir, "channel2.csv")
    c3out = os.path.join(outdir, "channel3.csv")
    c4out = os.path.join(outdir, "channel4.csv")

    # Save results tables.
    ResultsTable.save(c1Results, c1out)
    ResultsTable.save(c2Results, c2out)
    ResultsTable.save(c3Results, c3out)
    ResultsTable.save(c4Results, c4out)
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"

    #import pdb; pdb.set_trace()
    print "Loading images..."
    filenames = enumerate_filenames(pattern)
    num_channels = len(filenames)
    num_images = len(filenames[0])
    image = Opener().openImage(filenames[0][0])
    width = image.width
    height = image.height
    image.close()

    # The internal initialization of the BaSiC code fails when we invoke it via
    # scripting, unless we explicitly set a the private 'noOfSlices' field.
    # Since it's private, we need to use Java reflection to access it.
    Basic_noOfSlices = Basic.getDeclaredField('noOfSlices')
    Basic_noOfSlices.setAccessible(True)
    basic = Basic()
    Basic_noOfSlices.setInt(basic, num_images)

    # Pre-allocate the output profile images, since we have all the dimensions.
    ff_image = IJ.createImage("Flat-field", width, height, num_channels, 32);
    df_image = IJ.createImage("Dark-field", width, height, num_channels, 32);

    print("\n\n")

    # BaSiC works on one channel at a time, so we only read the images from one
    # channel at a time to limit memory usage.
    for channel in range(num_channels):
        print "Processing channel %d/%d..." % (channel + 1, num_channels)
        print "==========================="

        stack = ImageStack(width, height, num_images)
        opener = Opener()
        for i, filename in enumerate(filenames[channel]):
            print "Loading image %d/%d" % (i + 1, num_images)
            image = opener.openImage(filename)
            stack.setProcessor(image.getProcessor(), i + 1)
        input_image = ImagePlus("input", stack)

        # BaSiC seems to require the input image is actually the ImageJ
        # "current" image, otherwise it prints an error and aborts.
        WindowManager.setTempCurrentImage(input_image)
        basic.exec(
            input_image, None, None,
            "Estimate shading profiles", "Estimate both flat-field and dark-field",
            lambda_estimate, lambda_flat, lambda_dark,
            "Ignore", "Compute shading only"
        )
        input_image.close()

        # Copy the pixels from the BaSiC-generated profile images to the
        # corresponding channel of our output images.
        ff_channel = WindowManager.getImage("Flat-field:%s" % input_image.title)
        ff_image.slice = channel + 1
        ff_image.getProcessor().insert(ff_channel.getProcessor(), 0, 0)
        ff_channel.close()
        df_channel = WindowManager.getImage("Dark-field:%s" % input_image.title)
        df_image.slice = channel + 1
        df_image.getProcessor().insert(df_channel.getProcessor(), 0, 0)
        df_channel.close()

        print("\n\n")

    template = '%s/%s-%%s.tif' % (output_dir, experiment_name)
    ff_filename = template % 'ffp'
    IJ.saveAsTiff(ff_image, ff_filename)
    ff_image.close()
    df_filename = template % 'dfp'
    IJ.saveAsTiff(df_image, df_filename)
    df_image.close()

    print "Done!"
示例#37
0
IJ.run("Collect Garbage");
#inputDir1 = IJ.getDirectory("Choose image directory! ")
inputDir1 = "/home/mt/Downloads/1/"
fileList1 = os.listdir(inputDir1); 
###tilestring=getString("Which Tilescan", "1")
RGB=os.path.join(inputDir1,'RGB.png')
	
FileList=sorted(os.listdir(inputDir1))
print(FileList)
stitchedFiles=[x for x in FileList if "stitched.TIF" in x]
stitchedNames=[x.split('_')[0] for x in stitchedFiles]

mergedFiles=[x for x in FileList if "merged.TIF" in x]

imp = Opener.openUsingBioFormats(os.path.join(inputDir1,mergedFiles[0]))
xsize=imp.getWidth()
ysize=imp.getHeight()
imp.close()

print(xsize,ysize)

for im in stitchedFiles:
    if not "hoechst" in im.lower():
        IJ.open(inputDir1+im)
        imp = IJ.getImage()
        imp.setTitle(im.split('_')[0])
IJ.run("Images to Stack", "name=Stack title=[] use")
imp = IJ.getImage()
#IJ.run("Multiply...", "value=2.2")
IJ.beep()
class bImp:
	def __init__(self, filepath):
		"""
		Load an image or stack from filepath.

		Args:
			filepath (str): Full path to an image file. Can be .tif, .lsm, .czi, etc
		"""
		
		if not os.path.isfile(filepath):
			bPrintLog('ERROR: bImp() did not find file: ' + filepath,0)
			return 0

		self.filepath = filepath
		folderpath, filename = os.path.split(filepath)
		self.filename = filename
		self.enclosingPath = folderpath
		self.enclosingfolder = os.path.split(folderpath)[1]

		self.dateStr = ''
		self.timeStr = ''
		
		self.imp = None
		
		tmpBaseName, extension = os.path.splitext(filename)
		isZeiss = extension in ['.czi', '.lsm']
		self.islsm = extension == '.lsm'
		self.isczi = extension == '.czi'
		istif = extension == '.tif'
				
		if istif:
			# scanimage3 comes in with dimensions: [512, 512, 1, 52, 1]) = [width, height, numChannels, numSlices, numFrames]
			self.imp = Opener().openImage(filepath)
			self.imp.show()
			
		elif isZeiss:
			#open lsm using LOCI Bio-Formats
			options = ImporterOptions()
			#options.setColorMode(ImporterOptions.COLOR_MODE_GRAYSCALE)
			options.setId(filepath)
			imps = BF.openImagePlus(options)
			for imp in imps:
				self.imp = imp #WindowManager.getImage(self.windowname)
				imp.show()

		if not self.imp:
			bPrintLog('ERROR: bImp() was not able to open file: '+ filepath,0)
    				
		self.windowname = filename
		#self.imp = WindowManager.getImage(self.windowname)

		# numChannels is not correct for scanimage, corrected in readTiffHeader()
		(width, height, numChannels, numSlices, numFrames) = self.imp.getDimensions()

		self.width = width # pixelsPerLine
		self.height = height # linesPerFrame
		self.numChannels = numChannels
		self.numSlices = numSlices
		self.numFrames = numFrames

		self.infoStr = self.imp.getProperty("Info") #get all tags
				
		self.voxelx = 1
		self.voxely = 1
		self.voxelz = 1
		#self.numChannels = 1
		#self.bitsPerPixel = 8
		self.zoom = 1

		self.motorx = None
		self.motory = None
		self.motorz = None

		self.scanImageVersion = ''
		self.msPerLine = None
		self.dwellTime = None
		
		# read file headers (date, time, voxel size)
		if isZeiss:
			self.readZeissHeader(self.infoStr)
		elif istif:
			self.readTiffHeader(self.infoStr)

		self.updateInfoStr()
		
		self.channelWindows = []
		self.channelImp = []

		if self.numChannels == 1:
			self.channelWindows.append(self.windowname)
			self.channelImp.append(self.imp)
		else:
			self.deinterleave()
			
	def updateInfoStr(self):
		# Fill in infoStr with Map Manager tags		

		self.infoStr += 'Folder2MapManager=' + versionStr + '\n'

		self.infoStr += 'b_date=' + self.dateStr + '\n'
		self.infoStr += 'b_time=' + self.timeStr + '\n'
		
		# yevgeniya 20180314
		#if (self.numChannels > 3):
		#	self.numChannels = 3
		self.infoStr += 'b_numChannels=' + str(self.numChannels) + '\n'
		self.infoStr += 'b_pixelsPerline=' + str(self.width) + '\n'
		self.infoStr += 'b_linesPerFrame=' + str(self.height) + '\n'
		self.infoStr += 'b_numSlices=' + str(self.numSlices) + '\n'
		
		self.infoStr += 'b_voxelX=' + str(self.voxelx) + '\n'
		self.infoStr += 'b_voxelY=' + str(self.voxely) + '\n'
		self.infoStr += 'b_voxelZ=' + str(self.voxelz) + '\n'

		#self.infoStr += 'b_bitsPerPixel=' + str(self.bitsPerPixel) + '\n'

		self.infoStr += 'b_zoom=' + str(self.zoom) + '\n'
		
		self.infoStr += 'b_motorx=' + str(self.motorx) + '\n'
		self.infoStr += 'b_motory=' + str(self.motory) + '\n'
		self.infoStr += 'b_motorz=' + str(self.motorz) + '\n'

		self.infoStr += 'b_msPerLine=' + str(self.msPerLine) + '\n'

		self.infoStr += 'b_scanImageVersion=' + self.scanImageVersion + '\n'

	
	def readTiffHeader(self, infoStr):
		"""
		Read ScanImage 3/4 .tif headers
		"""
		logLevel = 3

		# splitting on '\r' for scanimage 3.x works
		# splitting on '\n' for scanimage 4.x works
		
		#we need to search whole infoStr to figure out scanimage 3 or 4.
		# we can't split info string because si3 uses \r and si4 uses \n
		
		infoStrDelim = '\n'
		if infoStr.find('scanimage.SI4') != -1:
			infoStrDelim = '\n'
			bPrintLog('Assuming SI4 infoStr to be delimited with backslash n', logLevel)
		elif infoStr.find('state.software.version') != -1:
			infoStrDelim = '\r'
			bPrintLog('Assuming SI3 infoStr to be delimited with backslash r', logLevel)
		else:
			bPrintLog('Splitting infoStr using backslah n', logLevel)

		# if we don't find zoom then voxel is an error (see end of function)
		foundZoom = False
		
		#for line in infoStr.split('\n'):
		for line in infoStr.split(infoStrDelim):
			#
			# ScanImage 4.x
			#
			
			# scanimage.SI4.versionMajor = 4.2
			if line.find('scanimage.SI4.versionMajor') != -1:
				bPrintLog(line, logLevel)
				rhs = line.split('=')[1]
				self.scanImageVersion = rhs
			
			# scanimage.SI4.motorPosition = [-33936.5 -106316 -55308.5]
			if line.find('scanimage.SI4.motorPosition') != -1:
				bPrintLog(line, logLevel)
				rhs = line.split('=')[1]
				rhs = rhs.replace('[','')
				rhs = rhs.replace(']','')
				floats = [float(x) for x in rhs.split()]
				self.motorx = floats[0]
				self.motory = floats[1]
				self.motorz = floats[2]

			# scanimage.SI4.channelsSave = [1;2]
			if line.find('scanimage.SI4.channelsSave') != -1:
				bPrintLog(line, logLevel)
				rhs = line.split('=')[1]
				rhs = rhs.replace('[','')
				rhs = rhs.replace(']','')
				channels = [int(x) for x in rhs.split(';')]
				bPrintLog('reading scanimage.SI4.channelsSave inferred channels:' + str(channels), logLevel)
				self.numChannels = len(channels)

			# scanimage.SI4.scanZoomFactor = 5.9
			if line.find('scanimage.SI4.scanZoomFactor') != -1:
				bPrintLog(line, logLevel)
				rhs = line.split('=')[1]
				self.zoom = float(rhs)
				foundZoom = True
				#self.voxelx = magic_scan_image_scale / self.zoom
				#self.voxely = magic_scan_image_scale / self.zoom

			# scanimage.SI4.triggerClockTimeFirst = '18-05-2015 11:58:43.788'
			if line.find('scanimage.SI4.triggerClockTimeFirst') != -1:
				bPrintLog(line, logLevel)
				rhs = line.split('=')[1]
				rhs = rhs.replace("'","") # remove enclosing ' and '
				if rhs.startswith(' '): # if date string starts with space, remove it
					rhs = rhs[1:-1]
				datetime = rhs.split(' ')
				# 20170811, there is an extra f*****g space before datestr on the rhs
				# convert mm/dd/yyyy to yyyymmdd
				#print 'rhs:' + "'" + rhs + "'"
				#print 'datetime:', datetime
				datestr = bFixDate(datetime[0], logLevel)
				self.dateStr = datestr
				self.timeStr = datetime[1]
			
			#
			# ScanImage 3.x
			#
			
			# state.software.version = 3.8
			if line.find('state.software.version') != -1:
				bPrintLog(line, logLevel)
				rhs = line.split('=')[1]
				self.scanImageVersion = rhs
			
			# state.acq.numberOfChannelsAcquire = 2
			if line.find('state.acq.numberOfChannelsAcquire') != -1:
				#print '\rDEBUG 12345'
				bPrintLog(line, logLevel)
				#print '\rDEBUG 12345'
				rhs = line.split('=')[1]
				self.numChannels = int(rhs)

			# state.acq.zoomFactor = 2.5
			if line.find('state.acq.zoomFactor') != -1:
				bPrintLog(line, logLevel)
				rhs = line.split('=')[1]
				self.zoom = float(rhs)
				foundZoom = True
				# set (voxelx, voxely)
				#self.voxelx = magic_scan_image_scale / self.zoom
				#self.voxely = magic_scan_image_scale / self.zoom
				
			# state.acq.msPerLine = 2.32
			if line.find('state.acq.msPerLine') != -1:
				bPrintLog(line, logLevel)
				rhs = line.split('=')[1]
				self.msPerLine = float(rhs)
			
			# state.acq.pixelTime = 3.2e-06
			if line.find('state.acq.pixelTime') != -1:
				bPrintLog(line, logLevel)
				rhs = line.split('=')[1]
				self.dwellTime = float(rhs)

			# state.motor.absXPosition = -9894.4
			if line.find('state.motor.absXPosition') != -1:
				bPrintLog(line, logLevel)
				rhs = line.split('=')[1]
				self.motorx = float(rhs)

			# state.motor.absYPosition = -18423.4
			if line.find('state.motor.absYPosition') != -1:
				bPrintLog(line, logLevel)
				rhs = line.split('=')[1]
				self.motory = float(rhs)

			# state.motor.absZPosition = -23615.04
			if line.find('state.motor.absZPosition') != -1:
				bPrintLog(line, logLevel)
				rhs = line.split('=')[1]
				self.motorz = float(rhs)

			# state.acq.zStepSize = 2
			if line.find('state.acq.zStepSize') != -1:
				bPrintLog(line, logLevel)
				rhs = line.split('=')[1]
				self.voxelz = float(rhs)

			# state.internal.triggerTimeString = '10/2/2014 12:29:22.796'
			if line.find('state.internal.triggerTimeString') != -1:
				bPrintLog(line, logLevel)
				rhs = line.split('=')[1]
				rhs = rhs.replace("'","")
				if rhs.startswith(' '): # if date string starts with space, remove it
					rhs = rhs[1:-1]
				datetime = rhs.split(' ')
				# 20170811, there is an extra f*****g space before datestr on the rhs
				# convert mm/dd/yyyy to yyyymmdd
				#print 'rhs:' + "'" + rhs + "'"
				#print 'datetime:', datetime
				self.dateStr = bFixDate(datetime[0], logLevel)
				self.timeStr = bFixTime(datetime[1], logLevel)
				

			# state.acq.acqDelay = 0.000122
			# state.acq.bidirectionalScan = 0
			# state.acq.fillFraction = 0.706206896551724
			# state.acq.frameRate = 0.841864224137931
			# huganir lab keeps this off, image pixel intensities are 2^11 * samplesperpixel (e.g. binFactor?)
			# state.acq.binFactor = 16
			# state.internal.averageSamples = 1
			# the real image bit depth is usually inputBitDepth-1 (1 bit is not used?)
			# state.acq.inputBitDepth = 12

		if foundZoom:
			self.voxelx = magic_scan_image_scale / self.zoom * (1024 / self.width)
			self.voxely = magic_scan_image_scale / self.zoom * (1024 / self.height)
		else:
			bPrintLog('ERROR: Did not find zoom in SI header, voxel x/y will be wrong', logLevel)
			
	def readZeissHeader(self, infoStr):		
		# This is incredibly difficult to get working as (date, time, voxels) are in different obscure places in lsm and czi
		# Furthermore, just trying to read the raw ome xls is futile
		#
		# parsing ome xml as a string and searching it with regular expression(re) does not work
		# it is beyond the scope of my work to figure this out
		# the fact that it does not work and there is little documentaiton is a pretty big waste of time
		#
		# get and parse xml to find date/time
		#fi = self.imp.getOriginalFileInfo(); # returns a FileInfo object
		#omexml = fi.description #omexml is a string
		#omexml = omexml.encode('utf-8')
		#omexml = omexml.replaceAll("[^\\x20-\\x7e]", "") # see: https://stackoverflow.com/questions/2599919/java-parsing-xml-document-gives-content-not-allowed-in-prolog-error

		# (1) try and search the ome xml like a string, this gives errors
		#docsPattern = '<AcquisitionDate>.*</AcquisitionDate>'
		#searchresult = re.search(docsPattern, omexml)
		#print 'searchresult:', searchresult.group(0)
		
		# 2) treat the ome xml like any other xml (because it's xml, right?)
		# well this raises errors too
		#omexml has <AcquisitionDate>2016-08-17T15:21:50</AcquisitionDate>
		#import xml.etree.ElementTree
		#e = xml.etree.ElementTree.fromstring(omexml).getroot()		#print omexml
		#for atype in e.findall('AcquisitionDate'):
		#    print 'AcquisitionDate:', atype #.get('foobar')
		#
		#

		if self.islsm:
			# lsm have date hidden in omeMeta.getImageAcquisitionDate(0)
			# this is copied from code at: https://gist.github.com/ctrueden/6282856
			reader = ImageReader()
			omeMeta = MetadataTools.createOMEXMLMetadata() #omeMeta.getImageAcquisitionDate(0)
			reader.setMetadataStore(omeMeta)
			reader.setId(self.filepath)
			#seriesCount = reader.getSeriesCount()
			dateTimeStr = omeMeta.getImageAcquisitionDate(0) #2016-08-17T16:36:26
			reader.close()
			if dateTimeStr:
				self.dateStr, self.timeStr = dateTimeStr.toString().split('T')
				self.dateStr = bFixDate(self.dateStr)
				self.timeStr = bFixTime(self.timeStr)
				#bPrintLog('LSM date/time is: ' + self.dateStr + ' ' + self.timeStr, 3)
			else:
				bPrintLog('WARNING: did not get Zeiss date/time string')

			# lsm have voxels in infoStr
			for line in infoStr.split('\n'):
				#print line
				if line.find('VoxelSizeX') != -1:
					self.voxelx = float(line.split('=')[1])
				if line.find('VoxelSizeY') != -1:
					self.voxely = float(line.split('=')[1])
				if line.find('VoxelSizeZ') != -1:
					self.voxelz = float(line.split('=')[1])
				if line.find('SizeC') != -1:
					self.numChannels = int(line.split('=')[1])
				#if line.find('BitsPerPixel') and not line.startswith('Experiment') != -1: # 20170811, startswith is for czi
				#	self.bitsPerPixel = int(line.split('=')[1])
				if line.find('RecordingZoomX#1') != -1:
					self.zoom = int(line.split('=')[1])

		if self.isczi:
			# czi has date/time in infoStr (lsm does not)
			for line in infoStr.split('\n'):
				if line.find('CreationDate #1') != -1: # w.t.f. is #1 referring to?
					lhs, rhs = line.split('=')
					rhs = rhs.replace('  ', ' ')
					if rhs.startswith(' '):
						rhs = rhs[1:-1]
					#print "lhs: '" + lhs + "'" + "rhs: '" + rhs + "'"
					if rhs.find('T') != -1:
						self.dateStr, self.timeStr = rhs.split('T')
					else:
						self.dateStr, self.timeStr = rhs.split(' ')
					self.dateStr = bFixDate(self.dateStr)
					self.timeStr = bFixTime(self.timeStr)
					#bPrintLog('CZI date/time is: ' + self.dateStr + ' ' + self.timeStr, 3)
				# .czi
				# <Pixels BigEndian="false" DimensionOrder="XYCZT" ID="Pixels:0" Interleaved="false" PhysicalSizeX="0.20756645602494875" PhysicalSizeXUnit="µm" PhysicalSizeY="0.20756645602494875" PhysicalSizeYUnit="µm" PhysicalSizeZ="0.75" PhysicalSizeZUnit="µm" SignificantBits="8" SizeC="1" SizeT="1" SizeX="1024" SizeY="1024" SizeZ="50" Type="uint8">

			# czi have voxel in calibration
			self.voxelx = self.imp.getCalibration().pixelWidth; 
			self.voxely = self.imp.getCalibration().pixelHeight; 
			self.voxelz = self.imp.getCalibration().pixelDepth; 
			#bPrintLog('readZeissHeader() read czi scale as: ' + str(self.voxelx) + ' ' + str(self.voxely) + ' ' + str(self.voxelz), 3)

			# CLEARING self.infoStr for CZI ... it was WAY to big to parse in Map Manager
			self.infoStr = ''
			
	def printParams(self, loglevel=3): # careful, thefunction print() is already taken?
		bPrintLog('file:' + self.filepath, loglevel)
		bPrintLog("date:'" + self.dateStr + "' time:'" + self.timeStr + "'", loglevel)
		bPrintLog('channels:' + str(self.numChannels), loglevel)
		bPrintLog('zoom:' + str(self.zoom), loglevel)
		bPrintLog('pixels:' + str(self.width) + ',' + str(self.height)+ ',' + str(self.numSlices), loglevel)
		bPrintLog('voxels:' + str(self.voxelx) + ',' + str(self.voxely)+ ',' + str(self.voxelz), loglevel)

	def deinterleave(self):
		if self.numChannels == 1:
			bPrintLog('Warning: deinterleave() did not deinterleave with num channels 1', 0)
			return -1
		
		#IJ.run('Deinterleave', 'how=' + str(self.numChannels) +' keep') #makes ' #1' and ' #2', with ' #2' frontmost
		cmdStr = 'how=' + str(self.numChannels) + ' keep'
		IJ.run('Deinterleave', cmdStr) #makes ' #1' and ' #2', with ' #2' frontmost
		for i in range(self.numChannels):
			currenChannel = i + 1
			currentWindowName = self.windowname + ' #' + str(currenChannel)
			self.channelWindows.append(currentWindowName)
			
			currentImp = WindowManager.getImage(currentWindowName)
			if currentImp:
				self.channelImp.append(currentImp)
			else:
				bPrintLog('ERROR: deinterleave() did not find window names:' + currentWindowName, 0)
			
	def exportTifStack(self, destFolder=''):
		channelNumber = 1
		for imp in self.channelImp:
			if not destFolder:
				destFolder = os.path.join(self.enclosingPath, self.enclosingfolder + '_tif')
			if not os.path.isdir(destFolder):
				os.makedirs(destFolder)
			
			if not imp:
				bPrintLog("ERROR: exportTifStack() did not find an imp at channel number '" + str(channelNumber) + "'", 0)
				return -1
				
			self.updateInfoStr()
			imp.setProperty("Info", self.infoStr);

			saveFile = os.path.splitext(self.filename)[0] + '_ch' + str(channelNumber) + '.tif'
			savePath = os.path.join(destFolder, saveFile)

			# save
			fs = FileSaver(imp)
			bPrintLog('saveTifStack():' + savePath, 3)
			if imp.getNSlices()>1:
				fs.saveAsTiffStack(savePath)
			else:
				fs.saveAsTiff(savePath)

			channelNumber += 1

	def saveMaxProject(self, destFolder=''):
		channelNumber = 1
		for imp in self.channelImp:
			if not destFolder:
				destFolder = os.path.join(self.enclosingPath, self.enclosingfolder + '_tif', 'max')
			if not os.path.isdir(destFolder):
				os.makedirs(destFolder)

			# make max project
			zp = ZProjector(imp)
			zp.setMethod(ZProjector.MAX_METHOD)
			zp.doProjection()
			zimp = zp.getProjection()

			# save
			saveFile = 'max_' + os.path.splitext(self.filename)[0] + '_ch' + str(channelNumber) + '.tif'
			savePath = os.path.join(destFolder, saveFile)
			fs = FileSaver(zimp)
			bPrintLog('saveMaxProject():' + savePath, 3)
			fs.saveAsTiff(savePath)

			channelNumber += 1
			
	def closeAll(self):
		self.imp.close()
		for imp in self.channelImp:
			imp.close()
示例#39
0
from org.python.core import codecs
codecs.setDefaultEncoding('utf-8')

import os
from java.io import File
from ij import ImageJ, ImagePlus
from ij.io import Opener
from net.imglib2.img import Img, ImgFactory
from net.imglib2.img.cell import CellImgFactory
from net.imglib2.img.display.imagej import ImageJFunctions
from net.imglib2.type.numeric.real import FloatType



gitDir  = os.environ['GIT_HOME']
relImg  = "/OSImageAnalysis/images"
# strImg  = gitDir + relImg + "/bridge.gif"
strImg  = gitDir + relImg + "/latex.tif"

fi = File(strImg)
imp = Opener().openImage( fi.getAbsolutePath() )
imp.show()

imgFactory = CellImgFactory(5 )
img1 = imgFactory.create( (20, 30, 40), FloatType() )
ImageJFunctions.show( img1 )
img2 = imgFactory.create( img1, img1.firstElement() )
ImageJFunctions.show( img2 )


def scaleandfilter(infile,outfile,scalex,scaley,scalez,anisofilter,runtube):
	
	print ("infile is: "+infile)
	imp = Opener().openImage(infile)
	print imp
	print "scalex = %f; scaley = %f ; scalez = %f" % (scalex,scaley,scalez)
	
	# Rescale
	cal = imp.getCalibration()
	iml = ImgLib.wrap(imp)
	scaledimg = Scale3D(iml, scalex, scaley, scalez)
	imp2=ImgLib.wrap(scaledimg)
	
	# find range of pixel values for scaled image
	from mpicbg.imglib.algorithm.math import ComputeMinMax
	# (for imglib2 will be: net.imglib2.algorithm.stats)
	minmax=ComputeMinMax(scaledimg)
	minmax.process()
	(min,max)=(minmax.getMin().get(),minmax.getMax().get())
	# Make a copy of the stack (converting to 8 bit as we go)
	stack = ImageStack(imp2.width, imp2.height)
	print "min = %e, max =%e" % (min,max)
	for i in xrange(1, imp2.getNSlices()+1):
		imp2.setSliceWithoutUpdate(i)
		ip=imp2.getProcessor()
		# set range
		ip.setMinAndMax(min,max)
		stack.addSlice(str(i), ip.convertToByte(True))
	
	# save copy of calibration info
	cal=imp.getCalibration()
	# close original image
	imp.close()
	# make an image plus with the copy
	scaled = ImagePlus(imp2.title, stack)
	
	# Deal with calibration info which didn't seem to come along for the ride
	cal.pixelWidth/=scalex
	cal.pixelHeight/=scaley
	cal.pixelDepth/=scalez
	scaled.setCalibration(cal)
	print "dx = %f; dy=%f; dz=%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth)
	
	intif=infile+".tif"
	outtif=infile+"-filtered.tif"
	if anisofilter.upper() != 'FALSE':
		print("saving input file as "+intif)
		f=FileSaver(scaled)
		f.saveAsTiffStack(intif)
		scaled.close()
		# anisotropic filtering
		anisopts="-scanrange:10 -tau:2 -nsteps:2 -lambda:0.1 -ipflag:0 -anicoeff1:1 -anicoeff2:0 -anicoeff3:0"
		anisopts=anisopts+" -dx:%f -dy:%f -dz:%f" % (cal.pixelWidth,cal.pixelHeight,cal.pixelDepth)

		if sys.version_info > (2, 4):
			#for testing
			# subprocess.check_call(["cp",intif,outtif])
			subprocess.check_call([anisofilter]+anisopts.split(' ')+[intif,outtif])
		else:
			os.system(" ".join([anisofilter]+anisopts.split(' ')+[intif,outtif]))
		# Open anisofilter output back into Fiji
		print("Opening output tif: "+outtif)
		scaled = Opener().openImage(outtif)
		scaled.setCalibration(cal)
	
	# Hessian (tubeness)
	print("Running tubeness")
	if(runtube):
		tp=TubenessProcessor(1.0,False)
		result = tp.generateImage(scaled)
		IJ.run(result, "8-bit","")
	else:
		result=scaled
	# Save out file
	fileName, fileExtension = os.path.splitext(outfile)
	print("Saving as "+fileExtension+": "+outfile)
	if fileExtension.lower()=='.nrrd':
		nw=Nrrd_Writer()
		nw.setNrrdEncoding("gzip")
		nw.save(result,outfile)
	else:
		# Save to PIC
		IJ.run(result,"Biorad ...", "biorad=["+outfile+"]")
	scaled.close()
	result.close()
        #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]))
            for image in MouseIDcFos:
                #open image
                imp_orig = Opener().openImage(In_dir + image)
                #gaussian blur
                imp_GB = blurImage(imp_orig)
                imp_orig.close()
                #threshold
                imp_GB.getProcessor().threshold(threshold)
                #save
                newname = image.split('.')[0] + '_GPT_' + str(
                    percentiles[i]) + '.tif'
                IJ.saveAsTiff(imp_GB, Perc_Out_dir + newname)
                imp_GB.close()

        IJ.log('Mouse ' + MouseID + ' processed')

    print "DONE, find your results in " + Out_dir