Beispiel #1
0
def findSeptum(root, show, pos, n = 4):
	from ij import IJ
	corrImg = IJ.openImage(root + "/%s_SegAnalysis/%s/CorrelationImage.tif"% (bf_prefix, pos))
	IJ.run(corrImg, "8-bit", "");
	#estimate_width extend_line
	# these parameters can be added also
	cmd = "line_width=10 high_contrast=250 low_contrast=50  show_junction_points show_ids add_to_manager make_binary method_for_overlap_resolution=NONE sigma=3 lower_threshold=0 upper_threshold=1.36 minimum_line_length=30 maximum=60"

	if show:
		cmd += " displayresults"
	IJ.run(corrImg, "Ridge Detection", cmd);
		
	binarylineImg = IJ.getImage()
	IJ.run(binarylineImg, "Invert", "");
	binaryImg = IJ.openImage(root + "/%s_SegAnalysis/%s/BinaryImage.tif" % (bf_prefix, pos))
	binaryImg.show()
	IJ.run("Add Image...", "x=0 y=0 opacity=100 zero");
	binaryImg.hide()
	binarylineImg.hide()
	imp2 = binaryImg.flatten();
	IJ.run(imp2, "8-bit", "");
	for i in range(n):
		IJ.run(imp2, "Erode", "");
	for j in range(n):
		IJ.run(imp2, "Dilate", "");
	IJ.saveAsTiff(imp2, d.getPath() + "/%s_SegAnalysis/%s/BinaryImage_with_sep.tif" % (bf_prefix, pos));
Beispiel #2
0
def findSeptum(root, show, pos, n=4):
    from ij import IJ
    corrImg = IJ.openImage(root + "/%s_SegAnalysis/%s/CorrelationImage.tif" %
                           (bf_prefix, pos))
    IJ.run(corrImg, "8-bit", "")
    #estimate_width extend_line
    # these parameters can be added also
    cmd = "line_width=10 high_contrast=250 low_contrast=50  show_junction_points show_ids add_to_manager make_binary method_for_overlap_resolution=NONE sigma=3 lower_threshold=0 upper_threshold=1.36 minimum_line_length=30 maximum=60"

    if show:
        cmd += " displayresults"
    IJ.run(corrImg, "Ridge Detection", cmd)

    binarylineImg = IJ.getImage()
    IJ.run(binarylineImg, "Invert", "")
    binaryImg = IJ.openImage(root + "/%s_SegAnalysis/%s/BinaryImage.tif" %
                             (bf_prefix, pos))
    binaryImg.show()
    IJ.run("Add Image...", "x=0 y=0 opacity=100 zero")
    binaryImg.hide()
    binarylineImg.hide()
    imp2 = binaryImg.flatten()
    IJ.run(imp2, "8-bit", "")
    for i in range(n):
        IJ.run(imp2, "Erode", "")
    for j in range(n):
        IJ.run(imp2, "Dilate", "")
    IJ.saveAsTiff(
        imp2,
        d.getPath() + "/%s_SegAnalysis/%s/BinaryImage_with_sep.tif" %
        (bf_prefix, pos))
def run():
    global ext, exp, saturated, outputFolder, srcFile

    IJ1.batchMode = True

    srcDir = srcFile
    images, channels = createFileAndChannelsDictionaries(srcDir, exp)
    outDir = os.path.join(srcDir, outputFolder)
    if not os.path.exists(outDir):
        os.makedirs(outDir)

    numberOfImages = len(images)
    counter = 1
    IJ.log("\\Clear")
    IJ.log("Convert images from Opera to Hyperstacks...")
    for image, filename in images.iteritems():
        IJ.log("\\Update1:Processing image " + str(counter) + "/" +
               str(numberOfImages))
        nrOfChannels = channels[image]
        success = openAsHyperstack(filename, image, nrOfChannels)
        if (success):
            adjustDisplay(nrOfChannels, saturated)
            IJ.saveAsTiff(IJ.getImage(), os.path.join(outDir, image + ".tiff"))
        IJ.getImage().close()
        counter = counter + 1
    IJ.log("Finished !")
    IJ1.batchMode = False
Beispiel #4
0
def run():
    helpText = "This program will batch convert any tif image to 8-bit greyscale, " + \
               "and empty calibration infomation.\n\n" + \
               ">> Press OK to Select a directory of TIFF images."
    MessageDialog(IJ.getInstance(), "Empty Calibration Guide", helpText)

    srcDir = DirectoryChooser("Chose Source Dir").getDirectory()
    if srcDir is None:
        IJ.log("Choose Dir Canceled!")
        return

    for root, directories, filenames in os.walk(srcDir):
        for filename in filenames:
            if not filename.endswith(".tif"):
                continue
            imgPath = os.path.join(root, filename)
            outPath = os.path.join(root, "decal-" + filename)

            imp = IJ.openImage(imgPath)
            imp.setCalibration(Calibration())
            ic = ImageConverter(imp)
            ic.convertToGray8()
            IJ.saveAsTiff(imp, outPath)
            print "removed calibration and saved to ", os.path.basename(
                outPath)
def subtract_back(file):
    """
    ImageJのSubtract backgroundを実行し, 
    開いた画像のDirectory内にSubtracted_imagesを作成し,
    背景画像を減算した画像を保存する。
    """
    import os
    from ij import IJ

    imp = IJ.openImage(file)

    img_dir = imp.getOriginalFileInfo().directory

    save_dir = os.path.join(img_dir, "Subtracted_images")

    if not os.path.exists(save_dir):  # もしsave_dirが存在しなければそのディレクトリを作成
        os.makedirs(save_dir)

    img_file = imp.getOriginalFileInfo().fileName
    file_name, ext = os.path.splitext(img_file)

    save_path = os.path.join(save_dir, file_name + "-subtracted.tif")

    IJ.run(imp, "Subtract Background...", "rolling=30")  # Radius 30
    IJ.saveAsTiff(imp, save_path)
    imp.close()
Beispiel #6
0
def save_tif():
    # Get the active image, its title, and the directory where it lies
    imp = IJ.getImage()
    imp_title = imp.getTitle()
    path = IJ.getDirectory("image")
    IJ.log("Active image source: {}{}".format(path, imp_title))

    for i in range(0, len(channel_names)):
        current_name = channel_names[i]
        if "C={}".format(i) in imp_title:
            channel_name = current_name
            found_name = True
        else:
            pass

    # In the imp title string, find the index where .nd2 first appears. Everything
    # up to this point is kept for use in saving the file.
    end_of_title = imp_title.find('.nd2')
    tif_title = "{}_{}".format(imp_title[:end_of_title], channel_name)
    # Save the image
    save_path = "{}{}".format(path, tif_title)
    IJ.saveAsTiff(imp, save_path)
    IJ.log("Tif saved at {}.tif".format(save_path))
    # Close the image
    imp.close()
Beispiel #7
0
 def process(self,imp):
     # skip automerged images
     if "Merging" in imp.getTitle():
         return
     
     title = imp.getTitle() + "_edf"
     print "EdfWorker.process: " + title
     output = edfProcess(imp, self.params)
     IJ.saveAsTiff(output, os.path.join(self.exportDir,title))
Beispiel #8
0
def save_separate_tif(f):
    if f is not None:

        save_dir, pre_save_path = get_presave_path(f, dir_name="Separate")

        imp = IJ.openImage(f)

        for i in range(imp.getNFrames()):
            imp.setT(i + 1)
            new_imp = Duplicator().crop(imp)
            IJ.saveAsTiff(new_imp, pre_save_path + "_{}.tif".format(i + 1))
Beispiel #9
0
def run():
    srcDir = DirectoryChooser("Chose Source Dir").getDirectory()
    if srcDir is None:
        IJ.log("Choose Dir Canceled!")
        return

    outDir = DirectoryChooser("Chose >Output< Dir").getDirectory()
    if outDir is None:
        IJ.log("Output to same dir as source.")
        ourtDir = srcDir

    refImageId = getRefIdDialog()
    if refImageId is None:
        IJ.log("Select Reference Image Canceled!")
        return

    for root, directories, filenames in os.walk(srcDir):
        for filename in filenames:
            # Skip non-ND2 files
            if not filename.endswith(".nd2"):
                continue
            inpath = os.path.join(root, filename)

            # outfn = "reg_" + os.path.splitext(filename)[0] + ".tif"
            # outpath = os.path.join(outDir, outfn)
            # if os.path.exists(outpath):
            #     print "Skipped, already exists: ", outfn
            #     continue

            IJ.log("Registering\n" + filename)
            imp = regBf(fn=inpath, refId=refImageId)
            if imp is None:
                IJ.log("Skipped, wrong with registration:\n" + filename)
                continue
            else:
                # fs = FileSaver(imp)
                # fs.saveAsTiffStack(outpath)
                # IJ.saveAsTiff(imp, outpath)
                # print "Registered and saved to ", outfn
                splittedimps = ChannelSplitter.split(imp)
                for i, simp in enumerate(splittedimps):
                    outfn = "reg_" + os.path.splitext(
                        filename)[0] + "_C_" + str(i) + ".tif"
                    outpath = os.path.join(outDir, outfn)
                    if os.path.exists(outpath):
                        IJ.log("Skipped saving, file already exists:\n" +
                               outfn)
                        continue
                    IJ.saveAsTiff(simp, outpath)
                    IJ.log("Registered and saved to\n" + outfn)

    IJ.log("done!")
Beispiel #10
0
    def save_registration_image(self):
        reg_text_info = self.textfield4.text.split(',')
        reg_pir_num = int(reg_text_info[0])
        reg_channel = int(reg_text_info[1])
        self.reg_final_res = float(reg_text_info[2])

        self.forreg_output_path = path.join(self.output_path, "000_Slices_for_ARA_registration")

        if path.isdir(self.forreg_output_path):
            print("Output path for low resolution slices was already created")
        else:
            mkdir(self.forreg_output_path)
            print("Output path for low resolution slices created")

        # check that this slice has not been saved before
        reg_slice_name = path.join(self.forreg_output_path, self.name)
        if path.isfile(reg_slice_name + '.tif'):
            print("Registration slice already exists")
        else:
            # save otherwise
            print("Saving for registration channel {} at {} um/px".format(reg_channel, self.reg_final_res))
            # get the Xth resolution image and Xth channel for saving it for registration
            series_num = self.high_res_index + reg_pir_num
            self.raw_reg_image = open_czi_series(self.input_path, series_num)  # read the image
            self.regist_image = extractChannel(self.raw_reg_image, reg_channel, 1)
            ContrastEnhancer().stretchHistogram(self.regist_image, 0.35)
            # self.regist_image.show()

            self.regist_image.getProcessor().resetRoi()
            # reset min and max automatically
            # convert to 8-bit (which also applies the contrast)
            # ImageConverter(self.regist_image).convertToGray8()
            # convert to Xum/px so that it can be aligned to ARA
            reg_im_bin_factor = self.binStep ** reg_pir_num
            regres_resolution = reg_im_bin_factor * self.res_xy_size
            rescale_factor = regres_resolution / self.reg_final_res
            new_width = int(rescale_factor * self.regist_image.getWidth())
            # self.lr_dapi_reg.getProcessor().scale(rescale_factor, rescale_factor)
            ip = self.regist_image.getProcessor().resize(new_width)
            self.regist_image.setProcessor(ip)
            # Add the information to the metadata
            self.regist_image.getCalibration().pixelWidth = self.reg_final_res
            self.regist_image.getCalibration().pixelHeight = self.reg_final_res
            self.regist_image.getCalibration().pixelDepth = 1
            self.regist_image.getCalibration().setXUnit("micrometer")
            self.regist_image.getCalibration().setYUnit("micrometer")
            self.regist_image.getCalibration().setZUnit("micrometer")
            # self.lr_dapi_reg.getProcessor().resetRoi()
            IJ.saveAsTiff(self.regist_image, reg_slice_name)
            self.regist_image.close()
            self.regist_image.flush()
            print("Slice for registration saved")
def make_MAX(cString):
    # max projection
    print "Running MAX projection..."
    IJ.run("Z Project...", "projection=[Max Intensity] all")

    # renaming
    imp = IJ.getImage()  # gets the resulting image
    imp.setTitle("MAX_C" + cString + "-" + scanName + "_raw")
    imp = IJ.getImage()  # gets the resulting image
    windowName = imp.getTitle()  # gets title

    print "Saving MAX..."
    IJ.saveAsTiff(imp, os.path.join(scanFolder, windowName))
def run():
  srcDir = DirectoryChooser("Chose Source Dir").getDirectory()
  if srcDir is None:
      IJ.log("Choose Dir Canceled!")
      return

  outDir = DirectoryChooser("Chose >Output< Dir").getDirectory()
  if outDir is None:
      IJ.log("Output to same dir as source.")
      ourtDir = srcDir

  refImageId = getRefIdDialog()
  if refImageId is None:
      IJ.log("Select Reference Image Canceled!")
      return

  for root, directories, filenames in os.walk(srcDir):
      for filename in filenames:
          # Skip non-ND2 files
          if not filename.endswith(".nd2"):
              continue
          inpath = os.path.join(root, filename)

          # outfn = "reg_" + os.path.splitext(filename)[0] + ".tif"
          # outpath = os.path.join(outDir, outfn)
          # if os.path.exists(outpath):
          #     print "Skipped, already exists: ", outfn
          #     continue

          IJ.log("Registering\n" + filename)
          imp = regBf(fn=inpath, refId=refImageId)
          if imp is None:
              IJ.log("Skipped, wrong with registration:\n" + filename)
              continue
          else:
              # fs = FileSaver(imp)
              # fs.saveAsTiffStack(outpath)
              # IJ.saveAsTiff(imp, outpath)
              # print "Registered and saved to ", outfn
              splittedimps = ChannelSplitter.split(imp)
              for i, simp in enumerate(splittedimps):
                  outfn = "reg_" + os.path.splitext(filename)[0] + "_C_" + str(i) + ".tif"
                  outpath = os.path.join(outDir, outfn)
                  if os.path.exists(outpath):
                      IJ.log("Skipped saving, file already exists:\n" + outfn)
                      continue
                  IJ.saveAsTiff(simp, outpath)
                  IJ.log("Registered and saved to\n" + outfn)

  IJ.log("done!")
Beispiel #13
0
def buildStack(saveDir, stacklist):
	stacks = {}
	for f, s in stacklist.iteritems():
		for name in s:
			curSlice = IJ.openImage(os.path.join(saveDir, name))
			if f not in stacks:
				stack = curSlice.createEmptyStack()
				stack.addSlice(name, curSlice.getProcessor())
				stacks[f] = stack
			else:
				stacks[f].addSlice(name, curSlice.getProcessor())
			call(["/usr/local/bin/rmtrash",os.path.join(saveDir,name)])

	for f in stacks:
		IJ.saveAsTiff(ImagePlus(f, stacks[f]),os.path.join(saveDir,f))
Beispiel #14
0
def save_rois(imp, corners_cleaned, L, OUTDIR):
    # parse title
    tit = imp.getTitle()
    core = '_'.join(tit.split('_')[0:-1])
    ending = tit.split('_')[-1]
    # save rois
    roi_ID = 1
    for [x, y] in corners_cleaned:
        rect = Roi(x, y, L, L)
        imp.setRoi(rect)
        imp2 = imp.crop()
        # save
        IJ.saveAsTiff(
            imp2, path.join(OUTDIR,
                            core + "_ROI-" + str(roi_ID) + "_" + ending))
        roi_ID += 1
Beispiel #15
0
def processImage(imp, threshold, min_size, max_size, remove_last_slice):
    title = imp.title
    image_dir = IJ.getDirectory("image")
    channel_dir = image_dir + "channel_" + str(channel) + "/"
    marker_dir = image_dir + "markers/"
    mapped_images_dir = image_dir + "mapped_images/"
    makeDir(channel_dir, marker_dir, mapped_images_dir)

    IJ.run("Split Channels")
    main_channel_image = "C" + str(channel) + "-" + title
    IJ.selectWindow(main_channel_image)
    imp = IJ.getImage()
    if os.path.exists(channel_dir + main_channel_image):
        os.remove(channel_dir + main_channel_image)
    images_list = WindowManager.getImageTitles()

    for image in images_list:
        if image != main_channel_image:
            IJ.selectWindow(image)
            IJ.run("Close")
    if remove_last_slice:
        imp.setSlice(imp.NSlices)
        IJ.run(imp, "Delete Slice", "")
        imp.setSlice(1)
    IJ.saveAsTiff(imp, channel_dir + main_channel_image)
    #time.sleep(5)
    IJ.run(
        imp, "3D Objects Counter",
        "threshold=" + str(threshold) + " slice=1 min.=" + str(min_size) +
        " max.=" + str(max_size) + " centres_of_masses statistics")
    #title="001-002.tiff"
    #time.sleep(10)
    image = title.split(".")[0]
    restults_window = image + ".csv"

    IJ.saveAs("Results", marker_dir + restults_window)

    IJ.selectWindow(restults_window)
    IJ.run("Close")

    imp.close()
    imp = IJ.getImage()
    title = imp.title
    if os.path.exists(mapped_images_dir + title):
        os.remove(mapped_images_dir + title)
    IJ.saveAsTiff(imp, mapped_images_dir + title)
    imp.close()
Beispiel #16
0
def draw_centers(data):
    pathname = data[1]
    filename = data[2]
    platename = data[3]

    print data[4]
    nx = int(data[4])
    ny = int(data[5])
    nx_com = int(data[6])
    ny_com = int(data[7])
    ax = int(data[8])
    ay = int(data[9])
    
    orientation = 2*math.pi * float(data[10]) / 360.0
    line_dy = int(round(math.atan(orientation) * LINE_DX))
    ax2 = ax - LINE_DX
    ay2 = ay - line_dy

    orientation_avg = 2*math.pi * float(data[11]) / 360.0
    line_dy = int(round(math.atan(orientation_avg) * LINE_DX))
    ax3 = ax - LINE_DX
    ay3 = ay - line_dy

    imp = IJ.openImage(os.path.join(pathname,filename))

    roi_nucleus = PointRoi(nx,ny)
    roi_nucleus.setDefaultMarkerSize("Large")
    roi_nucleus.setStrokeColor(Color.CYAN)
    roi_nucleus_com = PointRoi(nx_com,ny_com)
    roi_nucleus_com.setDefaultMarkerSize("Large")
    roi_nucleus_com.setStrokeColor(Color.GREEN)
    roi_anchor = PointRoi(ax,ay)
    roi_anchor.setDefaultMarkerSize("Large")
 
    imp.getProcessor().drawRoi(roi_nucleus)
    imp.getProcessor().drawRoi(roi_nucleus_com)
    imp.getProcessor().drawRoi(roi_anchor)

    imp.setColor(Color.RED)
    imp.getProcessor().drawLine(ax,ay,ax2,ay2)
    imp.setColor(Color.WHITE)
    imp.getProcessor().drawLine(ax,ay,ax3,ay3)


    IJ.saveAsTiff(imp,os.path.join(pathname,filename))
def pairwise_stitching(tiff_1, tiff_2, temp_dir):
	IJ.open(tiff_1)
	tiff_1_title = os.path.basename(tiff_1)
	IJ.open(tiff_2)
	tiff_2_title = os.path.basename(tiff_2)
	new_fused_image = "" + tiff_1_title.split("_")[0] + "-" + tiff_2_title.split("_")[0] + "_.tiff"

	IJ.run("Pairwise stitching", "first_image=" + tiff_1_title +  " second_image=" + tiff_2_title + " fusion_method=[Linear Blending] fused_image=" + new_fused_image + " check_peaks=1 compute_overlap x=0.0000 y=0.0000 z=0.0000 registration_channel_image_1=[Average all channels] registration_channel_image_2=[Average all channels]")
	IJ.selectWindow(tiff_1_title)
	IJ.run("Close")
	os.remove(tiff_1)
	IJ.selectWindow(tiff_2_title)
	IJ.run("Close")
	os.remove(tiff_2)
	IJ.selectWindow(new_fused_image)
	imp = IJ.getImage()
	IJ.saveAsTiff(imp, os.path.join(temp_dir, new_fused_image))
	imp.close()
def trans_to_tif(file_list, overwrite = False):
    if file_list is not None:
        for path in file_list:
            opts = ImporterOptions()
            opts.setId(path)
            opts.setVirtual(True)
            opts.setColorMode(ImporterOptions.COLOR_MODE_COMPOSITE)
            opts.setOpenAllSeries(True)

            process = ImportProcess(opts)

            try:
                process.execute()
            except:
                pass
            else:
                process.execute()

            try:
                imps = ImagePlusReader(process).openImagePlus()
            except:
                IJ.log(path + "\n" + "This file was not properly processed")
                pass

            else:
                dir_name = os.path.dirname(path)
                file_name = os.path.basename(os.path.splitext(path)[0])
                save_dir = os.path.join(dir_name, file_name)
                if not os.path.exists(save_dir):
                    os.makedirs(save_dir)

                imps = ImagePlusReader(process).openImagePlus()
                for i, imp in enumerate(imps):
                    save_path = os.path.join(save_dir, file_name + "_pos{}.tif".format(i + 1))

                    if not os.path.exists(save_path):
                        IJ.saveAsTiff(imp, save_path)
                        IJ.freeMemory()
                    else:
                        if overwrite:
                            IJ.saveAsTiff(imp, save_path)
                            IJ.freeMemory()
                        else:
                            pass
Beispiel #19
0
def processImage():
	imp = IJ.getImage()
	image_name = imp.title
	image_dir = IJ.getDirectory("image")
	IJ.run(imp, "Measure", "")
	marker_dir = os.path.join(image_dir, "markers" + os.path.sep)
	processed_marker_dir = os.path.join(image_dir, "processed_markers" + os.path.sep)
	makeDir(marker_dir, processed_marker_dir)
	csv_file = saveResults(imp, marker_dir)
	imp.deleteRoi()

	tiff_save_name = os.path.join(processed_marker_dir, image_name)
	IJ.saveAsTiff(imp, tiff_save_name)
	remove_duplicate_counter(csv_file, processed_marker_dir)
#	file_dir = os.path.dirname(os.path.abspath(__file__))
	IJ.run(imp, "setRoi ", "");
	IJ.run("Save")
	imp.close()
	return image_dir
Beispiel #20
0
def batchProcess(parentpath, theExp):
    resarray = []
    #for ind in range(8):
    for ind in theExp:
        cellNo = ind + 1
        tracks, cellarea, postcounts, postcounts2, precounts, imp, reallength, secondFrameVirusCounts = main(parentpath, cellNo)
        
        scaledCellArea = cellarea * reallength * reallength 
        #density = len(tracks) / float(scaledCellArea)
        density = secondFrameVirusCounts / float(scaledCellArea)
        #ripoffRatio = postcounts / float(len(tracks))
                if postcounts > 0:
                        ripoffRatio = postcounts / float(secondFrameVirusCounts)
                else: 
                    ripoffRatio = float('NaN')
                if postcounts2 > 0:
                            ripoffRatio2 = postcounts2 / float(secondFrameVirusCounts)
                else:
                    ripoffRatio2 = float('NaN')
                print "Total number of detected dots: ", len(tracks)
                print "Second Frame Counts", secondFrameVirusCounts
                print "cell area [um2]", scaledCellArea
                print "Dot Density:[count / um2]:" , density
                print "Number of Ripped off (", preDrug_Starts, " to ", preDrug_Ends, " frame):", precounts    
                print "Number of Ripped off (", postDrug_Starts, " to ", postDrug_Ends, " frame):", postcounts
                print "Number of Ripped off (", postDrug2_Starts, " to ", postDrug2_Ends, " frame):", postcounts2

                #resarray.append([cellNo, scaledCellArea, len(tracks), density, precounts, postcounts, ripoffRatio])
                resarray.append([cellNo, scaledCellArea, secondFrameVirusCounts, density, precounts, postcounts, postcounts2, ripoffRatio])        
                outname = "cell" + str(cellNo) + '_dots.tif'
                savefilepath = os.path.join(parentpath, outname)    
                IJ.saveAsTiff(imp, savefilepath)
                
                # exporting results
                outcsvpath = os.path.join(parentpath, 'results.csv')
                f = open(outcsvpath, 'wb')
                writer = csv.writer(f)
                writer.writerow(['CellID', 'Area[um2]', 'Dots Total', 'Density', 'RipOff counts2_4', 'RipOff counts5_7', 'RipOff counts8_10', 'RipOff Ratio'])
                for arow in resarray:
                        #arow = [cellNo, cellarea, len(tracks), postcounts, precounts]
                        writer.writerow(arow)
                f.close()
def split_stack():

    imp = IJ.getImage()
    path = IJ.getDirectory("image")

    IJ.run("Stack to Images", "")
    # close original image and leave split stacks open
    imp.close()

    n_images = WindowManager.getImageCount()

    for i in range(0, n_images):
        frame_imp = IJ.getImage()
        imp_title = frame_imp.getTitle()

        save_path = "{}{}".format(path, imp_title)
        IJ.saveAsTiff(frame_imp, save_path)
        IJ.log("{} saved at {}".format(frame_imp, save_path))

        frame_imp.close()
Beispiel #22
0
 def save_summary(self, e):
     IJ.selectWindow(self.name)
     IJ.run("Flatten")
     imp = IJ.getImage()
     # downsample
     # scale ENLARGING or SHRINKING the canvas dimensions
     scale_factor = .2
     new_width = str(int(imp.getWidth() * scale_factor))
     new_height = str(int(imp.getHeight() * scale_factor))
     IJ.selectWindow(self.name + "-1")
     str_to_scale = "x=" + str(scale_factor) + " y=" + str(
         scale_factor
     ) + " width=" + new_width + " height=" + new_height + " interpolation=Bilinear average create"
     IJ.run("Scale...", str_to_scale)
     # save
     imp2 = IJ.getImage()
     #IJ.saveAs("Tiff", path.join(OUTDIR, self.name + "_summaryOfROIs"))
     IJ.saveAsTiff(
         imp2, path.join(self.output_path,
                         self.name + "_summaryOfROIs.tif"))
     print "summary image saved"
Beispiel #23
0
def make_MAX(singleplane):  # singleplane is Boolean True/False
    image_titles = [
        WindowManager.getImage(id).getTitle()
        for id in WindowManager.getIDList()
    ]

    for i in image_titles:
        imp = WindowManager.getImage(i)
        if singleplane == False:  # If the data is not single z-plane, runs max projection
            IJ.run(imp, "Z Project...", "projection=[Max Intensity] all")
            imp = WindowManager.getImage("MAX_" + i)
            windowName = imp.getTitle()
            IJ.saveAsTiff(imp, os.path.join(saveFolder,
                                            windowName))  #saves to saveFolder
            imp = WindowManager.getImage(i)  # Gets the original hyperstack
            imp.changes = False  # Answers "no" to the dialog asking if you want to save any changes
            imp.close()  # Closes the hyperstack

        # If the data is single plane, it skipes projection and moves to LUT setting
        elif singleplane == True:
            windowName = imp.getTitle()
            print "Single plane data detected. Skipping Z-projection for ", windowName
Beispiel #24
0
def run():
    helpText = "This program will batch convert any tif image to 8-bit greyscale, " + \
               "and empty calibration infomation.\n\n" + \
               ">> Press OK to Select a directory of TIFF images."
    MessageDialog(IJ.getInstance(),"Empty Calibration Guide", helpText)

    srcDir = DirectoryChooser("Chose Source Dir").getDirectory()
    if srcDir is None:
        IJ.log("Choose Dir Canceled!")
        return

    for root, directories, filenames in os.walk(srcDir):
        for filename in filenames:
            if not filename.endswith(".tif"):
                continue
            imgPath = os.path.join(root, filename)
            outPath = os.path.join(root, "decal-" + filename)

            imp = IJ.openImage(imgPath)
            imp.setCalibration(Calibration())
            ic = ImageConverter(imp)
            ic.convertToGray8()
            IJ.saveAsTiff(imp, outPath)
            print "removed calibration and saved to ", os.path.basename(outPath)
Beispiel #25
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..."

    # Use BioFormats reader directly to determine dataset dimensions without
    # reading every single image. The series count (num_images) is the one value
    # we can't easily get any other way, but we might as well grab the others
    # while we have the reader available.
    bfreader = ImageReader()
    bfreader.id = str(filename)
    num_images = bfreader.seriesCount
    num_channels = bfreader.sizeC
    width = bfreader.sizeX
    height = bfreader.sizeY
    bfreader.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 "==========================="

        options = ImporterOptions()
        options.id = str(filename)
        options.setOpenAllSeries(True)
        # concatenate=True gives us a single stack rather than a list of
        # separate images.
        options.setConcatenate(True)
        # Limit the reader to the channel we're currently working on. This loop
        # is mainly why we need to know num_images before opening anything.
        for i in range(num_images):
            options.setCBegin(i, channel)
            options.setCEnd(i, channel)
        # openImagePlus returns a list of images, but we expect just one (a
        # stack).
        input_image = BF.openImagePlus(options)[0]

        # 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!"
Beispiel #26
0
        headers = ['Original path','Processed path']
        csvWriter.writerow(headers)

    # Process list of images
    for (counter, f) in enumerate(files):

        # Display progress
        IJ.showStatus("Processing file "+ str(counter+1) +"/"+ str(len(files)))

        # Open each image and process it
        imp = IJ.openImage(f)
        myRoutines(imp)

        # Save processed image in out_dir (enforcing .tif extension)
        newpath = os.path.splitext(out_dir + imp.getTitle())[0] +".tif"
        IJ.saveAsTiff(imp, newpath)
        imp.close()

        # Log paths of processed files
        csvWriter.writerow([f, newpath])

    # Display CSV log
    csvFile.close()
    rt = ResultsTable.open(csvPath)
    rt.show("_ProcessedFileList.csv")

    # Proudly inform that processing terminated
    if IJ.showMessageWithCancel("All done","Reveal output directory?"):
        Utils.revealFile(out_dir);

else:
Beispiel #27
0
outDir = DirectoryChooser("Batch Splitter: Chose >Output< Dir").getDirectory()
if outDir is None:
    print "Output to same dir as source."
    ourtDir = srcDir

for root, directories, filenames in os.walk(srcDir):
    for filename in filenames:
        # Skip non-TIF files
        if not filename.endswith(".tif"):
            continue
        inpath = os.path.join(root, filename)

        print "Reading ", filename
        imp = IJ.openImage(inpath)
        if imp is None:
            print "Skipped, wrong with reading: ", filename
            continue
        else:
            splittedimps = ChannelSplitter.split(imp)
            for i, simp in enumerate(splittedimps):
                outfn = os.path.splitext(filename)[0] + "_C_" + str(i) + ".tif"
                outpath = os.path.join(outDir, outfn)
                if os.path.exists(outpath):
                    print "Skipped, already exists: ", outfn
                    continue
                IJ.saveAsTiff(simp, outpath)
                print "Splitted and saved to ", outfn

print "done."
			for path in filecollection:
				theImage = IJ.openImage(path)
				calibration = theImage.getCalibration()
				scaleXs.append(calibration.pixelWidth)
				theImage.close()
			lc_scale = max(scaleXs)
			print lc_scale
			for path in filecollection:
				theImage = IJ.openImage(path)
				bname1 = os.path.basename(path)
				bname2 = os.path.splitext(bname1)[0]
				this_cal = theImage.getCalibration()
				scale_factor = (this_cal.pixelWidth / lc_scale) * common_scale
				params = "x=" + str(scale_factor) + " y=" + str(scale_factor) + " z=1.0 interpolation=Bilinear average process create title=doggie"
				IJ.run(theImage,"Scale...",params)
				saveImage = WindowManager.getImage("doggie")
				pixelWidth = saveImage.getCalibration().pixelWidth
				pixelHeight = saveImage.getCalibration().pixelHeight
				pixelDepth = saveImage.getCalibration().pixelDepth
				if convert_to_rgb:
					old_saveImage = saveImage
					old_saveImage.changes = False
					saveImage = old_saveImage.flatten()
					old_saveImage.close()
				saveImage.getCalibration().pixelWidth = pixelWidth
				saveImage.getCalibration().pixelHeight = pixelHeight
				saveImage.getCalibration().pixelDepth = pixelDepth
				IJ.saveAsTiff(saveImage,dirPath+"resized/"+bname2+".tif")
				theImage.close()
				saveImage.close()
Beispiel #29
0
    def process(self,imp):
        # extract nucleus channel, 8-bit and twice binned
        imp.setC(self.nucleusChannel)
        ip = imp.getChannelProcessor().duplicate()
        ip = ip.convertToByteProcessor()
        ip = ip.bin(4)
        nucleus = ImagePlus("nucleus_channel", ip)

        # threshold image and separate clumped nuclei
        IJ.run(nucleus, "Auto Threshold", "method=Otsu white setthreshold show");
        IJ.run(nucleus, "Make Binary", "thresholded remaining black");
        IJ.run(nucleus, "Watershed", "");

        directory = imp.getTitle()
        directory = directory.replace(" ", "_")\
            .replace(",", "_")\
            .replace("#", "_series")\
            .replace("...", "")\
            .replace(".","_")
        directory = os.path.join(self.exportDir, directory)
        sliceDirectory = os.path.join(directory, "slices")
        print directory
        print sliceDirectory
        if not os.path.exists(sliceDirectory):
            os.makedirs(sliceDirectory)

        # Create a table to store the results
        table = ResultsTable()

        # Create a hidden ROI manager, to store a ROI for each blob or cell
        #roim = RoiManager(True)

        # remove small particles and border particles
        pa = ParticleAnalyzer(\
            ParticleAnalyzer.ADD_TO_MANAGER | ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES,\
            Measurements.CENTER_OF_MASS,\
            table,\
            self.minArea, self.maxArea,\
            0.0,1.0)

        if pa.analyze(nucleus):
            print "All ok, number of particles: ", table.size()
        else:
            print "There was a problem in analyzing", imp, nucleus
        table.save(os.path.join(directory, "rt.csv"))

        # read the center of mass coordinates
        cmx = table.getColumn(0)
        cmy = table.getColumn(1)

        if self.debug:
            imp.show()

        i=0
        for i in range(0, min(self.nCells,table.size())):
            # ROI around the cell
            cmx = table.getValue("XM",i)
            cmy = table.getValue("YM",i)
            x = 4 * cmx - (self.boxSize - 1) / 2
            y = 4 * cmy - (self.boxSize - 1) / 2
            if (x < self.edge or y < self.edge or x > imp.getWidth() - self.edge or y > imp.getHeight() - self.edge):
                continue
            roi = Roi(x,y,self.boxSize,self.boxSize)
            imp.setRoi(roi, False)

            cellStack = ImageStack(self.boxSize, self.boxSize)

            for z in range(1, imp.getNSlices() + 1):
                imp.setSlice(z)
                for c in range(1, imp.getNChannels() + 1):
                    imp.setC(c)
                    # copy ROI to stack
                    imp.copy()
                    impSlice = imp.getClipboard()
                    cellStack.addSlice(impSlice.getProcessor())
                    if self.slices:
                        sliceTitle = "cell_%s_z%s_c%s" % (str(i).zfill(4), str(z).zfill(3), str(c))
                        print sliceTitle
                        IJ.saveAsTiff(impSlice, os.path.join(sliceDirectory, sliceTitle))
                    impSlice.close()

            title = "cell_" + str(i).zfill(4)
            cell = ImagePlus(title, cellStack)

            # save ROI image
            IJ.saveAsTiff(cell, os.path.join(directory, title))
            cell.close()

            if self.debug:
                imp.updateAndDraw()
                wait = Wait("particle done")
                wait.show()
    Canceled = False

if not Canceled:

    for f in file_path:

        # Hyperstackの作成
        imp = IJ.openImage(f)
        nFrame = imp.getNSlices(
        ) / n_Channel  # 元画像のAttributionがなぜかFrame が Z sliceとなっている

        # File 保存のための文字列作成
        save_file = imp.getTitle().replace(".tif", "-stack.tif")
        save_path = os.path.join(save_dir, save_file)

        # Hyper Stackに変換
        h_imp = HyperStackConverter.toHyperStack(imp, n_Channel, 1, nFrame,
                                                 "Composite")

        del imp

        # Hyper Stack の Channelカラー変更
        for i, color in enumerate(user_color):
            h_imp.setC(i + 1)
            h_imp.setLut(LUT.createLutFromColor(Colors[color]))

        # ファイルを保存
        IJ.saveAsTiff(h_imp, save_path)
        # IJ.log(save_path)
        del h_imp
from ij.io import DirectoryChooser
from ij.plugin import Memory

dc = DirectoryChooser("Choose directory of LSM files...")
dirPath = dc.getDirectory()
if dirPath is not None:
	fileList = glob.glob(dirPath+"*.lsm")

	for path in fileList:
		processImage = False
		theSize = os.path.getsize(path) / 1048576.0
		print theSize
		totFijiMem = Memory().maxMemory() / 1048576.0
		print totFijiMem
		if (theSize < totFijiMem/3.0):
			basename = os.path.splitext(os.path.basename(path))[0]
			outputPath = dirPath + basename + ".tif"
			if not os.path.exists(outputPath):
				processImage = True

			params = "type=[Positions from file] order=[Defined by image metadata] browse=[" + path + "] multi_series_file=[" + path + "] fusion_method=[Linear Blending] regression_threshold=0.30 max/avg_displacement_threshold=2.50 absolute_displacement_threshold=3.50 compute_overlap ignore_z_stage increase_overlap=10 subpixel_accuracy computation_parameters=[Save memory (but be slower)] image_output=[Fuse and display]"
			print params
			if (processImage):
				try:
					IJ.run("Grid/Collection stitching", params)
					stitchedImage = IJ.getImage()
					IJ.saveAsTiff(stitchedImage,outputPath)
					stitchedImage.close()
				except:
					IJ.log("Failed to stitch and save " + path)
Beispiel #32
0
from edfgui import ExtendedDepthOfField, Parameters

dc = DirectoryChooser("Set input directory")
files = glob.glob(dc.getDirectory() + "/*.tiff")

dc = DirectoryChooser("Set output directory")
outputDir = dc.getDirectory()

# EDF parameters
params = Parameters()
params.setQualitySettings(params.QUALITY_HIGH)

for f in files:
    imp = ImagePlus(f)

    # output name
    head,tail = os.path.split(f)
    base,ext = os.path.splitext(tail)
    output = os.path.join(outputDir,base + "_edf.tif")
    print output

    # make all-in-focus image
    edf = ExtendedDepthOfField(imp,params)
    edf.process()

    # save output
    imp = WindowManager.getCurrentImage()
    IJ.saveAsTiff(imp,output)
    imp.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
if dirPath is not None:
	dc2 = DirectoryChooser("Select output directory...")
	outPath = dc2.getDirectory()
	if outPath is not None:
		gd = GenericDialog("Options...")
		gd.addCheckbox("Recolor_images",True)
		gd.showDialog()
		if (gd.wasOKed()):
			doRecolor = gd.getNextBoolean()
		
			for f in os.listdir(dirPath):
				if f.endswith(".tif") or f.endswith(".tiff"):
					theImage = IJ.openImage(dirPath+f)
					IJ.log("Loaded " + f)
					palette = [Color.GREEN,Color.RED,Color.BLUE]
					if (theImage.getNChannels() < 4):
						if doRecolor:
							for i in range(theImage.getNChannels()):
								theImage.setChannelLut(LUT.createLutFromColor(palette[i]),i+1)
						try:
							sc = StackConverter(theImage)
							sc.convertToRGB()
							IJ.saveAsTiff(theImage,outPath+os.path.splitext(f)[0]+"_rgb.tif")
							IJ.log("Completed " + f)
						except:
							IJ.log("Exception thrown during RGB conversion, image skipped")
						finally:
							theImage.close()
					else:
						IJ.log("Image has too many color channels")
				
rm.runCommand("Show All with labels")
#for each image open..
for image in image_titles:
    imp = WindowManager.getImage(image)
    baseName = os.path.splitext(image)[0]  #get the name without extension
    roiFile = baseName + "_ROISet.zip"  #make the name for the text file
    roiFilePath = os.path.join(roiDir,
                               roiFile)  #make the path for the text file
    print(roiFilePath)

    IJ.openImage(roiFilePath)  #open the roi text file

    rm.runCommand("Select All")  #select all rois
    rm.runCommand(imp, "Measure")  #measure all rois

    rm.runCommand(imp, "Show All")  #show all rois
    imp2 = imp.flatten()  #create a flattened key with rois and labels
    imp2.setTitle("labels_" + baseName + ".tif")
    imp2.show()
    rm.runCommand("Select All")
    rm.runCommand("Delete")  #delete all rois in manager
    imp.close()
    rm.runCommand(imp, "Show None")

    windowName = imp2.getTitle()
    flatPath = os.path.join(roiDir, windowName)
    IJ.saveAsTiff(imp2, flatPath)  #save flattened image

csvFile = os.path.join(roiDir, "Measurements.csv")
IJ.saveAs("Results", csvFile)  #export measurements as csv file
Beispiel #36
0
        	image_path = image_directory + '/' + i;
        	imp = IJ.openImage(image_path);
        	imp.show();
        	for k in match_roi:
            		IJ.selectWindow(i);
            		cur_match_roi = k;
            		m = re.search('(Batch\d+_\d+_XY\d{2}_cropped_singlet\d+).roi', cur_match_roi);
            		crop_name = m.group(1);
            		roi_path = roi_directory + '/' + cur_match_roi;
            		IJ.open(roi_path);
            		temp_str = 'title=' + crop_name + '.tif duplicate';
            		IJ.run('Duplicate...', temp_str);
            		imp_cropped = IJ.getImage();
            		save_name = crop_dir + '/' + crop_name + '.tif';
            		print(save_name);
            		IJ.saveAsTiff(imp_cropped, save_name);
        	IJ.run('Close All');
    		gc.collect();
    else:
	if len(match_roi) >= 1:
		for k in match_roi:
			image_path = image_directory + '/' + i;
			imp = IJ.openImage(image_path);
			imp.show();
			IJ.selectWindow(i);
			cur_match_roi = k;
			m = re.search('(Batch\d+_\d+_XY\d{2}_cropped_singlet\d+).roi', cur_match_roi);
			crop_name = m.group(1);
			roi_path = roi_directory + '/' + cur_match_roi;
			IJ.open(roi_path);
			IJ.run('Crop');
refImp = IJ.openImage(refpath)
width = refImp.width  
height = refImp.height  

roim = RoiManager()
roim.runCommand("open", roipath)

roiArray = roim.getRoisAsArray()
nRoi = len(roiArray)
roim.close()

bwStack = ImageStack(width, height, nRoi)
for i in xrange(1, nRoi+1):
    bwStack.setProcessor(FloatProcessor(width, height, zeros('f', width * height), None), i)

for i in xrange(1, nRoi+1):
    roi = roiArray[i-1]
    fp = bwStack.getProcessor(i)
    fp.setValue(1.0)
    fp.fill(roi)

roiImp = ImagePlus("roi", bwStack)

outfn = "roi_" + os.path.splitext(roifn)[0] + ".tif"
outpath = os.path.join(roidir, outfn)
if os.path.exists(outpath):
    print "Skipped, already exists: ", outfn
else:
    IJ.saveAsTiff(roiImp, outpath)
Beispiel #38
0
import glob
import os.path
import sys

from ij import IJ, ImagePlus, ImageStack, WindowManager
from ij.io import DirectoryChooser

from edfgui import ExtendedDepthOfField, Parameters

file_in = sys.argv[1]
file_out = sys.argv[2]

# EDF parameters
params = Parameters()
params.setQualitySettings(params.QUALITY_HIGH)
params.nScales = 10

# read input image
imp = ImagePlus(file_in)

# make all-in-focus image
edf = ExtendedDepthOfField(imp,params)
edf.process()

# save output
imp = WindowManager.getCurrentImage()
IJ.saveAsTiff(imp,file_out)
imp.close()

Beispiel #39
0
def processOneImage(inputDir):
    tmp = glob.glob(os.path.join(inputDir, "fibrone*"))
    fibronectin = tmp[0]
    tmp = glob.glob(os.path.join(inputDir, "nucleus*"))
    nucleus = tmp[0]
    tmp = glob.glob(os.path.join(inputDir, "actin*"))
    actin = tmp[0]
    
    # read sample name
    head,tail = os.path.split(inputDir)
    sample = tail.replace(".tif_Files","")

    # original images
    imp_fn_orig = IJ.openImage(fibronectin)
    imp_nuc_orig = IJ.openImage(nucleus)

    # work copies
    imp_fn = imp_fn_orig.duplicate()
    imp_nuc = imp_nuc_orig.duplicate()

    IJ.run(imp_fn,"Set Scale...", "distance=1 known=1 pixel=1 unit=pixels")
    IJ.run(imp_fn,"Gaussian Blur...","sigma=5")
    IJ.run(imp_fn,"Make Binary","")
    IJ.run(imp_nuc,"Set Scale...", "distance=1 known=1 pixel=1 unit=pixels")
    IJ.run(imp_nuc,"Gaussian Blur...","sigma=5")
    IJ.run(imp_nuc,"Make Binary","")

    # get moments of the fibronectin image
    moments_file = os.path.join(OUTPUT, sample + " moments.txt")
    printMoments(fibronectin, moments_file)
    moments = readMoments(moments_file)
    print moments.m00
    sys.exit()

    # centroid of fibronectin anchor
    centers = getParticleCenters(imp_fn)
    cxfn = int(round(centers[0][0]))
    cyfn = int(round(centers[1][0]))
    fn_centroid_roi = PointRoi(cxfn,cyfn)
    fn_centroid_roi.setDefaultMarkerSize("Large")
    fn_centroid_roi.setStrokeColor(Color.CYAN)

    # center of mass of nucleus 
    centers = getParticleCenters(imp_nuc)
    cxnuc = int(round(centers[2][0]))
    cynuc = int(round(centers[3][0]))
    nuc_com_roi = PointRoi(cxnuc,cynuc)
    nuc_com_roi.setDefaultMarkerSize("Large")

    # skeletonize fibronectin anchor to find its orientation
    IJ.run(imp_fn,"Skeletonize","")
    skel = AnalyzeSkeleton_()
    skel.setup("",imp_fn)
    skelResult = skel.run(skel.NONE, False, True, None, True, True)
    graph = skelResult.getGraph()
    print len(graph)
    print skelResult.getNumOfTrees()
    # find the longest graph
    graph = sorted(graph, key=lambda g: getGraphLength(g), reverse=True)
    graph = graph[0]
    edges = graph.getEdges()
    # find longest edge, the main axis of the anchor
    edges = sorted(edges, key=lambda edge: edge.getLength(), reverse=True)
    #for e in edges:
    #    print e.getLength()
    v1long = edges[0].getV1()
    v2long = edges[0].getV2()
    x1 = v1long.getPoints()[0].x
    y1 = v1long.getPoints()[0].y
    x2 = v2long.getPoints()[0].x
    y2 = v2long.getPoints()[0].y
    anchor_roi = PointRoi(x1,y1)
    anchor_roi = anchor_roi.addPoint(x2,y2)
    # find top and bottom vertices of the graph
    vertices = graph.getVertices()
    vertices = sorted(vertices, key=lambda vertex: vertex.getPoints()[0].y)
    v1short = vertices[len(vertices)-1]
    v2short = vertices[0]
    x3 = v1short.getPoints()[0].x
    y3 = v1short.getPoints()[0].y
    x4 = v2short.getPoints()[0].x
    y4 = v2short.getPoints()[0].y
    anchor_roi = anchor_roi.addPoint(x3,y3)
    anchor_roi = anchor_roi.addPoint(x4,y4)
    # calculate angles
    a1 = math.atan(abs(float(y2-y1)/float(x2-x1))) / math.pi * 360
    a2 = math.atan(abs(float(x4-x3)/float(y4-y3))) / math.pi * 360
    amean = float((a1+a2)/2)
    dx = cxfn-cxnuc
    print sample,cxfn,cyfn,cxnuc,cynuc,dx,math.cos(amean)*dx,x1,y1,x2,y2,x3,y3,x4,y4,a1,a2

    # create composite
    comp = ImagePlus("composite",imp_nuc_orig.getProcessor().convertToColorProcessor())
    comp.getProcessor().setChannel(2,imp_fn_orig.getProcessor())
    comp.getProcessor().setChannel(3,imp_fn.getProcessor())
    comp.show()
    comp.getProcessor().drawRoi(fn_centroid_roi)
    comp.getProcessor().drawRoi(nuc_com_roi)
    comp.getProcessor().drawRoi(anchor_roi)
    comp.repaintWindow()
    IJ.saveAsTiff(comp, os.path.join(OUTPUT,sample + ".tif"))
	## Outputs each stitched z plane as a separate file
	iReader = ImageReader()
	iReader.setId(parentLSMFilePath)
	for z in range(max_coords[2]+basic_info[4]):
	## for z in range(50,51):
		IJ.showStatus("z: "+str(z+1)+" of "+str(max_coords[2]+basic_info[4]))
		chIps = []
		resImages = []
		for ch in range(basic_info[0]):
			chIps.append(ByteProcessor(max_coords[0]+scale_info[2],max_coords[1]+scale_info[2]))
		for ch in range(basic_info[0]):
			resImages.append(ImagePlus("ch"+str(ch+1),chIps[ch]))
		for se in range(basic_info[1]):
			IJ.showProgress(se,basic_info[1])
			if z >= coords_upscaled[se][2] and z <= coords_upscaled[se][2]+basic_info[4]-1:
				iReader.setSeries(se)
				for ch in range(basic_info[0]):
					byteArray = iReader.openBytes((z-coords_upscaled[se][2])*basic_info[0]+ch)
					testIp = ByteProcessor(scale_info[2],scale_info[2],byteArray)
					testImage = ImagePlus("tester",testIp)
					Image_stamper.stampStack(testImage,resImages[ch],coords_upscaled[se][0],coords_upscaled[se][1],0)			
					activeIp = chIps[ch]
					testImage.close()
					
					
		for ch in range(len(resImages)):
			IJ.saveAsTiff(resImages[ch],parentLSMFilePath+"_tiles/v_img/img_z_"+str(z+1)+"_c_"+str(ch+1)+".tif")
		#outPlaneImage = RGBStackMerge.mergeChannels(resImages,False)
		#IJ.saveAsTiff(outPlaneImage,parentLSMFilePath+"_tiles/v_img/img_z_"+str(z+1)+".tif")
		#outPlaneImage.close()

parser = OptionParser()
parser.add_option('-o', '--output', help='edf.tiff')
options, args = parser.parse_args()

print options.output
print args

# check input image size
tmp = ImagePlus(args[0])

# put input images in a stack
stack = ImageStack(tmp.getWidth(), tmp.getHeight())
for a in args:
    imp = ImagePlus(a)
    stack.addSlice(imp.getProcessor())
imp = ImagePlus("focus stack", stack)
IJ.saveAsTiff(imp, options.output.replace("_edf_", "_edf_stack_"))

#sys.exit()
# process input
output = process(imp)

# save output
IJ.saveAsTiff(output, options.output)

# close images
output.close()
imp.close()
        categorizer = RangedCategorizer( nImages )

        matrices    = DenseCorrelationMatricesWithRadius(
			wrappedImage,
			radii[0],
			c,
			DoubleType()
			)
        
        result = MultiScaleEstimation.estimateZCoordinates( matrices, startingCoordinates, c, radii, steps, visitor, categorizer, opt )
        IJ.log("done")

        resultFileName = '%s/result.tif' % home.rstrip('/')
        imp = ImageJFunctions.wrap( result, 'result' )
        IJ.saveAsTiff(imp.duplicate(), resultFileName)

        relativeResult = result.copy()
        c = relativeResult.cursor()
        while c.hasNext():
            c.fwd()
            cur = c.get()
            val = cur.get()
            cur.set( val - c.getDoublePosition( 2 ) )

        relativeResultFileName = '%s/relativeResult.tif' % home.rstrip('/')
        imp = ImageJFunctions.wrap( relativeResult, 'relative result' )
        IJ.saveAsTiff(imp.duplicate(), relativeResultFileName)

        ratio = [ wrappedImage.dimension( 0 )*1.0/result.dimension( 0 ), wrappedImage.dimension( 1 )*1.0/result.dimension( 1 ) ]
        shift = [ 0.0, 0.0 ]
		ratio_rec_str = "%.3f" % ratio_rec
		gd.addMessage(str(i+1)+"-channel: " + str(mem_recs[i]) + "MB; Ratio: " + ratio_rec_str)
	gd.showDialog()
	ratioRaw = gd.getNextNumber()
	ratio = math.sqrt(ratioRaw)

	if (gd.wasOKed()):		
		filecollection = glob.glob(os.path.join(sourceDir, '*.ome.tif'))
		numFiles = len(filecollection)
		count = 1
		for f in filecollection:
			bname1 = os.path.basename(f)
			bname2 = os.path.splitext(bname1)[0]
			bname3 = os.path.splitext(bname2)[0]
			print bname3
		
			params = "open=[" + f + "] color_mode=Default view=Hyperstack stack_order=XYCZT"
			IJ.run("Bio-Formats Importer",params)
		
			theImage = WindowManager.getCurrentImage()
	
			params2 = "x=" + str(ratio) + " y=" + str(ratio) + " z=1.0 interpolation=Bilinear average process create title=doggie"
			IJ.run(theImage,"Scale...",params2)
			theImage.close()
			saveImage = WindowManager.getImage("doggie")
			savePath = sourceDir+"resized/"+bname3+".tif"
			IJ.saveAsTiff(saveImage,sourceDir+"resized/"+bname3+".tif")
			saveImage.close()
			IJ.showStatus("Tile: " + str(count) + "/" + str(numFiles))
			count = count + 1
Beispiel #44
0
imageHeight = 1024
imageDepth = 151
pixelWidth = 0.52
pixelHeight = 0.52
pixelDepth = 1.9867549668874172

print(folder)

images = []

# load all images, collect them in a list
for root, directories, filenames in os.walk(folder):
    filenames.sort()
    for filename in filenames:
        print(filename)
        if (filename.endswith(".raw")):
            if (not File(os.path.join(targetFolder,
                                      filename + ".tif")).exists()):
                IJ.run(
                    "Raw...", "open=[" + os.path.join(folder, filename) +
                    "] image=[16-bit Signed] width=" + str(imageWidth) +
                    " height=" + str(imageHeight) + " number=" +
                    str(imageDepth) + " little-endian")
                imp = IJ.getImage()
                imp.getCalibration().pixelWidth = pixelWidth
                imp.getCalibration().pixelHeight = pixelHeight
                imp.getCalibration().pixelDepth = pixelDepth
                IJ.saveAsTiff(imp, os.path.join(targetFolder,
                                                filename + ".tif"))
                imp.close()
	# Copies tiles for stitching into temp directory and stitches, if necessary
	if len(tiles)==1:
		params = "open=["+ imgDir +"tile_"+str(tiles[0])+".ome.tif] color_mode=Default view=Hyperstack stack_order=XYCZT"
		IJ.run("Bio-Formats Importer", params);
		tileImage = WindowManager.getImage("tile_"+str(tiles[0])+".ome.tif")
		tileImage.setSlice(int(tileImage.getNSlices()/2))
	else:
		ind = 1
		for t in tiles:
			shutil.copyfile(imgDir+"tile_"+str(t)+".ome.tif",imgDir+"temp/tile_"+str(ind)+".ome.tif")
			ind = ind + 1
		IJ.showStatus("Beginning stitch...")
		params = "type=[Grid: row-by-row] order=[Right & Down                ] grid_size_x=" + str(xs[2]) + " grid_size_y=" + str(ys[2]) + " tile_overlap=10 first_file_index_i=1 directory=[" + imgDir + "temp] file_names=tile_{i}.ome.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 ignore_z_stage subpixel_accuracy computation_parameters=[Save memory (but be slower)] image_output=[Fuse and display]"
		IJ.run("Grid/Collection stitching", params)
		fusedImage = WindowManager.getImage("Fused")
		IJ.saveAsTiff(fusedImage,imgDir+"temp/Fused.tif")
		fusedImage.close()
		IJ.open(imgDir+"temp/Fused.tif")
		tileImage = WindowManager.getImage("Fused.tif")
		tileImage.setSlice(int(tileImage.getNSlices()/2))
	
	gd = NonBlockingGenericDialog("Explore full resolution...")
	gd.addMessage("Select ROI for visualization at full resolution")
	gd.showDialog()
	doContinue = gd.wasOKed()

##### Removes temporary tile files ######
# filelist = [f for f in os.listdir(imgDir+"temp") if f.endswith(".tif")]
# for f in filelist:
#	os.remove(f)
from ij import IJ
from ij.gui import GenericDialog
from ij.plugin import ChannelSplitter
import os

path = IJ.getDirectory("Select source directory:")

if not os.path.exists(path + "\\output"):
    os.mkdir(path + "\\output")

filenames = list(name for name in os.listdir(path) if name.endswith(".lsm"))
for filename in filenames:
    img = IJ.openImage(path + "\\" + filename)
    #IJ.saveAsTiff(img, path + "\\output\\" + filename[:-4])
    channels = ChannelSplitter.split(img)
    for i, c in enumerate(channels):
        IJ.saveAsTiff(
            c, path + "\\output\\" + filename[:-4] + "_channel" + str(i))

IJ.beep()
gd = GenericDialog("Success!")
gd.addMessage("Successfully split " + str(len(filenames)) + " hyperstacks.")
gd.showDialog()
# Create the overlay image
overlayImage = image.duplicate()
IJ.run(overlayImage, "RGB Color", "")
IJ.run(overlayImage, 'Specify...', 'width=' + str(2*mean_radius) + \
					' height=' + str(2*mean_radius) + \
					' x=' + str(mean_cx) + \
					' y=' + str(mean_cy) + ' oval centered');

roi = overlayImage.getRoi()
overlayImage.setOverlay(roi, Color(246, 27, 27), 10, None)
overlayImage = overlayImage.flatten();

# Now add the overlay image as the first stack

newStack = image.createEmptyStack()
newStack.addSlice(overlayImage.getProcessor())
newStack.addSlice(image.getProcessor())

image.setStack(newStack)

directory = IJ.getDirectory('image')
print directory
name = image.getShortTitle()
print name
# Now save results table. Then done.
IJ.saveAs('Measurements', directory + name + '.txt')
print 'Done saving measurement table!'
# Now overwrite the original image
IJ.saveAsTiff(image, directory + name + '.tif')
def main():

    Interpreter.batchMode = True

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

    print "Loading images..."

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

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

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

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

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

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

        imp.close()

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

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

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

    print "Done!"
	
	# Performs scaling
	if (gd.wasOKed()):
		anchorTiles = range(startTile,finishTile+1,stepSize)
		print anchorTiles
		for i in anchorTiles:
			if (i+stepSize-1 > finishTile):
				lastAnchorTile = finishTile
			else:
				lastAnchorTile = i+stepSize-1
			
			iterTiles = range(i,lastAnchorTile+1)
			params = "open=[" + theFilePath + "] color_mode=Default view=Hyperstack stack_order=XYCZT series_list=" + str(i) + "-" + str(lastAnchorTile)
			print params
			IJ.run("Bio-Formats Importer", params)
			imageIDList = WindowManager.getIDList()
			if (len(imageIDList) == len(iterTiles)):
				count = 0
				for j in imageIDList:
					theImage = WindowManager.getImage(j)
					print theImage.getTitle()
					params2 = "x=" + str(ratio) + " y=" + str(ratio) + " z=1.0 interpolation=Bilinear average create title=doggie"
					IJ.run(theImage,"Scale...",params2)
					theImage.close()
					saveImage = WindowManager.getImage("doggie")
					IJ.saveAsTiff(saveImage,theDirectory+baseName+"_resized/tile_"+str(iterTiles[count])+".tif")
					saveImage.close()
					count = count + 1
			else:
				print "Open image count does not match tile count!"	
						"std_dev_distance_to_surface median_distance_to_surface centre_of_mass " +
						"bounding_box dots_size=5 font_size=10 " + 
						"redirect_to=none")
				IJ.run("3D OC Options", params)
				params = ("threshold=" + str(intThreshold) + 
						" slice=1 min.=" + str(sizeThreshold) + " max.=24903680 objects surfaces statistics")
				IJ.redirectErrorMessages(True)
				IJ.run(dataImage, "3D Objects Counter", params)
				dataImage.changes = False
				dataImage.close()

				## Saves the results table, surfaces image output, and run configuration
				surfacesImage = WindowManager.getImage("Surface map of " + dataImage.getTitle())
				IJ.run(surfacesImage,"8-bit","")
				surfacesImage = make_image_binary(surfacesImage)
				IJ.saveAsTiff(surfacesImage,parentLSMFilePath + "_tiles/surfaces/C" + str(analysisChannel) + "-tile_" + str(tile) + ".tif")
				surfacesImage.close()
				objectsImage = WindowManager.getImage("Objects map of " + dataImage.getTitle())
				IJ.run(objectsImage,"8-bit","")
				objectsImage = make_image_binary(objectsImage)
				IJ.saveAsTiff(objectsImage,parentLSMFilePath + "_tiles/maps/C" + str(analysisChannel) + "-tile_" + str(tile) + ".tif")
				objectsImage.close()
				IJ.selectWindow("Results")
				IJ.saveAs("Results",parentLSMFilePath + "_tiles/objects/C" + str(analysisChannel) + "-tile_" + str(tile) + ".csv")
			
			configData = ("Parent LSM file: " + parentLSMFilePath + "\n" +
						"Analysis channel: " + str(analysisChannel) + "\n" +
						"Bleeding channel: " + str(bleedingChannel) + "\n" +
						"Refractive correction reference channel: " + str(refChannel) + "\n" +
						"Intensity threshold (0-255): " + str(intThreshold) + "\n" +
						"Size threshold (voxels): " + str(sizeThreshold) + "\n" +
        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')

    print("DONE, find your results in " + Out_dir)