예제 #1
0
    def saveAllImages(self, oldImages):
        try:
            #this will extract all the new images generated sence oldImages was created
            #and will save them all to the downloads folder
            titles2Save = WindowManager.getImageTitles()
            inspectorOutput = list(set(titles2Save) - set(oldImages))[0]
            im2Save = WindowManager.getImage(inspectorOutput)
            IJ.save(
                im2Save,
                join(
                    self.downloadsFolder, self.outputFolder +
                    "InspectorOutput" + self.uniqueID + ".tif"))
            iterID = int(0)
            for image in list(set(titles2Save) - set([inspectorOutput])):

                im2Save = WindowManager.getImage(image)
                IJ.save(
                    im2Save,
                    join(
                        self.downloadsFolder, self.uniqueID +
                        " speckleInspectorImage{}.tif".format(iterID)))
                iterID = iterID + 1
            print("saved all images.")
        except:
            print("failed to save all images.")
        finally:
            print("")
def runPoreDetection(inputImp, data, ops, display):

	name=inputImp.getTitle()	
	inputDataset=Utility.getDatasetByName(data, name)
	
	detectionParameters=DetectionParams()

	roi=inputImp.getRoi()
	if (roi is None):
		message=name+": "+Messages.NoRoi
		IJ.write(message)
		return

	roi=inputImp.getRoi().clone();

	header, statslist=poreDetectionTrueColor(inputImp, inputDataset, roi, ops, data, display, detectionParameters)

	directory, overlayname, roiname=Utility.createImageNames(inputImp)
	statsname=directory+'truecolor_stats.csv'
	
	IJ.save(inputImp, overlayname);
	IJ.saveAs(inputImp, "Selection", roiname);

	header.insert(0,Messages.FileName)
	statslist.insert(0,name)

	print header
	print statslist

	ExportDataFunction.exportSummaryStats(statsname, header, statslist)
예제 #3
0
 def saveNewImages(self, oldImages):
     try:
         #this will extract all the new images generated sence oldImages was created
         #and will save them all to the downloads folder
         newImages = WindowManager.getImageTitles()
         titles2Save = list(set(newImages) - set(oldImages))
         iterID = int(0)
         for image in titles2Save:
             im2Save = WindowManager.getImage(image)
             IJ.save(
                 im2Save,
                 join(
                     self.downloadsFolder,
                     self.outputFolder + " speckleInspectorOutput " +
                     self.uniqueID + "{}.tif".format(iterID)))
             iterID = iterID + 1
         for image in oldImages:
             #this loop will kill off the save dialog box that will
             #pop up for the secondary image
             im2Save = WindowManager.getImage(image)
             im2Save.changes = False
         print("saved new images.")
     except:
         print("failed to save new images.")
     finally:
         print("")
예제 #4
0
 def saveMIP(self):
     curdir = os.path.split(os.getcwd())[1]
     savename = self.saveDir + curdir + self.savfileName + "_MIP.tif"
     print "savename = ", savename
     print "saving...."
     IJ.save(self.outimp, savename)
     print "saved as", savename
def runPoreDetection(inputImp, data, ops, display):

    name = inputImp.getTitle()
    inputDataset = Utility.getDatasetByName(data, name)

    detectionParameters = DetectionParams()

    roi = inputImp.getRoi()
    if (roi is None):
        message = name + ": " + Messages.NoRoi
        IJ.write(message)
        return

    roi = inputImp.getRoi().clone()

    header, statslist = poreDetectionTrueColor(inputImp, inputDataset, roi,
                                               ops, data, display,
                                               detectionParameters)

    directory, overlayname, roiname = Utility.createImageNames(inputImp)
    statsname = directory + 'truecolor_stats.csv'

    IJ.save(inputImp, overlayname)
    IJ.saveAs(inputImp, "Selection", roiname)

    header.insert(0, Messages.FileName)
    statslist.insert(0, name)

    print header
    print statslist

    ExportDataFunction.exportSummaryStats(statsname, header, statslist)
 def scale_convertTo8Bit_montage(self):
     for channel in self.channel_names:
         # apply lut
         try:
             IJ.run(self.cropped_imps[channel], self.luts[channel], "")
         except:
             IJ.run(self.cropped_imps[channel], "Grays", "")
             ## min/max
         if channel not in self.contrasts:
             ## do quick autocontrast based on min/max
             self.contrasts[channel] = [
                 self.cropped_imps[channel].getProcessor().getMin(),
                 self.cropped_imps[channel].getProcessor().getMax(),
             ]
         try:
             c = self.contrasts[channel]
             self.cropped_imps[channel].getProcessor().setMinAndMax(c[0], c[1])
         except:
             print "Unable to do contrast"
             ## save 16 bit images
         directory = self.outdir
         file_name = self.name
         x = self.x
         y = self.y
         save_as = os.path.join(directory, "%s_%s_%s_%s.tif" % (file_name, channel, x, y))
         IJ.save(self.cropped_imps[channel], save_as)
         ## save RGBs
         IJ.run(self.cropped_imps[channel], "RGB Color", "")
         save_as = os.path.join(directory, "%s_%s_%s_%s_RGB.tif" % (file_name, channel, x, y))
         IJ.save(self.cropped_imps[channel], save_as)
     self.make_montage(xy="%sx%s" % (x, y))
def run():
  srcDir = DirectoryChooser("Choose!").getDirectory()
  if not srcDir:
    # user canceled dialog
    return
  
  for root, directories, filenames in os.walk(srcDir):
    for filename in filenames:
      # Skip non-TIFF files
      if not filename.endswith(fileID):
        continue
      path = os.path.join(root, filename)
      print path
      imp = IJ.openImage(path)
      imp.show()
      if method=="contrast":
        IJ.run(imp,"Enhance Contrast", "saturated=0.35");
        time.sleep(0.2)
        IJ.save(imp,path + "_auto.jpeg")
        imp.changes = False
        imp.getWindow().close()
      elif method=="scale":
        IJ.run(imp, "Scale...", "x=0.2 y=0.2 interpolation=None create title=small");      
        impScale = IJ.getImage()
        time.sleep(0.2)
        IJ.save(impScale,path + "_thumb.jpeg")
        imp.changes = False
        imp.getWindow().close()
        impScale.changes = False
        impScale.getWindow().close()
예제 #8
0
def getTortuosity(directory, imageName):
    print(imageName)
    image = IJ.openImage(directory + imageName)

    skeletoniseWrapper = cs.run("org.bonej.wrapperPlugins.SkeletoniseWrapper",
                                False, ["inputImage", image])
    skeletonInstance = skeletoniseWrapper.get()
    skeleton = skeletonInstance.getOutput("skeleton")
    IJ.save(
        skeleton,
        directory + "Skeletons/" + imageName.replace(".tif", "") + "-skeleton")

    wrapper = cs.run("org.bonej.wrapperPlugins.AnalyseSkeletonWrapper", False,
                     ["inputImage", image, "verbose", True])
    wrapperInstance = wrapper.get()

    table = wrapperInstance.getOutput("verboseTable")
    print(table[0])
    nskeletons = max(table[0])
    print(nskeletons)
    branchLength = table[2]
    euclideanDistance = table[9]
    if (len(branchLength) > nskeletons):
        print("multiple branches in skeleton: returning zero tortuosity")
        return [0, 0, 0]
    avgBL = sum(branchLength) / float(nskeletons)
    avgED = sum(euclideanDistance) / float(nskeletons)
    print("branch length: ", avgBL)
    print("euclidean distance: ", avgED)
    tortuosity = avgED / avgBL
    return [avgBL, avgED, tortuosity]
예제 #9
0
 def saveMask(self, maskdir):
     imp = self.mask
     imp.getProcessor().invert()
     filebasename = os.path.basename(self.filename)
     maskfilename = os.path.join(maskdir, "mask_%s" % filebasename)
     IJ.save(imp, maskfilename)
     IJ.log("Mask image: %s\n" % maskfilename)
예제 #10
0
def contrastImage():
	while atomicI.get() < nPaths:
		k = atomicI.getAndIncrement()
		if k < nPaths:
			im = IJ.openImage(toContrastPaths[k][0])
			im = fc.normLocalContrast(im, normLocalContrastSize, normLocalContrastSize, 3, True, True)
			IJ.save(im, toContrastPaths[k][1])
			im.close()
예제 #11
0
def analyzeImage(passImage, passModel, passChannel, passProbability,
                 passPixels, passOutput):
    retResults = list()
    windows = set()

    # Register current window
    registerWindow(passImage.title, windows)

    # Extract the requested channel
    IJ.run("Z Project...", "projection=[Max Intensity]")
    registerWindow("MAX_" + passImage.title, windows)
    IJ.run("Duplicate...", "title=temp")
    registerWindow("temp", windows)

    # Apply WEKA training model to image
    wekaSeg = WekaSegmentation(WindowManager.getCurrentImage())
    wekaSeg.loadClassifier(passModel)
    wekaSeg.applyClassifier(True)

    # Extract first slice of probability map
    wekaImg = wekaSeg.getClassifiedImage()
    wekaImg.show()
    registerWindow("Probability maps", windows)
    IJ.setSlice(1)
    IJ.run("Duplicate...", "title=temp2")
    registerWindow("temp2", windows)

    # Apply threshold and save
    IJ.setThreshold(passProbability, 1, "Black & White")
    fileParts = passImage.getTitle().split(".")
    IJ.save(
        os.path.join(
            passOutput, "{0}-probmap.png".format(fileParts[0],
                                                 '.'.join(fileParts[1:]))))

    # Perform particle analysis and save
    IJ.run("Analyze Particles...",
           "size={0}-Infinity show=Outlines pixel clear".format(passPixels))
    registerWindow("Drawing of temp2", windows)
    IJ.save(
        os.path.join(
            passOutput, "{0}-particles.png".format(fileParts[0],
                                                   '.'.join(fileParts[1:]))))

    # Get measurements
    tableResults = ResultsTable.getResultsTable()
    for rowIdx in range(tableResults.size()):
        retResults.append(tableResults.getRowAsString(rowIdx).split())
        retResults[-1].insert(
            0,
            WindowManager.getCurrentImage().getCalibration().unit)
        retResults[-1].append(
            float(retResults[-1][4]) / float(retResults[-1][3]))

    # Close windows
    closeWindows(windows)

    return retResults
def run():
    time_dirs = glob(os.path.join(input_dir.getPath(), 't*/'))

    for time_dir in time_dirs:
        log.info('\tprocessing %s' % time_dir)

        # Extract information from file name
        xy_files = glob(os.path.join(time_dir, '*.tif'))
        match = re.search('(.*)_x\d_y\d_t(\d{1,2})\.tif',
                          os.path.basename(xy_files[0]))
        if not match:
            log.error('\tCould not extract time digits from %s\nAbort.' %
                      (time_dir))
            return

        experiment = match.group(1)
        time = match.group(2)
        fields = str(len(xy_files))
        log.info('\t\texperiment=%s, time-point=%s, #files=%s' %
                 (experiment, time, fields))

        # Compose the output file name
        output_file = os.path.join(input_dir.getPath(),
                                   experiment + '_t' + time + '.tif')
        if os.path.exists(output_file):
            log.info('\t\talreday stitched: %s)' % output_file)
            continue

        # Run the stitching macro
        print '\t\truning stitching plugin...'
        IJ.run('Grid/Collection stitching', \
               'type=[Filename defined position]' + \
               ' order=[Defined by filename         ]' + \
               ' grid_size_x=1' + \
               ' grid_size_y=' + fields + \
               ' tile_overlap=' + str(overlap) + \
               ' first_file_index_x=1' + \
               ' first_file_index_y=1' + \
               ' directory=' + time_dir + \
               ' file_names=12_x{x}_y{y}_t' + time + '.tif' + \
               ' output_textfile_name=TileConfiguration.txt' + \
               ' fusion_method=[Linear Blending]' + \
               ' regression_threshold=0.30' + \
               ' max/avg_displacement_threshold=2.50' + \
               ' absolute_displacement_threshold=3.50' + \
               ' compute_overlap' + \
               ' subpixel_accuracy' + \
               ' computation_parameters=[Save computation time (but use more RAM)]' + \
               ' image_output=[Fuse and display]')

        # Save the output
        imp = WindowManager.getImage("Fused")
        IJ.save(imp, output_file)
        log.info('\t\tsaved:  %s' % (output_file))
        IJ.run('Close All')

    log.info('Done.')
예제 #13
0
def exportFlatForPresentations(project,outputFolder,scaleFactor,rectangle):
	layerset = project.getRootLayerSet()
	loader = project.getLoader()
	for l,layer in enumerate(layerset.getLayers()): # import the patches
		IJ.log('Exporting layer ' + str(l) + 'with rectangle ' + str(rectangle) + 'scale factor ' + str(scaleFactor))
		imp = loader.getFlatImage(layer,rectangle,scaleFactor, 0x7fffffff, ImagePlus.GRAY8, Patch, layer.getAll(Patch), True, Color.black, None)
		IJ.save(imp,outputFolder + os.sep + nameFromPath(outputFolder.rstrip(os.sep)) + '_' + str(l) + '.tif') #use the name of the outputFolder to name the images
		IJ.log('Layer ' + str(l)+' flat exported to ' + outputFolder + os.sep + nameFromPath(outputFolder.rstrip(os.sep)) + '_' + str(l) + '.tif')
		imp.close()
예제 #14
0
def saveImg(imp, nslices, label):
	mask = WindowManager.getImage('Mask of ' + imp.getTitle())
	IJ.save(mask, saveDir + '/' + title + '_' + label + '.tif')
	labeled = mask.duplicate()
	for n in range(1,nslices+1):
		s = labeled.getStack().getProcessor(n);
		s.setFont(Font("SansSerif", Font.BOLD, 30));
		s.setColor(Color.blue);
		s.drawString(title + ' Layer: ' + label + ' Slice: ' + str(n), 20, 40)
	labeled.updateAndDraw()
	IJ.save(labeled, saveDir + '/labeled_' + title + '_' + label + '.tif')
	IJ.run("Close")
def main():
    files = []
    for filt in img_extensions.split(";"):
        if len(filt.strip()) > 0:
            files += glob.glob(os.path.join(str(input_dir), filt.strip()))
        else:
            files += glob.glob(os.path.join(str(input_dir), "*.*"))
            break

    if len(files) == 0:
        IJ.showMessage("No files found in '{}'\nfor extensions '{}'".format(
            str(input_dir), img_extensions))
    else:
        for fn in files:
            try:
                imp = BF.openImagePlus(fn)[0]
            except:
                IJ.showMessage(
                    "Could not open file '{}' (skipping).\nUse extension filter to filter non-image files..."
                    .format(str(fn)))
                continue

            img = IJF.wrap(imp)

            cali = imp.getCalibration().copy()
            if pixel_width > 0:
                cali.pixelWidth = pixel_width
                cali.pixelHeight = pixel_width
                cali.setUnit("micron")
            if frame_interval > 0:
                cali.frameInterval = frame_interval
                cali.setTimeUnit("sec.")

            imp_out = smooth_temporal_gradient(ops, img, sigma_xy, sigma_t,
                                               frame_start, frame_end,
                                               normalize_output)
            imp_out.setCalibration(cali)

            channels = ChannelSplitter.split(imp_out)

            fn_basename = os.path.splitext(fn)[0]
            IJ.save(channels[0], "{}_shrinkage.tiff".format(fn_basename))
            IJ.save(channels[1], "{}_growth.tiff".format(fn_basename))

            print("{} processed".format(fn_basename))

        IJ.showMessage(
            "Growth/shrinkage extraction of {} inputs finsihed.".format(
                len(files)))
예제 #16
0
def main(argv):
    """Convert .dm3 files to tifs."""

    inputdir = 'INPUTDIR'
    outputdir = 'OUTPUTDIR'
    output_postfix = 'OUTPUT_POSTFIX'

    infiles = glob.glob(os.path.join(inputdir, '*.dm3'))

    for infile in infiles:
        imp = BF.openImagePlus(infile)
        tail = os.path.split(infile)[1]
        filename = os.path.splitext(tail)[0][-4:] + output_postfix + '.tif'
        outpath = os.path.join(outputdir, filename)
        IJ.save(imp[0], outpath)
예제 #17
0
def exportFlatCloseFiji(project,outputFolder,scaleFactor):
	#todo: check whether the output file already exists. If yes, skip
	for l,layer in enumerate(layerset.getLayers()):
		savePath = outputFolder + os.sep + nameFromPath(outputFolder.rstrip(os.sep)) + '_' + str(l) + '.tif'
		savePathNext = outputFolder + os.sep + nameFromPath(outputFolder.rstrip(os.sep)) + '_' + str(l+1) + '.tif'
		if os.isfile(savePathNext):
			IJ.log('Skipping layer ' + str(l) + ': already processed')
		else:
			IJ.log('Exporting layer ' + str(layer) + '; layer number ' + str(l))
		layerset = project.getRootLayerSet()
		loader = project.getLoader()
		imp = loader.getFlatImage(layer,layerset.get2DBounds(),scaleFactor, 0x7fffffff, ImagePlus.GRAY8, Patch, layer.getAll(Patch), True, Color.black, None)
		IJ.save(imp, savePath)
		IJ.log('Layer ' + str(layerCurrent)+' flat exported to ' + savePath)
		imp.close()
	IJ.log('exportFlatCloseFiji has reached the end')
def saveIndividualTimePoints(inputImp, outputFolder):
    imp = inputImp
    width, height, nChannels, nSlices, nFrames = imp.getDimensions()
    print nSlices
   
    for f in range(nFrames):
        print "frame: ", f
        minSlice = (f*nSlices)+1
        maxSlice = (f+1)*(nSlices)
        slices = str(minSlice) + "-" + str(maxSlice)
        print "Isolating slices ",slices
        subStack = SubstackMaker().makeSubstack(imp, slices)

        name = "t"+ str(f) + ".tif"
        IJ.save(subStack, path.join(outputFolder, name) )
        imp.close()
예제 #19
0
def runPoreDetection(inputImp, data, ops, display):

    # in this step get the image in the "imagej2" dataset format
    # this way we can take advantage of some of the new imagej2 functionality
    name = inputImp.getTitle()

    inputDataset = Utility.getDatasetByName(data, name)

    # this structure keeps track of detection parameters
    detectionParameters = DetectionParams()

    roi = inputImp.getRoi()

    # check if there is an roi on the image.  If not return an error
    if (roi is None):
        message = name + ": " + Messages.NoRoi
        IJ.write(message)
        return

    # clone the roi
    roi = inputImp.getRoi().clone()

    # call the function that processes the UV image
    roilist, statslist, statsheader = poreDetectionUV(inputImp, inputDataset,
                                                      roi, ops, data, display,
                                                      detectionParameters)

    # get the names for the images that will be saved
    directory, overlayname, roiname = Utility.createImageNames(inputImp)

    # name of file to save summary stats
    statsname = os.path.join(directory, 'stats.csv')

    # save the image with overlay
    IJ.save(inputImp, overlayname)

    # save the roi
    IJ.saveAs(inputImp, "Selection", roiname)

    statsheader.insert(0, Messages.FileName)
    statslist.insert(0, name)

    ExportDataFunction.exportSummaryStats(statsname, statsheader, statslist)

    print statsname
    print statsheader
    print statslist
def runPoreDetection(inputImp, data, ops, display):

	

	# in this step get the image in the "imagej2" dataset format
	# this way we can take advantage of some of the new imagej2 functionality
	name=inputImp.getTitle()	

	inputDataset=Utility.getDatasetByName(data, name)

	# this structure keeps track of detection parameters
	detectionParameters=DetectionParams()

	roi=inputImp.getRoi()

	# check if there is an roi on the image.  If not return an error
	if (roi is None):
		message=name+": "+Messages.NoRoi
		IJ.write(message)
		return

	# clone the roi
	roi=inputImp.getRoi().clone();

	# call the function that processes the UV image
	roilist, statslist, statsheader=poreDetectionUV(inputImp, inputDataset, roi, ops, data, display, detectionParameters)
	
	# get the names for the images that will be saved
	directory, overlayname, roiname=Utility.createImageNames(inputImp)
	
	# name of file to save summary stats 
	statsname=os.path.join(directory, 'stats.csv')
	
	# save the image with overlay
	IJ.save(inputImp, overlayname);
	
	# save the roi 
	IJ.saveAs(inputImp, "Selection", roiname);

	statsheader.insert(0,Messages.FileName)
	statslist.insert(0,name)

	ExportDataFunction.exportSummaryStats(statsname, statsheader, statslist)

	print statsname
	print statsheader
	print statslist
예제 #21
0
def analyzeImage(passImage, passModel, passProbability, passPixels,
                 passOutput):
    retResults = list()

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

    # Extract first slice of probability map
    wekaImg = wekaSeg.getClassifiedImage()
    wekaImg.show()

    IJ.selectWindow("Probability maps")
    IJ.setSlice(1)
    IJ.run("Duplicate...", "title=temp")

    # Apply threshold and save
    IJ.setThreshold(passProbability, 1, "Black & White")
    fileParts = passImage.getTitle().split(".")
    IJ.save(
        os.path.join(
            passOutput, "{0}-probmap.png".format(fileParts[0],
                                                 '.'.join(fileParts[1:]))))

    # Perform particle analysis and save
    IJ.run("Analyze Particles...",
           "size={0}-Infinity show=Outlines pixel clear".format(passPixels))
    IJ.selectWindow("Drawing of temp")
    IJ.save(
        os.path.join(
            passOutput, "{0}-particles.png".format(fileParts[0],
                                                   '.'.join(fileParts[1:]))))

    # Get measurements (skip final row, this will correspond to legend)
    tableResults = ResultsTable.getResultsTable()
    for rowIdx in range(tableResults.size() - 1):
        retResults.append(tableResults.getRowAsString(rowIdx).split())

    # Close interim windows
    IJ.run("Close")
    IJ.selectWindow("temp")
    IJ.run("Close")
    IJ.selectWindow("Probability maps")
    IJ.run("Close")

    return retResults
예제 #22
0
def exportFlat(project,outputFolder,scaleFactor, baseName = '', bitDepth = 8, layers = [], roi = ''):
	layerset = project.getRootLayerSet()
	loader = project.getLoader()
	for l,layer in enumerate(layerset.getLayers()):
		if (layers ==[] ) or (l in layers):
			IJ.log('Exporting layer ' + str(l))
			if roi == '':
				roiExport = layerset.get2DBounds()
			else:
				roiExport = roi
			if bitDepth == 8:
				imp = loader.getFlatImage(layer,roiExport,scaleFactor, 0x7fffffff, ImagePlus.GRAY8, Patch, layer.getAll(Patch), True, Color.black, None)
			elif bitDepth == 16:
				imp = loader.getFlatImage(layer,roiExport,scaleFactor, 0x7fffffff, ImagePlus.GRAY16, Patch, layer.getAll(Patch), True, Color.black, None)
			savePath = os.path.join(outputFolder, baseName + '_' + str(l).zfill(4) + '.tif')
			IJ.save(imp, savePath)
			IJ.log('Layer ' + str(l) +' flat exported to ' + savePath)
			imp.close()
예제 #23
0
def find_folders(inpt_folder):

    #get list of folders and open folder one after the other
    for idx, i in enumerate(os.listdir(inpt_folder)):
        if os.path.isdir(os.path.join(inpt_folder, i)):
            comp_img, timepoints = open_images(os.path.join(inpt_folder, i))
            corrected_img, corrected_img_bleach = pre_process_images(
                comp_img, timepoints)

            create_folder(os.path.join(inpt_folder, i, "Corrected"))
            file_name = i + "_Red_corrected.tif"
            folder_file = os.path.join(inpt_folder, i, "Corrected", file_name)
            IJ.save(corrected_img, folder_file)

            create_folder(os.path.join(inpt_folder, i, "Corrected_bleach"))
            file_name = i + "_Red_corrected_bleach.tif"
            folder_file = os.path.join(inpt_folder, i, "Corrected_bleach",
                                       file_name)
            IJ.save(corrected_img_bleach, folder_file)
def process(srcDir, currentDir, fileName, table, numberOfWidthMeasurements):
    if "control-images" in currentDir:
      return   
    print "Processing:"
    # Opening the image
    print "Open image file", fileName
    imp = IJ.openImage(os.path.join(currentDir, fileName)) 
    # Put your processing commands here!
    imp.show()
   
    processCurrentImage(table);

    impIn = WindowManager.getCurrentImage()
    path = os.path.join(srcDir, 'control-images')
    if not os.path.exists(path):
      os.makedirs(path)
    IJ.save(os.path.join(path, fileName))
    impIn.changes = False
    impIn.close()
예제 #25
0
def exportFlatRoi(project, scaleFactor, x, y, w, h, layer, saveName):
	loader = project.getLoader()
	rectangle = Rectangle(x-int(w/2),y-int(h/2),w,h)
	patches = layer.find(Patch, x, y)
	print patches
	# IJ.log('patches' + str(patches))

	for p, patch in enumerate(patches):
		visible = patch.visible
		patch.visible = True
		tiles = ArrayList()
		tiles.add(patch)
		print 'tiles',tiles
		print 'rectangle',rectangle
		IJ.log('Patch ' + str(patch) + ' cropped with rectangle ' + str(rectangle) )
		imp = loader.getFlatImage(layer, rectangle, scaleFactor, 0x7fffffff, ImagePlus.GRAY8, Patch, tiles, True, Color.black, None)
		exportName = saveName + '_' + str(int(p)) + '.tif'
		IJ.save(imp, exportName)
		patch.visible = visible
 def make_montage(self, xy="", montage_name=""):
     if self.channels_to_montage == None:
         channels_to_montage = self.channel_names
     else:
         channels_to_montage = self.channels_to_montage
     w = self.cropped_imps[self.channel_names[0]].width
     h = self.cropped_imps[self.channel_names[0]].height
     new_stack = ImageStack(w, h)
     # print self.cropped_imps.keys()
     for channel in channels_to_montage:
         img = self.cropped_imps[channel].getProcessor()
         new_stack.addSlice(img)
     tomontage = ImagePlus("to montage", new_stack)
     montager = MontageMaker()
     self.montage = montager.makeMontage2(
         tomontage, len(channels_to_montage), 1, 1, 1, len(channels_to_montage), 1, 0, 0
     )
     directory = self.outdir
     file_name = self.name
     save_as = os.path.join(directory, "%s_%s_montage.tif" % (file_name, xy))
     IJ.save(self.montage, save_as)
예제 #27
0
 def saveNewImage(self, oldImages):
     try:
         #this will extract one image
         newImages = WindowManager.getImageTitles()
         title2Save = list(set(newImages) - set(oldImages))
         im2Save = WindowManager.getImage(title2Save[0])
         IJ.save(
             im2Save,
             join(
                 self.downloadsFolder, self.outputFolder +
                 " speckleInspectorOutput " + self.uniqueID + ".tif"))
         for image in list(set(newImages) - set([title2Save[0]])):
             #this loop will kill off the save dialog box that will
             #pop up for other images bescides the Inspector output
             im2Save = WindowManager.getImage(image)
             im2Save.changes = False
         print("saved new image.")
     except:
         print("failed to save image.")
     finally:
         print("")
예제 #28
0
def convertAndSaveFile(fullFilePath, convertTo8Bit=False, allowOverwrite=False):
	"""
	"""
	print('  convertAndSaveFile() fullFilePath:', fullFilePath)
	
	folderPath, fileName = os.path.split(fullFilePath)
	fileNameNoExtension = os.path.splitext(fileName)[0]
	saveFileNoExtension = os.path.join(folderPath, fileNameNoExtension)
	
	#
	# load file and build a dict of parameters like (channels, pixels, voxels)
	myFileInfo, imp = bSimpleFileInfo.myLoadFile(fullFilePath, doShow=True)
	
	if convertTo8Bit:
		# from (ImagePlus.GRAY8, ImagePlus.GRAY16, ImagePlus.GRAY32, ImagePlus.COLOR_256 or ImagePlus.COLOR_RGB)
		myType = imp.getType()
		if myType in [1,2]:
			ic = ImageConverter(imp) # converts channelImp in place
			scaleConversions = True
			ic.setDoScaling(scaleConversions) # scales inensities to fill 0...255
			ic.convertToGray8()		

	#
	# split channels
	channelArray = ChannelSplitter.split(imp) # returns an array of imp
	
	for channelIdx, channelImp in enumerate(channelArray):
		# channelImp is an imp, this will NOT have fileinfo (we just created it)
		#channelImp.show()
		
		saveFilePath = saveFileNoExtension + '_ch' + str(channelIdx+1) + '.tif'
		print('    ch:', channelIdx+1, 'saveFilePath:', saveFilePath)
		
		if not allowOverwrite and os.path.isfile(saveFilePath):
			print(' .   not saving, file already exists', saveFilePath)
		else:
			IJ.save(channelImp, saveFilePath)

	return myFileInfo
예제 #29
0
def main():
	root = myDir.getPath() # get the root out the java file object
	print(root)
	
	import os, glob

	# set up bioformats
	from loci.plugins import BF
	from loci.plugins.in import ImporterOptions
	options = ImporterOptions()
	options.setColorMode(ImporterOptions.COLOR_MODE_COMPOSITE)
	options.setGroupFiles(True)  # if the files are named logically if will group them into a stack
  	
	# this will do the maximum intensity projection
	from ij.plugin import ZProjector
	Zproj = ZProjector()

	for path, subdirs, files in os.walk(root):
		print(path)
		# just get the one of the files that matches your image pattern
		flist = glob.glob(os.path.join(path,"*.tif"))
		print(len(flist))
		if( flist ):
			file = flist[0]
			print("Processing {}".format(file))
			options.setId(file)
			imp = BF.openImagePlus(options)[0]

			# show the image if you want to see it
			IJ.run(imp, "Grays", "")
			imp.show()

			imp_max = Zproj.run(imp,'max')
			IJ.run(imp_max, "Grays", "")
			imp_max.show()

			# save the Z projection
			IJ.save(imp_max,file.rsplit('_',1)[0]+'_processed.tif')
예제 #30
0
def prepareImage(passDir, passFile, passOutput, passPixels, passBlur, passThreshold):
	# Attempt to open as image, exit if not
	fullPath = os.path.join(passDir, passFile)
	retImage = IJ.openImage(fullPath)
	if not retImage: return None
	retImage.show()

	# Resize canvas to prepare for fast rotations, select original
	imgWidth = retImage.getWidth()
	imgHeight = retImage.getHeight()
	maxDim = math.sqrt(imgWidth ** 2 + imgHeight ** 2)
	borderX = (maxDim - imgWidth)/2
	borderY = (maxDim - imgHeight)/2
	
	IJ.run("Canvas Size...", "width={0} height={0} position=Center".format(maxDim))
	IJ.makeRectangle(borderX, borderY, imgWidth, imgHeight) 

	# Set scale to pixels (will manually calculate later)
	IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel");

	# Blur "overhanging" projections
	IJ.run("Gaussian Blur...", "sigma={0}".format(passBlur))
	
	# Set threshold 
	IJ.setAutoThreshold(retImage, "{0} dark apply".format(passThreshold))
	IJ.makeRectangle(0, 0, retImage.getWidth(), retImage.getHeight()) 
		
	# Analyze particles and obtain outline image
	IJ.run("Analyze Particles...", "size={0}-Infinity show=Outlines pixel clear".format(passPixels));
	IJ.selectWindow("Drawing of {0}".format(retImage.getTitle()))
	
	fileParts = passFile.split(".")
	IJ.save(os.path.join(passOutput, "{0}-outline-{1}.{2}".format(fileParts[0], passThreshold, '.'.join(fileParts[1:]))))
	IJ.run("Close")

	return retImage
예제 #31
0
def cropAndSave(name, row):
    # for checking bounds and making Regions of Interest (ROI, or aka rectangles)
    # 4.818 comes from converting micron to pixels
    global prolif_counter
    global iffy_counter
    global senescent_counter
    global curr
    global length
    global height
    global batch_folder
    # checking for out of bounds
    if float(row[4]) < 152.0 or float(row[5]) < 152.0 or float(row[4]) + float(
            row[6]) > 27000 or float(row[5]) + float(row[7]) > 27000:
        IJ.log("outta bounds")
        return
    else:
        topLeft_x = int(float(row[2]) * 4.818 - (length / 2))
        topLeft_y = int(float(row[3]) * 4.818 - (height / 2))
        c3.setRoi(topLeft_x, topLeft_y, length, height)
        temp_image = c3.crop()  # note: does not render, so saves memory
        #temp_image.show()
        IJ.log("Mean: " + row[1])
        if float(row[1]) < 10:
            IJ.save(
                temp_image, "D:/Stem_Cells/Batches/%s/Senescent/cell%i.tiff" %
                (batch_folder, senescent_counter))
            senescent_counter += 1
            IJ.log("senescent saved")
        elif float(row[1]) > 30:
            IJ.save(
                temp_image, "D:/Stem_Cells/Batches/%s/Prolif/cell%i.tiff" %
                (batch_folder, prolif_counter))
            #IJ.save(temp_image,"D:/Stem_Cells/A3_Exp/cell%i.tif" %prolif_counter)
            #IJ.save(temp_image,"D:/Stem_Cells/A3_Exp/sub_exp/cells/test/Proliferative/cell%i.tif" %prolif_counter)
            prolif_counter += 1
            IJ.log("prolif saved")
        else:
            IJ.save(
                temp_image, "D:/Stem_Cells/Batches/%s/Iffy/cell%i.tif" %
                (batch_folder, iffy_counter))
            iffy_counter += 1
            IJ.log("iffy saved")
예제 #32
0
	capturer.execute(trackmate)

#---------------
# Export results
#---------------

dir = File(settings.imageFolder + '/Tracked')
dir.mkdir()

if not batchmode:
	cap = WindowManager.getImage("TrackMate capture")
	if not WindowManager.checkForDuplicateName:
		capTitle = 'Captured_' + settings.imageFileName
		capFile = File(dir, '/' + capTitle)
		print 'Saving capture to ' + capFile.getPath()
		IJ.save(cap, capFile.getPath())
		cap.setTitle(capTitle)
	else: 
		print 'Warning: Capture not saved because there are duplicate ImagePlus names'
		loglist.append ('Warning: Capture not saved because there are duplicate ImagePlus names')
		model.getLogger().log('Warning: Capture not saved because there are duplicate ImagePlus names')

if batchmode:
	batchtracks = File(dir, 'Tracked_Batch_' + settings.imageFileName + '.xml')
	ExportTracksToXML.export(model, settings, batchtracks)
else:
	tracks = File(dir, 'Tracked_TracksOnly.xml')
	ExportTracksToXML.export(model, settings, tracks)

file = File(dir, 'Tracked_Complete.xml')
print 'Preparing to save complete xml to ' + file.getPath()
예제 #33
0
def runVesselDistance(path):
    """
	path: full path to original oir file
	"""

    #
    # PREPROCESS (mean, threshold, closing)

    # pre-process ch1
    ch1_AnalysisOptions = getDefaultAnalysisDict(1)
    ch1_AnalysisOptions, ch1_Final_Mask_Title, impCh1 = myPreProcess(
        path, ch1_AnalysisOptions)
    if ch1_AnalysisOptions is None:
        # there was an error in myPreProcess
        return None

    # pre-process ch1
    ch2_AnalysisOptions = getDefaultAnalysisDict(2)
    ch2_AnalysisOptions['removeBlobsSmallerThan'] = 100  # units ???
    ch2_AnalysisOptions, ch2_Final_Mask_Title, impCh2 = myPreProcess(
        path, ch2_AnalysisOptions)
    if ch2_AnalysisOptions is None:
        # there was an error in myPreProcess
        return None

    ##
    ## Calculate (EDT, EVF)
    ## 	in general, we want pixel values from EDT but only for pixels in EVF in range [0.0, 1.0]
    ## 	todo: I am not going to get to this right now
    ##

    doDistanceMap = False
    if doDistanceMap:
        # this is using '#D ImageJ Suite
        # see: https://imagejdocu.tudor.lu/doku.php?id=plugin:stacks:3d_ij_suite:start
        #myThreshold = 1
        #paramStr = 'map=Both image=' + ch2_Final_Mask_Title + ' mask=' + ch1_Final_Mask_Title + ' threshold=' + str(myThreshold) + ' inverse'
        paramStr = 'map=Both image={0} mask={1} threshold={2} inverse'.format(
            ch2_Final_Mask_Title, ch1_Final_Mask_Title, myThreshold)
        print('3D Distance Map paramStr:', paramStr)
        print(
            ' . calculating (EDT, EVF) ... this will make new windows (EDT, EVF) ...please wait'
        )
        IJ.run("3D Distance Map", paramStr)
        IJ.run("Fire", "")  # set last window, evf, to fire

        # shrink (EDT, EVF) windows
        '''
			Both (EDT, EVF) are 32-bit images
			EDT has:
				pixel values set to the micrometer distance to the vascular mask
			EVF has pixel values:
				-1: pixels that were in the ch2 vascular mask
				0: pixels outside the ch1 HCN1 mask
				[0..1]: distance between pixels in HCN1 mask and vascular map (these are normalized)
	
			todo:
				for each value in SVF between [0..1], grab value in EDT (in microns)
		'''

    ##
    # save results
    ##

    #
    # make output folder
    folderPath, filename = os.path.split(path)
    fileNameNoExtension, fileExtension = filename.split('.')

    outputPath = os.path.join(folderPath, 'distanceAnalysis')
    if not os.path.exists(outputPath):
        os.makedirs(outputPath)

    # append to this to get final output fil path ('_ch1.tif', '_ch2.tif', '_ch1_mask.tif', ...)
    outBasePath = os.path.join(outputPath, fileNameNoExtension)

    # ch1
    ch1SavePath = outBasePath + '_ch1.tif'
    print(' . saving ch1:', ch1SavePath)
    IJ.save(impCh1, ch1SavePath)

    # ch2
    ch2SavePath = outBasePath + '_ch2.tif'
    print(' . saving ch2:', ch2SavePath)
    IJ.save(impCh2, ch2SavePath)

    # ch1 mask
    impCh1Mask = WindowManager.getImage(ch1_Final_Mask_Title)
    ch1MaskSavePath = outBasePath + '_ch1_mask.tif'
    print(' . saving ch1 mask:', ch1MaskSavePath)
    IJ.save(impCh1Mask, ch1MaskSavePath)

    # ch2 mask
    impCh2Mask = WindowManager.getImage(ch2_Final_Mask_Title)
    ch2MaskSavePath = outBasePath + '_ch2_mask.tif'
    print(' . saving ch2 mask:', ch2MaskSavePath)
    IJ.save(impCh2Mask, ch2MaskSavePath)

    if doDistanceMap:
        impEDT = WindowManager.getImage('EDT')
        edtSavePath = outBasePath + '_edt.tif'
        print(' . saving EDT:', edtSavePath)
        IJ.save(impEDT, edtSavePath)

        impEVF = WindowManager.getImage('EVF')
        evfSavePath = outBasePath + '_evf.tif'
        print(' . saving EVF:', evfSavePath)
        IJ.save(impEVF, evfSavePath)

    ##
    # merge results into composite (merge EVF and vessel mask)
    ##
    '''
	IJ.selectWindow(edmFile);
	IJ.run("Enhance Contrast", "saturated=0.35"); # not sure how to calculate auto, 0.35 will be different !!!
	IJ.run("Apply LUT", "stack");
	# merge into composite
	print(' .  === merging into composite')
	#impOriginalWindowTitle was assigned right at start
	maskWindowTitle = imp.getTitle() # (mean, threshold) was done in place on copy
	edmWindowTitle = edmImp.getTitle()
	# run("Merge Channels...", "c1=20200420_distalHEAD__ch2.tif c2=20200420_distalHEAD__ch2_mask.tif c3=20200420_distalHEAD__ch2_edm.tif create keep ignore");
	paramStr = 'c1=' + impOriginalWindowTitle + ' c2=' + maskWindowTitle + ' c3=' + edmWindowTitle + ' create keep ignore'
	IJ.run("Merge Channels...", paramStr)
	'''

    # tile all the windows
    IJ.run('Tile', '')

    #
    print('closing all windows')
    #closeWorked = WindowManager.closeAllWindows()

    return True
예제 #34
0
#!/bin/sh
''''exec "$(dirname "$0")"/../fiji --jython "$0" "$@" # (call again with fiji)'''

import sys
from ij import IJ, ImageJ

if len(sys.argv) < 2:
	print 'Need an output file'
	sys.exit(1)

window = ImageJ()
window.hide()
IJ.run("Capture Screen ")
IJ.save(sys.argv[1])
sys.exit(0)
예제 #35
0
import os
from ij import IJ, ImagePlus

srcDir = "/home/albert/jo/casa/Cambridge/Fulbrooke Road/Fulbrooke Road/HR/"
tgtDir = "/home/albert/jo/casa/Cambridge/Fulbrooke Road/Fulbrooke Road/HR-0.5/"

if not os.path.exists(tgtDir):
    os.makedirs(tgtDir)

for filename in os.listdir(srcDir):
    if filename.endswith(".jpg"):
        imp = IJ.openImage(os.path.join(srcDir, filename))
        ip = imp.getProcessor().resize(imp.getWidth() / 2)
        IJ.save(ImagePlus(imp.getTitle(), ip), os.path.join(tgtDir, filename))
import sys
from ij import IJ

# Fiji Jython interpreter implements Python 2.5 which does not
# provide support for argparse.
title = sys.argv[ -6 ]
width = int( sys.argv[ -5 ] )
height = int( sys.argv[ -4 ] )
depth = int( sys.argv[ -3 ] )
type = sys.argv[ -2 ].replace( '_', ' ' )
tmp_image_path = sys.argv[ -1 ]

imp = IJ.newImage( title, type, width, height, depth )
IJ.save( imp, "%s" % tmp_image_path )
예제 #37
0
zscale = calib.pixelDepth
cred = Color(255, 0, 0)
cblue = Color(0, 0, 255)
xoffset = imp.getWidth()
yoffset = imp.getHeight()
ip = out.getStack().getProcessor(1)
for d in data:
   frame = int(d[1])
   x1 = int(round(float(d[2]) / xscale))
   y1 = int(round(float(d[3]) / yscale))
   z1 = int(round(float(d[4]) / xscale**2 * zscale))
   x2 = int(round(float(d[5]) / xscale))
   y2 = int(round(float(d[6]) / yscale))
   z2 = int(round(float(d[7]) / xscale**2 * zscale))
   direction = float(d[8])
   if direction <= 0:
      ip.setColor(Color(255, 100, 100))
   else:
      ip.setColor(Color(100, 100, 255))
   ip.setLineWidth(1)
   ip.drawLine(x1, y1, x2, y2)
   ip.drawLine(x1, yoffset+ z1, x2, yoffset+z2)
   ip.drawLine(xoffset+z1, y1, xoffset+z2, y2)
#out.updateAndDraw()
# plot 
#out.show()
outimp = ImagePlus(os.path.basename(filename)+'_Out.tif', ip)
#outimp.show()
IJ.save(outimp, newfilepath)
IJ.log("File saved:" + newfilepath)
from ij import IJ
from ij.io import DirectoryChooser
import os

inputFolder = DirectoryChooser('Set input directory.').getDirectory()
outputFolder = DirectoryChooser('Set output directory.').getDirectory()

for filename in os.listdir(inputFolder):
	image = IJ.openImage(inputFolder + '/' + filename);
	print image.getImageStackSize()
	if image.getStackSize() > 1:
		IJ.run(image, 'Make Composite', '')
		image.show()
		IJ.run(image, 'Stack to RGB','')
		image.show()
		image.close()
		newImage = IJ.getImage()
		newImage.show()
		IJ.save(newImage, outputFolder + '/' + filename);
		newImage.close()
	else:
		IJ.run(image, 'RGB Color','')
		IJ.save(image, outputFolder + '/' + filename);
		image.close()
예제 #39
0
    f.close()

    font = Font("SanSerif", Font.PLAIN, 12)
    overlay = ij.gui.Overlay()

    for (i,t) in enumerate(ts):
        roi = ij.gui.TextRoi(10, 5, "%s" % t, font)
        roi.setPosition(0,0,i+1) # order: (channel, slice, frame), 0 means all.
        overlay.add(roi)
        out.setOverlay(overlay)

# === Saving
IJ.log("Saving.")
#print type(dc_st), dc_st
if not os.path.isfile(of):
    IJ.save(out, of)
    #if dc_st is None:
    #    f=open(of, 'w')
    #    f.write("Only one frame\n")
    #    f.close()
    #else:
    #    IJ.save(out, of)
# === Save shifts (if needed)
if run_DC:
    f=open(of+'.shifts', "w")
    f.write("frame,x,y,z\n")
    for (i,s) in enumerate(dc_st[0]):
        f.write("%i, %f, %f, %f\n" % (i,s.x,s.y, s.z))
    f.close()
    
IJ.run("Quit")
예제 #40
0
# http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE)
# http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=HEAD

dir = "/usr/people/tmacrina/seungmount/research/Julimaps/datasets/AIBS_pilot_v1/0_raw/"

blocksize = 63
histogram_bins = 255
maximum_slope = 3
mask = "*None*"
composite = False
mask = None

# files = os.listdir(dir)
# files.sort()
# for file in files:
#      if file.endswith(".tif")
fn = os.path.join(dir, 'original.tif')
imp = IJ.openImage(fn)
output_fn = os.path.splitext(fn)[0] + "_CLAHE_8bit.tif"
imp = IJ.openImage(fn)
  
Flat.getFastInstance().run( imp, 
                        blocksize,
                        histogram_bins,
                        maximum_slope,
                        mask,
                        composite )
ImageConverter(imp).convertToGray8()

IJ.save(imp, output_fn)
	for cutIndex in cutIndices:
		IJ.log('Working on short time course around cut at frame ' + str(cutIndex))
		imStack = ij.ImageStack(512,512)
		for fileIndex in range(-1,21):
			filename = "%06d_mix.tif" % (cutIndex+fileIndex)
			#print filename
			imp = IJ.openImage(os.path.join(srcDir, folder, filename))
			ip = imp.getProcessor()
			#print(ip)
			imStack.addSlice(filename, ip)

		newFileName = "%s_E%sC%d.tif" % (date, embryoNumber, 1+cutIndices.index(cutIndex))
		newImp = ImagePlus(newFileName, imStack)
		newImp.show()
		IJ.log('Saving data to ' + os.path.join(outputDir, newFileName))
		IJ.save(newImp,  os.path.join(outputDir, newFileName))
		newImp.close()

	# Also save whole lot as an image stack...
	IJ.log('Working on complete time course - this might take a while...')
	images = [f for f in os.listdir(os.path.join(srcDir, folder))
	    if f.endswith('mix.tif')]

	imStack = ij.ImageStack(512,512)
	for image in images:
		imp = IJ.openImage(os.path.join(srcDir, folder, image))
		ip = imp.getProcessor()
		imStack.addSlice(image, ip)

	newFileName = "%s_E%s complete data.tif" % (date, embryoNumber)
	newImp = ImagePlus(newFileName, imStack)
import sys

from ij import IJ

# Fiji Jython interpreter implements Python 2.5 which does not
# provide support for argparse.
title = sys.argv[-6]
width = int(sys.argv[-5])
height = int(sys.argv[-4])
depth = int(sys.argv[-3])
type = sys.argv[-2].replace('_', ' ')
tmp_image_path = sys.argv[-1]

imp = IJ.newImage(title, type, width, height, depth)
IJ.save(imp, "%s" % tmp_image_path)
예제 #43
0
 def write(self, patch=None):
     """ Write the patch to a file.
     """
     if self.save:
         IJ.save(patch, os.path.join(self.datapath, patch.getTitle()+".tif"))
예제 #44
0
#!/bin/sh
''''exec "$(dirname "$0")"/../fiji --jython "$0" "$@" # (call again with fiji)'''

import sys
from ij import IJ, ImageJ

if len(sys.argv) < 2:
    print 'Need an output file'
    sys.exit(1)

window = ImageJ()
window.hide()
IJ.run("Capture Screen ")
IJ.save(sys.argv[1])
sys.exit(0)
    def crop_project_and_montage(self, roi=None):
        ## Check for settings
        ## Dont proceed if no roi is give and no channel is set
        if self.roi_channel is None and roi is None:
            print "Please set the channel to display the ROI"
            return None
            ## Dont proceed if no name is set. How will you name the files?
        if self.name == None:
            print "Please set the name of the stack"
            return None
        if self.outdir == None:
            print "Please set where to save the processed images"
            return None
        self.make_all_projections()
        ## grab the ROI if no ROI is passed to this function
        if roi is None:
            roi = self.stack_imps[self.roi_channel].getRoi()
            ## set images to use
        self.to_crop = {}
        for channel in self.channel_names:
            if channel in self.projections and channel in self.do_z:
                self.to_crop[channel] = self.projections[channel]
            else:
                self.select_slice_to_crop(channel)

                ## Crop down
        x = str(roi.getXBase())[:-2]  ## get updated size of Roi
        y = str(roi.getYBase())[:-2]
        self.processors_to_crop = {}
        self.cropped_imps = {}
        self.cropped_processors = {}
        for channel in self.channel_names:
            self.processors_to_crop[channel] = self.to_crop[channel].getProcessor()
            self.processors_to_crop[channel].setRoi(roi)
            self.cropped_processors[channel] = self.processors_to_crop[channel].crop()
            self.cropped_imps[channel] = ImagePlus("Cropped_%s" % channel, self.cropped_processors[channel])
            ## apply lut
            try:
                IJ.run(self.cropped_imps[channel], self.luts[channel], "")
            except:
                IJ.run(self.cropped_imps[channel], "Grays", "")
                ## min/max
            if channel not in self.contrasts:
                ## do quick autocontrast based on min/max
                self.contrasts[channel] = [
                    self.cropped_imps[channel].getProcessor().getMin(),
                    self.cropped_imps[channel].getProcessor().getMax(),
                ]
            try:
                c = self.contrasts[channel]
                self.cropped_imps[channel].getProcessor().setMinAndMax(c[0], c[1])
            except:
                "Print unable to do contrast"

                ## save 16 bit images
            directory = self.outdir
            file_name = self.name
            save_as = os.path.join(directory, "%s_%s_%s_%s.tif" % (file_name, channel, x, y))
            IJ.save(self.cropped_imps[channel], save_as)
            ## save RGBs
            IJ.run(self.cropped_imps[channel], "RGB Color", "")
            save_as = os.path.join(directory, "%s_%s_%s_%s_RGB.tif" % (file_name, channel, x, y))
            IJ.save(self.cropped_imps[channel], save_as)
        self.make_montage(xy="%sx%s" % (x, y))
예제 #46
0
	BS.rollingBallBackground(dapi_ip,
						*[a[1] for a in bkgd_sub])
	if SHOW_IMAGES:
		dapi.updateAndDraw()
	
	# IJ.setAutoThreshold("Otsu");
	# IJ.run("Convert to Mask");
	dapi_ip.autoThreshold()
	dapi.setProcessor(dapi_ip.convertToByteProcessor(False))
	dapi_ip = dapi.getProcessor()
	# IJ.run("Watershed");
	EDM().toWatershed(dapi_ip)
	dapi_ip.invert()
	
	# IJ.run("Analyze Particles...", "size=30-400 show=Masks");
	pa_options = particle_analyzer(dapi.getCalibration().pixelWidth)
	PA = ParticleAnalyzer(*[a[1] for a in pa_options])
	PA.analyze(dapi, dapi_ip)

	if SHOW_IMAGES:
		dapi.updateAndDraw()
	
	IJ.save(dapi, savename(stack))
	
	
	dapi.close()


rename_file(progress_name, done_name)
print 'done'
 	
from ij import IJ, ImagePlus, ImageStack, WindowManager

imp = WindowManager.getCurrentImage()

fileinfo = imp.getOriginalFileInfo()
filename = fileinfo.fileName
directory = fileinfo.directory

def extractFrames(imp, interval, offset, nFrames):
 """ Extract a stack containing a subset of frames from a stack """
 stack = imp.getImageStack()
 man = ImageStack(imp.width, imp.height)

 for i in range(0, nFrames):
   index = imp.getStackIndex(0, 1, i * interval + offset)
   man.addSlice(stack.getProcessor(index))
 return ImagePlus("Manual_" + filename, man)

mimp = extractFrames(imp, 45, 3, 4)

IJ.save(mimp, directory + '/Manual/Manual.tif')
예제 #48
0
def run_combine(filePath):
	basePath,baseName = os.path.split(filePath)
	imagePrefix = os.path.splitext(baseName)[0]
	resizeName = basePath + "/" + baseName + "_tiles/resized/"
	checkName = basePath + "/" + baseName + "_tiles/resized/" + imagePrefix + "_seq/"
	activeName = basePath + "/" + baseName + "_tiles"
	outputName = basePath + "/stitched/" + imagePrefix + "/"
	IJ.log("Combining " + filePath + "...")
	if (not os.path.isdir(outputName)):
		try:
			os.makedirs(outputName)
			if (not os.path.isdir(checkName)):
				raise ValueError("Stitched image directory not found")
			for dirpath, dirnames, files in os.walk(checkName):
				if not files:
					raise ValueError("Stitched image directory is empty")
			IJ.run("Bio-Formats Importer", "open=["+ activeName +"/tile_1.ome.tif] color_mode=Default view=Hyperstack stack_order=XYCZT");
			tileImage = WindowManager.getImage("tile_1.ome.tif")
			nChannels = tileImage.getNChannels()
			tileImage.close()
			options = "open=[" + checkName + "] starting=1 increment=1 scale=100 file=[] sort"
			IJ.run("Image Sequence...", options)
			theImage = IJ.getImage()
			for i in range(1,nChannels+1):
				params = "slices=" + str(i) + "-" + str(theImage.getNSlices()) + "-" + str(nChannels)
				IJ.run(theImage,"Make Substack...",params)
			theImage.close()
			wList = WindowManager.getIDList()
			for i in range(len(wList)):
				currImage = WindowManager.getImage(wList[i])
				currImage.setTitle("image"+str(i+1))
				IJ.save(currImage,outputName+imagePrefix+"_ch"+str(i+1)+".tif")
			if nChannels > 1 and not os.path.isfile(outputName+imagePrefix+"_composite.tif"):
				if nChannels == 2:
					params = ("c1=" + WindowManager.getImage(wList[0]).getTitle() + 
							" c4=" + WindowManager.getImage(wList[1]).getTitle() + " create ignore")
				elif nChannels == 3:
					params = ("c1=" + WindowManager.getImage(wList[1]).getTitle() +
							" c2=" + WindowManager.getImage(wList[0]).getTitle() +
							" c4=" + WindowManager.getImage(wList[2]).getTitle() + " create ignore")
				elif nChannels == 4:
					params = ("c1=" + WindowManager.getImage(wList[1]).getTitle() +
							" c2=" + WindowManager.getImage(wList[2]).getTitle() +
							" c3=" + WindowManager.getImage(wList[0]).getTitle() +
							" c4=" + WindowManager.getImage(wList[3]).getTitle() + " create ignore")
				elif nChannels == 5:
					params = ("c1=" + WindowManager.getImage(wList[1]).getTitle() +
							" c2=" + WindowManager.getImage(wList[2]).getTitle() +
							" c3=" + WindowManager.getImage(wList[0]).getTitle() +
							" c4=" + WindowManager.getImage(wList[4]).getTitle() + 
							" c7=" + WindowManager.getImage(wList[3]).getTitle() +
							" create ignore")
				else:
					IJ.log("No composite image created due to excess channels (>4)")
				IJ.run("Merge Channels...", params)
				compositeImage = IJ.getImage()
				IJ.save(compositeImage,outputName+imagePrefix+"_composite.tif")			
			wList = WindowManager.getIDList()
			for i in range(len(wList)):
				currImage = WindowManager.getImage(wList[i])						
				currImage.close()
			IJ.log("succeeded")
			returnVal = 0
		except:
			IJ.log("failed")
			os.rmdir(outputName)
			wList = WindowManager.getIDList()
			for i in range(len(wList)):
				currImage = WindowManager.getImage(wList[i])
				currImage.close()
			returnVal = 1
	else:
		IJ.log("skipped")
		returnVal = 2

	return returnVal