Example #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()
Example #2
0
def run():

    # ensure no other windows are open and clear resultstable
    IJ.run("Close All")
    IJ.run("Clear Results", "")
    #Ask user for file to be converted
    srcDir = IJ.getFilePath("Select file to analyse")
    if not srcDir:
        return

    #open file
    IJ.open(srcDir)
    dstDir = os.path.dirname(srcDir)
    print("dstDir = " + dstDir)
    #open ROI manager, save ROI names as labels in measurements
    rm = RoiManager.getInstance()
    if not rm:
        rm = RoiManager()
    rm.runCommand("UseNames", "true")

    # set parameters to be measured
    IJ.run("Set Measurements...",
           "area mean integrated limit display redirect=None decimal=3")

    FOVlist = WindowManager.getIDList()
    chnls = IJ.getString(
        "Please enter which channels you would like to analyse. Example: 123 analyses channels 1, 2 and 3",
        '123')

    for FOV in FOVlist:
        imp = WindowManager.getImage(FOV)
        IJ.run(imp, "Arrange Channels...", "new=" + chnls)
        imp.close()
        imp2 = WindowManager.getCurrentImage()

        imageTitle = WindowManager.getImage(FOV).getTitle()
        newDir = imageTitle + ' ROIs'

        dirPath = os.path.join(dstDir, newDir)

        if not os.path.exists(dirPath):
            try:
                os.makedirs(dirPath)
            except OSError as e:
                if e.errno != errno.EEXIST:
                    raise
        # clear ROI list before analysis
        rm.runCommand(imp2, "Deselect")
        rm.runCommand(imp2, "Delete")

        TMdata, nFrames = runTrackMate(imp2)
        if TMdata:
            iterateCoords(TMdata, nFrames, dirPath, imp2)
        imp2.changes = 0
        imp2.close()
    #relabel()
    resultsDir = os.path.splitext(srcDir)[0] + ".csv"
    #while os.path.exists(resultsDir):
    #resultsDir = resultsDir+"_1"+".csv"
    IJ.saveAs("Results", resultsDir)
Example #3
0
    def opencsv(self, name):
        # Return if the csv object was not set.
        # if self.trackscsv == None: return None TODO: some errorchecking for false csv input.

        # Open the csv file and return it as ResultsTable object.
        try:
            csv = IJ.getFilePath("Choose the {} file".format(name))

            if csv.endswith(".csv"):
                rt = ResultsTable.open(csv)
            else:
                IJ.log("{} was not a .csv file".format(csv))
                raise ValueError

            columns = rt.getHeadings()
            table = [{column: rt.getValue(column, row)
                      for column in columns} for row in range(rt.size())]

            if rt.columnExists("Label"):
                for i in range(len(table)):
                    table[i]["Label"] = rt.getStringValue("Label", i)

            IJ.log("Read {} rows in {}.".format(len(table), name))
            return table

        except Exception as ex:
            IJ.log("Something in opencsv() went wrong: {}".format(
                type(ex).__name__, ex.args))
Example #4
0
def main():
    # ---------------------------------------------
    # Loads json file, reads tiff stack filenames
    # runs them through the selected STORM analyser
    # then attempts to save the collected spot info.
    # ---------------------------------------------
    settingsFile = ""
    settingsFile = IJ.getFilePath(settingsFile)
    if settingsFile == None:
        return
    try:
        jsonFileObj = open(settingsFile, 'r')
        jsonRead = json.load(jsonFileObj)
    except:
        IJ.error("No JSON could be loaded from " + settingsFile +
                 ". Are you certain this file is the correct format?")
        return
    directory = jsonRead['SaveDirectory']
    tiledStormOutputFile = directory + os.sep + "Tiled_STORM_spots.csv"
    # Run analysis:
    for item in jsonRead['Points']:
        imageFile = directory + os.sep + item['Filename']
        if macro == "ThunderSTORM":
            fileList = runThunderSTORM(imageFile)
        elif macro == "SomeOTHERnotimplementedSTORM":
            fileList = runThunderSTORM(imageFile)
        else:
            IJ.error(
                "The STORM method selected in the Tile_STORM macro is invalid. :("
            )
    # Apply offsets:
    applyOffsets(fileList, jsonRead, tiledStormOutputFile)

    return 0
Example #5
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()
 def __init__(self, fp = None):
     # Initialize the filepath to the grid file
     if fp is None:
         self.fp = IJ.getFilePath("Grid file")
     else:
         self.fp = fp
     # Get the directory, the name of the grid, and the name of the image
     self.initializeFilenames()
     self.loadSourceImage()
     self.initializeGridCoords()
def main():
    imp = IJ.getFilePath("Select DCIMG file")
    if not imp:
        return
    root, ext = os.path.splitext(imp)
    if ext.lower() != '.dcimg':
        cFrame = PlugInFrame('ERR DLG')
        MessageDialog(cFrame, 'ERROR', 'Expected extension .dcimg')
        return

    #Lets start
    fID = open(imp, 'rb')

    hdr_bytes = read_header_bytes(fID)
    hdr = parse_header_bytes(fID, hdr_bytes)

    metadataStr = beginMetadata()
    for key, value in hdr.iteritems():
        metadataStr += addMetadataEntry(key, str(value))

    metadataStr += endMetadata()
    metadataDlg = HTMLDialog("DCIMG metadata", metadataStr, 0)
    size = metadataDlg.getSize()
    if size.width < 300:
        size.width = 300
    if size.height < 500:
        size.height = 500
    metadataDlg.setSize(size)

    finfo = FileInfo()
    finfo.fileName = imp
    #finfo.width = hdr['xsize_req']
    finfo.width = hdr['xsize']
    finfo.height = hdr['ysize']
    finfo.nImages = hdr['nframes']
    finfo.offset = 232
    finfo.fileType = hdr['bitdepth'] / 8 - 1  #Ugh
    finfo.intelByteOrder = 1
    #finfo.gapBetweenImages = int(hdr['bytes_per_img']*(1-float(hdr['xsize_req'])/float(hdr['xsize'])))
    finfo.gapBetweenImages = 0
    finfo.fileFormat = 1
    finfo.samplesPerPixel = 1
    finfo.displayRanges = None
    finfo.lutSize = 0
    finfo.whiteIsZero = 0
    vs = VirtualStack()
    finfo.virtualStack = vs
    FileInfoVirtualStack(finfo)
Example #8
0
    def select_input(self, event):
        # get the info about the number of images in the file
        self.input_path = IJ.getFilePath("Choose a File")
        # if default naming is not changed use file name
        if self.textfield2.text == self.default_naming:
            self.file_core_name = path.basename(self.input_path).split('.czi')[0]
        else:
            self.file_core_name = self.textfield2.text
        # put that name in the text field
        self.panel.getComponents()[1].setText(self.file_core_name)

        reader = ImageReader()
        reader.setId(self.input_path)
        metadata_list = reader.getCoreMetadataList()
        # slide scanner makes a piramid of X for every ROI you draw
        # resolution is not updated in the metadata so it needs to be calculated manually
        number_of_images, self.num_of_piramids_list = get_data_structure(metadata_list)
        print("Number of images is " + str(number_of_images))
        # get the indexes of the maximum resolution images
        self.max_res_indexes = get_maxres_indexes(self.num_of_piramids_list)
        print("Number of pyramids are " + str(self.num_of_piramids_list))
        # set names of subimages in the list, waiting to compare to current outputs
        self.possible_slices = [self.file_core_name + "_slice-" + str(n)
                                for n in range(number_of_images)]

        self.binFactor_list, self.binStep_list = get_binning_factor(self.max_res_indexes,
                                                self.num_of_piramids_list, metadata_list)
        print("Binning factors are " + str(self.binFactor_list))
        print("Binning steps are " + str(self.binStep_list))

        # create output directory if it doesn't exist
        # get the animal id
        animal_id = self.file_core_name.split('_')[0]
        self.output_path = path.join(path.dirname(path.dirname(self.input_path)),
                                     "Processed_data", animal_id, "ROIs")
        if path.isdir(self.output_path):
            print("Output path was already created")
        else:
            makedirs(self.output_path)
            print("Output path created")

        # update_lists depending on whether something has been processed already
        self.update_list()
Example #9
0
def opencsv():
    """Simply imports .csv file in ImageJ.

    Ask the user for the location of a .csv file.

    Returns:
        A ResultsTable object from the input file.
    """

    csv = IJ.getFilePath("Choose a .csv file")

    # Open the csv file and return it as ResultsTable object.
    try:
        if csv.endswith(".csv"):
            res = ResultsTable.open(csv)
            return res
        else:
            raise TypeError()
    except TypeError:
        IJ.log("The chosen file was not a .csv file.")
    except Exception as ex:
        IJ.log("Something in opencsv() went wrong: {}".format(type(ex).__name__, ex.args))
Example #10
0
	(basename)_R(fixed)_GR(.*)_B(block number)_L(location number)\.lsm

with GR (group repetition) number being left to be variable, 
and then these files are merged in the orfer of the GR value. 

request from Katharina Sonnen
'''

import os
import re
from ij import IJ, ImagePlus
from ij.io import Opener
from ij.plugin import Concatenator
from jarray import array

srcpath = IJ.getFilePath('Choose the first file')
filename = os.path.basename(srcpath)
srcDir = os.path.dirname(srcpath)

#chosefile = '20130711_R1_GR001_B1_L2.lsm'
pattern = re.compile('(.*)_R(.*)_GR(.*)_B(.*)_L(.*)\.lsm')
res = re.search(pattern, filename)

basename = res.group(1)
repetition = res.group(2)
grouprepetition = res.group(3)
block = res.group(4)
location = res.group(5)

GRlist = []
for root, directories, filenames in os.walk(srcDir):
Example #11
0
# VIB - Vlaams Instituut voor Biotechnologie
# October 2018

from ij import IJ
from ij.plugin.frame import RoiManager
import sys

rm = RoiManager.getInstance()
if rm == None:
    rm = RoiManager()

rois = rm.getRoisAsArray()
if rois == None or len(rois) == 0:
    sys.exit('The ROI manager has no ROIs')

filename = IJ.getFilePath(
    'Specify the output file for the ROIs in JSON format (e.g. myrois.json)')
if filename == None:
    sys.exit('ROI saving canceled by the user.')

# Save the ROIs as JSON arrays
IJ.log("Saving {} ROIs to {}".format(len(rois), filename))
with open(filename, 'w') as f:
    f.write('[\n')
    for i, roi in enumerate(rois):
        polygon = roi.getPolygon()
        f.write('[\n')
        for j in range(polygon.npoints):
            f.write('[{}, {}]'.format(polygon.xpoints[j], polygon.ypoints[j]))
            if j < polygon.npoints - 1:
                f.write(',')
            f.write('\n')
Example #12
0
from ij.gui import HTMLDialog

import struct
import os

def addMetadataEntry(name, val):
  return "<tr><td style='padding:0 25px 0 0px;'><b>" + name + "</b></td><td>" + val + "</td></tr>"

def beginMetadata():
  return "<table border=0 cellspacing=0>"

def endMetadata():
  return "</table>"


imp = IJ.getFilePath("Select HIS file")
if not imp:
  exit(-1)
root, ext = os.path.splitext(imp)
if ext.lower() != '.his':
  cFrame = PlugInFrame('ERR DLG')
  MessageDialog(cFrame, 'ERROR', 'Expected extension .his')
  exit(-1)

fID = open(imp, 'rb')
fID.seek(2)
offset = struct.unpack('<h', fID.read(2))[0]
fID.seek(14)
frames = struct.unpack('<I', fID.read(4))[0]
fID.seek(2)
commentBytes = struct.unpack('<h', fID.read(2))[0]
Example #13
0
def getPath(text):
	path = IJ.getFilePath(text)
	IJ.log('File selected: ' + path)
	return path
from os import path, makedirs
import sys

sys.path.append(path.abspath(path.dirname(__file__)))
from functions.czi_structure import get_data_structure, get_binning_factor, open_czi_series, \
    get_maxres_indexes
from functions.image_manipulation import extractChannel

piramid_to_open = 1
channel_to_save = 3
final_resolution = 5

# Main
if __name__ in ['__builtin__', '__main__']:
    # get the file
    input_path = IJ.getFilePath("Choose a .czi file")
    reader = ImageReader()
    reader.setId(input_path)
    metadata_list = reader.getCoreMetadataList()
    # slide scanner makes a piramid of X for every ROI you draw
    # resolution is not updated in the metadata so it needs to be calculated manually
    number_of_images, num_of_piramids_list = get_data_structure(metadata_list)
    IJ.log("Number of images is " + str(number_of_images))
    # set names of subimages in the list, waiting to compare to current outputs
    file_core_name = path.basename(input_path).split('.czi')[0]
    # get the indexes of the maximum resolution images
    max_res_indexes = get_maxres_indexes(num_of_piramids_list)
    IJ.log("Number of pyramids are " + str(num_of_piramids_list))
    # set names of subimages in the list, waiting to compare to current outputs
    possible_slices = [
        file_core_name + "_slice-" + str(n) for n in range(number_of_images)