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 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!"
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()
示例#4
0
def main():

    Interpreter.batchMode = True

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

    print "Loading images..."
    filenames = enumerate_filenames(pattern)
    if len(filenames) == 0:
        return
    # This is the number of channels inferred from the filenames. The number
    # of channels in an individual image file will be determined below.
    num_channels = len(filenames)
    num_images = len(filenames[0])
    image = Opener().openImage(filenames[0][0])
    if image.getNDimensions() > 3:
        print "ERROR: Can't handle images with more than 3 dimensions."
    (width, height, channels, slices, frames) = image.getDimensions()
    # The third dimension could be any of these three, but the other two are
    # guaranteed to be equal to 1 since we know NDimensions is <= 3.
    image_channels = max((channels, slices, frames))
    image.close()
    if num_channels > 1 and image_channels > 1:
        print (
            "ERROR: Can only handle single-channel images with {channel} in"
            " the pattern, or multi-channel images without {channel}. The"
            " filename patterns imply %d channels and the images themselves"
            " have %d channels." % (num_channels, image_channels)
        )
        return
    if image_channels == 1:
        multi_channel = False
    else:
        print (
            "Detected multi-channel image files with %d channels"
            % image_channels
        )
        multi_channel = True
        num_channels = image_channels
        # Clone the filename list across all channels. We will handle reading
        # the individual image planes for each channel below.
        filenames = filenames * num_channels

    # 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)
            # For multi-channel images the channel determines the plane to read.
            args = [channel + 1] if multi_channel else []
            image = opener.openImage(filename, *args)
            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!"