def main(*R):
    """ Main function
	"""
    # Show intial progress bar
    IJ.showProgress(0, 50)
    IJ.showStatus("Heterogeneous Z Correction")

    # Retrieve the values R (with default values) from previous attempts
    Rstr = "[(-0.05977, 83.3, 78.73),(-0.05976, 41.65, 39.36)]"
    R = eval(Prefs.get("HetZCorr.R", Rstr))

    # Load current image and get infos
    imp = IJ.getImage()
    stk = imp.getStack()
    (sx, sy, sz) = stackSize(stk)
    cal = imp.getCalibration()

    # Get unique values
    val = getUniqueValues(stk)

    # Get R from dialog
    R = showDialogR(R, val)

    # Generate optical model
    correction = generateModel(stk, R, val)
    imp.setCalibration(cal)

    #Show model image
    correction.show()
    correction.setSlice(sz)
    IJ.run(correction, "Enhance Contrast", "saturated=0.35")
    IJ.run(correction, "Fire", "")
def downsample_for_isotropy(imp, extra_downsample_factor=2.0, info=None):
	"""downsample x, y pixel directions to get ~cubic voxels"""
	title = imp.getTitle();
	cal = imp.getCalibration();
	if info is None:
		pix_w = cal.pixelWidth;
		pix_h = cal.pixelHeight;
		pix_d = cal.pixelDepth;
	else:
		pix_w = info.get_xy_pixel_size_um();
		pix_h = pix_w;
		pix_d = info.get_z_plane_spacing_um();
	im_w = imp.getWidth();
	im_h = imp.getHeight();
	im_d = imp.getNSlices();
	print("original pixel whd = ({}, {}, {})".format(pix_w, pix_h, pix_d));
	print("original image whd = ({}, {}, {})".format(im_w, im_h, im_d));
	im_nch = imp.getNChannels();
	if im_nch > 1:
		split_ch = ChannelSplitter().split(imp);
	else:
		split_ch = [imp];
	print("downsampling {} and making isotropic...".format(title));
	IJ.showStatus("Downsampling and making ~isotropic...");
	xy_scale = pix_h / (pix_d * extra_downsample_factor);
	xy_scaled_h = int(xy_scale * im_h);
	xy_scaled_w = int(xy_scale * im_w);
	z_scale = 1/ extra_downsample_factor;
	z_scaled_h = int(z_scale * im_d);
	out_imps = [];
	for ch_imp in split_ch:
		print(ch_imp.getTitle());
		sp = StackProcessor(ch_imp.getStack());
		print((xy_scaled_w, xy_scaled_h));
		stack = sp.resize(xy_scaled_w, xy_scaled_h, True);
		xz_stack = rot_around_x(stack);
		xz_sp = StackProcessor(xz_stack);
		xz_stack = xz_sp.resize(xy_scaled_w, z_scaled_h, True);
		out_stack = rot_around_x(xz_stack);
		out_imps.append(ImagePlus("Isotropic downsampled {}".format(title), out_stack));
	cal.setUnit('um');
	cal.pixelWidth = im_w/xy_scaled_w * pix_w;
	cal.pixelHeight = im_h/xy_scaled_h * pix_h;
	cal.pixelDepth = im_d/z_scaled_h * pix_d;
	print("new pixel whd = ({}, {}, {})".format(cal.pixelWidth, cal.pixelHeight, cal.pixelDepth));
	imp.changes = False;
	imp.close();
	for ch_imp in split_ch:
		ch_imp.close();
	if len(out_imps) > 1:
		out_imp = RGBStackMerge().mergeChannels(out_imps, False);
	else:
		out_imp = out_imps[0];
	out_imp.setCalibration(cal);
	print("new image whd = ({}, {}, {})".format(out_imp.getWidth(), out_imp.getHeight(), out_imp.getNSlices()));
	print("...done downsampling {} and making isotropic. ".format(title));
	IJ.showStatus("...done downsampling and making ~isotropic. ");
	return out_imp;
Beispiel #3
0
def download_from_url(download_url,
                      target_dir,
                      download_file=None,
                      download_msg=None):
    '''
	download file in temporary location
	move to target_dir
	clean up download
	'''
    from ij import IJ
    print(download_url)

    # open url and set up using header information
    u = urllib2.urlopen(download_url)
    headers = u.info()
    download_size = int(headers['Content-Length'])
    print(u)
    print(headers)

    if download_file == None:
        if headers.has_key('Content-Disposition'):
            download_file = re.sub(".*filename=", "",
                                   headers['Content-Disposition'])
        else:
            IJ.error(
                "No filename specified for download and none in http header!")
    if download_msg == None:
        download_msg = 'Downloading: %s' % (download_file)
    tf = tempfile.NamedTemporaryFile(suffix=download_file, delete=False)
    print 'Downloading ' + download_url + ' to ' + tf.name
    print "Download size should be %d" % (download_size)

    dest_file = os.path.join(target_dir, download_file)
    print 'Destination location %s' % (dest_file)

    # Now for the download
    block_size = 100000
    if download_size > block_size:
        bytes_read = 0
        while bytes_read < download_size:
            IJ.showStatus("%s (%.1f/%.1f Mb)" % (download_msg,
                                                 (bytes_read / 1000000.0),
                                                 (download_size / 1000000.0)))
            IJ.showProgress(bytes_read, download_size)
            tf.file.write(u.read(block_size))
            bytes_read += block_size
        IJ.showProgress(1.0)
    else:
        tf.file.write(u.read())

    u.close()
    tf.file.close()
    print('Downloaded file has size %d') % (os.path.getsize(tf.name))
    tf.close()

    shutil.move(tf.name, dest_file)
    IJ.showStatus('Cleaning up!')
Beispiel #4
0
	def __init__(self, download = True):
		'''
		Display the list of project descriptions in a non-modal dialog.
		'''
		super(ProjectDialog, self).__init__(self)
		self.biaflows = ConnectionWindow.getInstance().getBiaflows()
		IJ.showStatus('Connecting to: ' + self.biaflows.getHost() + " - please stand by...")
		self.download = download
		self.eventHandler = ProjectDialogEventHandler('BIAFlows', self.getHTML(), False)
def run(title):
    gd = GenericDialog('Record Desktop')
    gd.addNumericField('Max. frames:', 50, 0)
    gd.addNumericField('Milisecond interval:', 300, 0)
    gd.addSlider('Start in (seconds):', 0, 20, 5)
    gd.showDialog()
    if gd.wasCanceled():
        return
    n_frames = int(gd.getNextNumber())
    interval = gd.getNextNumber() / 1000.0  # in seconds
    delay = int(gd.getNextNumber())

    snaps = []

    try:
        while delay > 0:
            IJ.showStatus('Starting in ' + str(delay) + 's.')
            time.sleep(1)  # one second
            delay -= 1
        IJ.showStatus('')
        System.out.println("Starting...")
        # start capturing
        robot = Robot()
        box = Rectangle(IJ.getScreenSize())
        start = System.currentTimeMillis() / 1000.0  # in seconds
        last = start
        intervals = []
        real_interval = 0
        # Initial shot
        snaps.append(robot.createScreenCapture(box))
        while len(snaps) < n_frames and last - start < n_frames * interval:
            now = System.currentTimeMillis() / 1000.0  # in seconds
            real_interval = now - last
            if real_interval >= interval:
                last = now
                snaps.append(robot.createScreenCapture(box))
                intervals.append(real_interval)
            else:
                time.sleep(interval / 5)  # time in seconds
        # Create stack
        System.out.println("End")
        awt = snaps[0]
        stack = ImageStack(awt.getWidth(None), awt.getHeight(None), None)
        t = 0
        for snap, real_interval in zip(snaps, intervals):
            stack.addSlice(str(IJ.d2s(t, 3)),
                           ImagePlus('', snap).getProcessor())
            snap.flush()
            t += real_interval

        ImagePlus("Desktop recording", stack).show()
    except Exception, e:
        print "Some error ocurred:"
        print e
        for snap in snaps:
            snap.flush()
Beispiel #6
0
def run(title):
    gd = GenericDialog("Record Desktop")
    gd.addNumericField("Max. frames:", 50, 0)
    gd.addNumericField("Milisecond interval:", 300, 0)
    gd.addSlider("Start in (seconds):", 0, 20, 5)
    gd.showDialog()
    if gd.wasCanceled():
        return
    n_frames = int(gd.getNextNumber())
    interval = gd.getNextNumber() / 1000.0  # in seconds
    delay = int(gd.getNextNumber())

    snaps = []

    try:
        while delay > 0:
            IJ.showStatus("Starting in " + str(delay) + "s.")
            time.sleep(1)  # one second
            delay -= 1
        IJ.showStatus("")
        System.out.println("Starting...")
        # start capturing
        robot = Robot()
        box = Rectangle(IJ.getScreenSize())
        start = System.currentTimeMillis() / 1000.0  # in seconds
        last = start
        intervals = []
        real_interval = 0
        # Initial shot
        snaps.append(robot.createScreenCapture(box))
        while len(snaps) < n_frames and last - start < n_frames * interval:
            now = System.currentTimeMillis() / 1000.0  # in seconds
            real_interval = now - last
            if real_interval >= interval:
                last = now
                snaps.append(robot.createScreenCapture(box))
                intervals.append(real_interval)
            else:
                time.sleep(interval / 5)  # time in seconds
                # Create stack
        System.out.println("End")
        awt = snaps[0]
        stack = ImageStack(awt.getWidth(None), awt.getHeight(None), None)
        t = 0
        for snap, real_interval in zip(snaps, intervals):
            stack.addSlice(str(IJ.d2s(t, 3)), ImagePlus("", snap).getProcessor())
            snap.flush()
            t += real_interval

        ImagePlus("Desktop recording", stack).show()
    except Exception, e:
        print "Some error ocurred:"
        print e
        for snap in snaps:
            snap.flush()
def rot3d(imp, axis='x'):
	"""pare back Slicer to implement whole-image, +90* rotations that return ImagePlus"""
	if imp.getType()==ImagePlus.COLOR_256 or imp.getType()==ImagePlus.COLOR_RGB:
		raise NotImplementedError("Handling of colour images isn't implemented yet");
	IJ.showStatus("Rotating around {}-axis...".format(axis))
	title = imp.getTitle();
	original_cal = imp.getCalibration();
	new_cal = original_cal;
	
	if imp.getNChannels > 1:
		split_ch = ChannelSplitter().split(imp);
	else:
		split_ch = [imp];

	out_imps = [];
	if axis=='x':
		for ch_imp in split_ch:
			input_stack = ch_imp.getStack();
			output_stack = rot_around_x(input_stack);
			out_imps.append(ImagePlus(title, output_stack));
			new_cal.pixelHeight = original_cal.pixelDepth;
			new_cal.pixelDepth = original_cal.pixelHeight;
	elif axis=='y' or axis=='-y':
		for ch_imp in split_ch:
			if axis[0]=='-':
				input_stack = StackProcessor(ch_imp.getStack()).rotateLeft();
			else:
				input_stack = StackProcessor(ch_imp.getStack()).rotateRight();
			output_stack = rot_around_x(input_stack);
			if axis[0]=='-':
				final_stack = StackProcessor(output_stack).rotateLeft();
			else:
				final_stack = StackProcessor(output_stack).rotateRight();
			out_imps.append(ImagePlus(title, final_stack));
			new_cal.pixelWidth = original_cal.pixelDepth;
			new_cal.pixelDepth = original_cal.pixelWidth;
	elif axis=='z' or axis=='-z':
		for ch_imp in split_ch:
			if axis[0]=='-':
				output_stack = StackProcessor(ch_imp.getStack()).rotateLeft();
			else:
				output_stack = StackProcessor(ch_imp.getStack()).rotateRight();
			out_imps.append(ImagePlus(title, output_stack));
			new_cal.pixelWidth = original_cal.pixelHeight;
			new_cal.pixelHeight = original_cal.pixelWidth;
	else:
		raise NotImplementedError("Please check which axis you've chosen - if not (x, +/-y, +/-z) then it's not implemented...");
	imp.changes = False;
	imp.close();
	if len(out_imps) > 1:
		out_imp = RGBStackMerge().mergeChannels(out_imps, False);
	else:
		out_imp = out_imps[0];
	out_imp.setCalibration(new_cal);
	return out_imp;
Beispiel #8
0
def concatenateImagePlus(files, outfile):
    """Concatenate images contained in files and save in outfile"""

    options = ImporterOptions()
    options.setId(files[0])
    options.setVirtual(1)
    options.setOpenAllSeries(1)
    options.setQuiet(1)
    images = BF.openImagePlus(options)
    imageG = images[0]
    nrPositions = len(images)
    options.setOpenAllSeries(0)

    nslices = imageG.getNSlices()
    nframes = len(files)
    nchannels = imageG.getNChannels()
    luts = imageG.getLuts()

    for i in range(0, nrPositions):
        concatImgPlus = IJ.createHyperStack(
            "ConcatFile", imageG.getWidth(), imageG.getHeight(),
            imageG.getNChannels(), imageG.getNSlices(),
            len(files), imageG.getBitDepth())


        concatStack = ImageStack(imageG.getWidth(), imageG.getHeight())
        IJ.showStatus("Concatenating files")
        for file_ in files:
            try:
                print '...', basename(file_)
                options.setSeriesOn(i, 1)
                options.setId(file_)
                image = BF.openImagePlus(options)[0]
                imageStack = image.getImageStack()

                sliceNr = imageStack.getSize()
                for j in range(1, sliceNr+1):
                    concatStack.addSlice(imageStack.getProcessor(j))
                image.close()
                options.setSeriesOn(i, 0)
            except Exception, e:
                IJ.log("ERROR")
                IJ.log(file_ + str(e))
                raise
            IJ.showProgress(files.index(file_), len(files))

        concatImgPlus.setStack(concatStack, nchannels, nslices, nframes)
        concatImgPlus.setCalibration(image.getCalibration())
        concatImgPlus.setOpenAsHyperStack(True)
        concatImgPlus.setLuts(luts)
        concatImgPlus.close()
        IJ.saveAs(concatImgPlus, "Tiff",  outfile)
	def itemStateChanged(self,e):
		theRoi = self.theImage.getRoi()
		if (theRoi is not None):
			if (e.getStateChange() == ItemEvent.SELECTED):
				self.theImage.deleteRoi()
				backupImage = self.theImage.duplicate()
				self.theImage.setRoi(theRoi)
				outputImage = self.theImage.duplicate()
				for i in range(1,self.theImage.getNSlices()):
					self.theImage.setSliceWithoutUpdate(i)
					ip = self.theImage.getProcessor()
					ip.setValue(0)
					ip.fillOutside(theRoi)
				self.theImage.updateAndDraw()
				params = ("volume surface nb_of_obj._voxels " + 
						"nb_of_surf._voxels integrated_density mean_gray_value " +
						"std_dev_gray_value median_gray_value minimum_gray_value " +
						"maximum_gray_value centroid mean_distance_to_surface " + 
						"std_dev_distance_to_surface median_distance_to_surface centre_of_mass " +
						"bounding_box dots_size=5 font_size=10 show_numbers white_numbers " + 
						"redirect_to=none")
				IJ.run("3D OC Options", params)
				params = ("threshold=" + str(self.thresholdSlider.getValue()) + 
						" slice=1 min.=" + self.sizeText.getText() + " max.=24903680 surfaces statistics")
				print params
				self.theImage.resetDisplayRange()
				self.theImage.updateAndDraw()
				IJ.run(self.theImage, "3D Objects Counter", params)
				self.theImage.setImage(backupImage)
				self.theImage.updateAndRepaintWindow()
				surfacesImage = WindowManager.getImage("Surface map of " + self.theImage.getTitle())
				surfacesImage.setRoi(theRoi)
				surfacesImageCut = surfacesImage.duplicate()
				IJ.run(surfacesImageCut,"8-bit","")
				surfacesImageCut = make_image_binary(surfacesImageCut)
				surfacesImageCut.show()
				outputImage.show()
				surfacesImage.close()
				self.theImage.setSlice(self.theImage.getNSlices()/2)
				IJ.run("Merge Channels...", "c2=[" + outputImage.getTitle() + "] c6=[" + surfacesImageCut.getTitle() + "] create ignore")
				self.workRoiCheckbox.setState(False)
			else:
				IJ.showStatus("Select freeform ROI to operate on, or delete to operate on whole image")
				
		else:
			IJ.showStatus("Need to pick an ROI first before running this option")
			self.workRoiCheckbox.setState(False)
Beispiel #10
0
def concatenateImagePlus(files, outfile):
	"""concatenate images contained in files and save in outfile"""
	'''
	if len(files) == 1:
		IJ.log(files[0] + " has only one time point! Nothing to concatenate!")
		return
	'''
	options = ImporterOptions()
	options.setId(files[0])
	options.setVirtual(1)
	options.setOpenAllSeries(1)
	options.setQuiet(1)
	images = BF.openImagePlus(options)
	imageG = images[0]
	nrPositions = len(images)
	options.setOpenAllSeries(0)

	for i in range(0, nrPositions):
		concatImgPlus = IJ.createHyperStack("ConcatFile", imageG.getWidth(), imageG.getHeight(), imageG.getNChannels(), imageG.getNSlices(), len(files), imageG.getBitDepth())
		concatStack = ImageStack(imageG.getWidth(), imageG.getHeight())
		IJ.showStatus("Concatenating files")
		for file in files:
			try:
				IJ.log("	Add file " + file)
				options.setSeriesOn(i,1)
				options.setId(file)
				image = BF.openImagePlus(options)[0]
				imageStack = image.getImageStack()
				sliceNr = imageStack.getSize()
				for j in range(1, sliceNr+1):
					concatStack.addSlice(imageStack.getProcessor(j))
				image.close()
				options.setSeriesOn(i,0)
			except:
				traceback.print_exc()
				IJ.log(file + " failed to concatenate!")
			IJ.showProgress(files.index(file), len(files))
		concatImgPlus.setStack(concatStack)
		concatImgPlus.setCalibration(image.getCalibration())
		if len(images) > 1:
			outfileP = addPositionName(i+1,outfile)
			IJ.saveAs(concatImgPlus, "Tiff",  outfileP)
		else:
			IJ.saveAs(concatImgPlus, "Tiff",  outfile)
		concatImgPlus.close()
	def itemStateChanged(self,e):
		imgList = []
		imgList.append(virginImage)
		for i in range(len(checkboxObjects)):
			if checkboxObjects[i].getState() == True:
				imgList.append(self.boxImages[i])

		titles = WindowManager.getImageTitles()
		p = re.compile(r'^Result')
		for title in titles:
			m = p.search(title)
			if m is not None:
				computedImage = WindowManager.getImage(title)
				computedImage.close()

		IJ.showStatus("Computing...")
		computedImage = reduce(self.addImages,imgList)
		computedImage.show()
		IJ.showStatus("Ready")
Beispiel #12
0
def download_and_untar_url(download_url,target_dir,untarfun,download_file=None,
	download_msg=None):
	'''
	download file in temporary location
	untar to target_dir using untarfun
	clean up download
	'''
	# open url and set up using header information
	u = urllib2.urlopen(download_url)
	headers = u.info()
	download_size = int(headers['Content-Length'])
	if download_file == None:
		if headers.has_key('Content-Disposition'):
			download_file = re.sub(".*filename=","",headers['Content-Disposition'])
		else:
			myErr("No filename specified for download and none in http header!")
	if download_msg==None:
		download_msg='Downloading: %s' % (download_file)
	tf=tempfile.NamedTemporaryFile(suffix=download_file)
	print 'Downloading '+download_url+' to '+ tf.name
	print "Download size should be %d" % (download_size)
	
	from ij import IJ
	
	# Now for the download
	block_size=100000
	if download_size>block_size:
		bytes_read=0
		while bytes_read<download_size:
			IJ.showStatus("%s (%.1f/%.1f Mb)" % 
				(download_msg,(bytes_read/1000000.0),(download_size/1000000.0)))
			IJ.showProgress(bytes_read,download_size)
			tf.file.write(u.read(block_size))
			bytes_read+=block_size
		IJ.showProgress(1.0)
	else:
		tf.file.write(u.read())
	u.close()
	tf.file.close()
	print ('Downloaded file has size %d')%(os.path.getsize(tf.name))
	untarfun(tf.name,target_dir)
	IJ.showStatus('Cleaning up!')
	tf.close()
def stack_median_filter(imp, radius_um=5.0):
	"""perform 2D median filtering slicewise on a stack"""
	t1 = datetime.now();
	stack = imp.getStack();
	title = imp.getTitle();
	n_z = imp.getNSlices();
	progress_inc = 1 if n_z/20 < 1 else n_z/20;
	filt = RankFilters();
	for idx in range(n_z):
		#print("Median filtering stack, {} % complete...".format(100 * round(float(zidx)/n_z, 3)));
		ip = stack.getProcessor(idx+1);
		filt.rank(ip, radius_um, RankFilters.MEDIAN);
		IJ.showProgress(float(idx)/n_z);
		if idx%progress_inc==0:
			IJ.showStatus("Median filtering stack in 2D: {}/{}".format(idx, n_z));
	imp.updateAndDraw();
	imp.setTitle("Median filtered (r={}) {}".format(radius_um, imp.getTitle()).replace(".tif", ""));
	t2 = datetime.now();
	IJ.showProgress(1.0);
	print("Median filtering took {} s".format((t2-t1).total_seconds()));
	return imp;
Beispiel #14
0
 def keyPressed(self, event):
     try:
         dx, dy, dz = self.delta.get(event.getKeyCode(), (0, 0, 0))
         if dx + dy + dz == 0:
             return
         syncPrintQ("Translating source")
         if event.isShiftDown():
             dx *= self.shift
             dy *= self.shift
             dz *= self.shift
         if event.isAltDown():
             dx *= self.alt
             dy *= self.alt
             dz *= self.alt
         syncPrintQ("... by x=%i, y=%i, z=%i" % (dx, dy, dz))
         x, y, z = self.translatable.translate(dx, dy, dz)
         IJ.showStatus("[x=%i y=%i z=%i]" %
                       (x, y, z + 1))  # 1-based stack index
         self.imp.updateAndDraw()
         event.consume()
     except:
         printException()
Beispiel #15
0
	def getProjectData(self):
		'''
		Retrieve the project data of all available projects from the BIAFLOWS server.
		'''
		projects = ProjectCollection().fetch()
		projectData = []
		for i in range(0, projects.size()):
			if (i%2):
				IJ.showStatus('Connecting to: ' + self.biaflows.getHost() + " - please stand by.../")
			else:
				IJ.showStatus('Connecting to: ' + self.biaflows.getHost() + " - please stand by...\\")
			project = projects.get(i)
			name = project.get("name")
			pId = project.get('id')
			try:
				text = Description().fetch(project).get('data')
				text = self.downloadThumbnailsAndReplaceLinks(text)
				message = '\n' + '<h1>' + name + '</h1>' 
				message = message + '\n' + text
				projectData.append({'id': pId, 'name': name, 'message': message})
			except CytomineException, e:
				print(e.getMessage())
				continue
def robust_convertStackToGrayXbit(imp, x=8, normalise=False):
	"""simplified from https://github.com/imagej/imagej1/blob/master/ij/process/StackConverter.java, 
	avoiding complications of scaling based on LUT taken from the current frame. Assumes conversion
	from grayscale image"""
	if x!=8 and x!=16 and x!=32:
		raise NotImplementedError("can't convert to the specified bit depth");
	if imp.getBitDepth()==x:
		return imp;
	if normalise:
		stats = StackStatistics(imp);
		offset = stats.min;
		maxtomin = stats.max - stats.min;
		IJ.run(imp, "Subtract...", "value={} stack".format(offset));
		IJ.run(imp, "Multiply...", "value={} stack".format(float(2**x - 1)/maxtomin));
	current_slice = imp.getCurrentSlice();
	stack = imp.getStack();
	out_stack = ImageStack(imp.getWidth(), imp.getHeight());
	n_z = imp.getNSlices();
	progress_inc = 1 if n_z/20 < 1 else n_z/20;
	for idx in range(n_z):
		# always use 1 as old stack index since we remove a slice at each iteration
		label = stack.getSliceLabel(1);
		ip = stack.getProcessor(1);
		stack.deleteSlice(1);
		if x==8:
			out_stack.addSlice(label, ip.convertToByte(False));
		elif x==16:
			out_stack.addSlice(label, ip.convertToShort(False));
		elif x==32:
			out_stack.addSlice(label, ip.convertToFloat());
		IJ.showProgress(float(idx)/n_z);
		if idx%progress_inc==0:
			IJ.showStatus("Converting stack to {}-bits: {}/{}".format(x, idx, n_z));
	imp.setStack(out_stack);
	IJ.showProgress(1.0);
	imp.setSlice(current_slice);
	return imp;
def regBf(fn=None, imp=None, refId=None):
    """ 
        Register a time series stack to a specified reference slice, 
            from a file (imported by BioFormat) or a stack ImagePlus.
        Returns a registered ImagePlus.
        The stack must have only 1 z layer.
        refId is in the format of [int channel, int slice, int frame]
            If no refId is supplied, will use the first slice [1,1,1]

        Note: since TurboReg is used for registeration, there will be 
            temporary opened image windows.

    """

    ## Prepare the right ImagePlus
    if imp is None:
        if fn is None:
            od = OpenDialog("Choose a file", None)
            filename = od.getFileName()

            if filename is None:
                print "User canceled the dialog!"
                return
            else:
                directory = od.getDirectory()
                filepath = directory + filename
                print "Selected file path:", filepath
        else:
            if os.path.exists(fn) and os.path.isfile(fn):
                filepath = fn
            else:
                print "File does not exist!"
                return

        imps = BF.openImagePlus(filepath)
        imp = imps[0]
        if imp is None:
            print "Cannot load file!"
            return

    else:
        if fn is not None:
            print "File or ImagePlus? Cannot load both."
            return

    width = imp.getWidth()
    height = imp.getHeight()
    # C
    nChannels = imp.getNChannels()
    # Z
    nSlices = imp.getNSlices()
    # T
    nFrames = imp.getNFrames()
    # pixel size
    calibration = imp.getCalibration()

    # Only supoort one z layer
    if nSlices != 1:
        print "Only support 1 slice at Z dimension."
        return

    # set registration reference slice
    if refId is None:
        refC = 1
        refZ = 1
        refT = 1
    else:
        refC = refId[0]
        refZ = refId[1]
        refT = refId[2]
        if (refC not in range(1, nChannels+1) or
            refZ not in range(1, nSlices+1) or
            refT not in range(1, nFrames+1) ):
            print "Invalid reference image!"
            return

    stack = imp.getImageStack()
    registeredStack = ImageStack(width, height, nChannels*nFrames*nSlices)

    # setup windows, these are needed by TurboReg
    tmpip = FloatProcessor(width, height)
    refWin = ImageWindow(ImagePlus("ref", tmpip))
    bounds = refWin.getBounds()
    # refWin.setVisible(False)
    toRegWin = ImageWindow(ImagePlus("toReg", tmpip))
    toRegWin.setLocation(bounds.width + bounds.x, bounds.y)
    # toRegWin.setVisible(False)
    toTransformWin = ImageWindow(ImagePlus("toTransform", tmpip))
    toTransformWin.setLocation(2 * bounds.width + bounds.x, bounds.y)
    # toTransformWin.setVisible(False)

    # get reference image
    refImp = ImagePlus("ref", stack.getProcessor(imp.getStackIndex(refC, refZ, refT)))
    refWin.setImage(refImp)

    tr = TurboReg_()

    for t in xrange(1, nFrames+1):
        IJ.showProgress(t-1, nFrames)

        # print "t ", t
        # do TurboReg on reference channel
        toRegId = imp.getStackIndex(refC, refZ, t)
        toRegImp = ImagePlus("toReg", stack.getProcessor(toRegId))
        toRegWin.setImage(toRegImp)

        regArg =  "-align " +\
                  "-window " + toRegImp.getTitle() + " " +\
                  "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\
                  "-window " + refImp.getTitle() + " " +\
                  "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\
                  "-rigidBody " +\
                  str(width / 2) + " " + str(height / 2) + " " +\
                  str(width / 2) + " " + str(height / 2) + " " +\
                  "0 " + str(height / 2) + " " +\
                  "0 " + str(height / 2) + " " +\
                  str(width - 1) + " " + str(height / 2) + " " +\
                  str(width - 1) + " " + str(height / 2) + " " +\
                  "-hideOutput"
                
        tr = TurboReg_()
        tr.run(regArg)
        registeredImp = tr.getTransformedImage()
        sourcePoints = tr.getSourcePoints()
        targetPoints = tr.getTargetPoints()

        registeredStack.setProcessor(registeredImp.getProcessor(), toRegId)

        # toRegImp.flush()

        # apply transformation on other channels
        for c in xrange(1, nChannels+1):
            # print "c ", c
            if c == refC:
                continue

            toTransformId = imp.getStackIndex(c, 1, t)
            toTransformImp = ImagePlus("toTransform", stack.getProcessor(toTransformId))
            toTransformWin.setImage(toTransformImp)

            transformArg = "-transform " +\
                           "-window " + toTransformImp.getTitle() + " " +\
                           str(width) + " " + str(height) + " " +\
                           "-rigidBody " +\
                           str(sourcePoints[0][0]) + " " +\
                           str(sourcePoints[0][1]) + " " +\
                           str(targetPoints[0][0]) + " " +\
                           str(targetPoints[0][1]) + " " +\
                           str(sourcePoints[1][0]) + " " +\
                           str(sourcePoints[1][1]) + " " +\
                           str(targetPoints[1][0]) + " " +\
                           str(targetPoints[1][1]) + " " +\
                           str(sourcePoints[2][0]) + " " +\
                           str(sourcePoints[2][1]) + " " +\
                           str(targetPoints[2][0]) + " " +\
                           str(targetPoints[2][1]) + " " +\
                           "-hideOutput"

            tr = TurboReg_()
            tr.run(transformArg)
            registeredStack.setProcessor(tr.getTransformedImage().getProcessor(), toTransformId)

            # toTransformImp.flush()
            sourcePoints = None
            targetPoints = None

        IJ.showProgress(t, nFrames)
        IJ.showStatus("Frames registered: " + str(t) + "/" + str(nFrames))

    refWin.close()
    toRegWin.close()
    toTransformWin.close()

    imp2 = ImagePlus("reg_"+imp.getTitle(), registeredStack)
    imp2.setCalibration(imp.getCalibration().copy())
    imp2.setDimensions(nChannels, nSlices, nFrames)
    # print "type ", imp.getType()
    # print "type ", imp2.getType()
    # print nChannels, " ", nSlices, " ", nFrames
    # print registeredStack.getSize()

    for key in imp.getProperties().stringPropertyNames():
        imp2.setProperty(key, imp.getProperty(key))
    # comp = CompositeImage(imp2, CompositeImage.COLOR)  
    # comp.show()
    # imp2 = imp.clone()
    # imp2.setStack(registeredStack)
    # imp2.setTitle("reg"+imp.getTitle())
    # imp2.show()
    # imp.show()

    return imp2
try:
	download_url='https://github.com/jefferis/fiji-cmtk-gui/tarball/master'
	# check date
	installed_version='NA'
	local_version_info=cmtkgui.gui_local_versioninfo()
	if local_version_info.has_key('date'):
		installed_version=local_version_info['date']
	github_version_info=cmtkgui.gui_github_versioninfo()
	update_available=cmtkgui.gui_update_available(github_version_info)

	gd = GenericDialogPlus('Update CMTK GUI')
	if update_available:
		gd.addMessage('CMTK GUI update available')
		gd.setOKLabel("Download")
	else:
		gd.addMessage('CMTK GUI is up to date')

	gd.addMessage('Currently installed CMTK GUI version: '+installed_version)

	gd.showDialog()
	if gd.wasOKed() and update_available:
		# nb url has a suffix to indicate that user agreed to license
		from ij import IJ
		IJ.showStatus('Downloading CMTK GUI')
		cmtkgui.download_and_untar_url(download_url,cmtkgui.gui_install_dir(),untar_github_archive)
		cmtkgui.gui_write_local_versioninfo(github_version_info)
except SystemExit, e:
	from ij import IJ
	IJ.showStatus(str(e))
Beispiel #19
0
    regparams = gd.getNextChoice()
    print regparams
    regparams = gd.getNextString()
    mungeropts = gd.getNextString()
    action = gd.getNextChoice()

    if action == 'Test': mungeropts += ' -t'
    if verbose: mungeropts += ' -v'
    mungeropts += ' -T %d' % (int(corestouse))

    if not outsuffix == '':
        mungeropts += ' -d .' + outsuffix

    cmd = '"%s" -b "%s" %s %s %s -s "%s" %s' % (
        munger, bindir, munger_actions, regparams, mungeropts, refBrain, image)
    print cmd

    if action != 'Test':
        # make a script
        script = makescript(cmd,
                            rootDir,
                            outdir=os.path.join(rootDir, 'commands'))
        print 'script is %s' % (script)

        if action != 'Write Script':
            # Actually run the script
            subprocess.call(script, shell=False)
except SystemExit, e:
    from ij import IJ
    IJ.showStatus(str(e))
Beispiel #20
0
def run(title):
    gd = GenericDialog("Record Window")
    gd.addMessage("Maximum number of frames to record.\nZero means infinite, interrupt with ESC key.")
    gd.addNumericField("Max. frames:", 50, 0)
    gd.addNumericField("Milisecond interval:", 300, 0)
    gd.addSlider("Start in (seconds):", 0, 20, 5)
    frames = []
    titles = []
    for f in Frame.getFrames():
        if f.isEnabled() and f.isVisible():
            frames.append(f)
            titles.append(f.getTitle())
    gd.addChoice("Window:", titles, titles[0])
    gd.addCheckbox("To file", False)
    gd.showDialog()
    if gd.wasCanceled():
        return
    n_frames = int(gd.getNextNumber())
    interval = gd.getNextNumber() / 1000.0  # in seconds
    frame = frames[gd.getNextChoiceIndex()]
    delay = int(gd.getNextNumber())
    tofile = gd.getNextBoolean()

    dir = None
    if tofile:
        dc = DirectoryChooser("Directory to store image frames")
        dir = dc.getDirectory()
        if dir is None:
            return  # dialog canceled

    snaps = []
    borders = None
    executors = Executors.newFixedThreadPool(1)
    try:
        while delay > 0:
            IJ.showStatus("Starting in " + str(delay) + "s.")
            time.sleep(1)  # one second
            delay -= 1

        IJ.showStatus("Capturing frame borders...")
        bounds = frame.getBounds()
        robot = Robot()
        frame.toFront()
        time.sleep(0.5)  # half a second
        borders = robot.createScreenCapture(bounds)

        IJ.showStatus("Recording " + frame.getTitle())

        # Set box to the inside borders of the frame
        insets = frame.getInsets()
        box = bounds.clone()
        box.x = insets.left
        box.y = insets.top
        box.width -= insets.left + insets.right
        box.height -= insets.top + insets.bottom

        start = System.currentTimeMillis() / 1000.0  # in seconds
        last = start
        intervals = []
        real_interval = 0
        i = 1
        fus = None
        if tofile:
            fus = []

            # 0 n_frames means continuous acquisition
        while 0 == n_frames or (len(snaps) < n_frames and last - start < n_frames * interval):
            now = System.currentTimeMillis() / 1000.0  # in seconds
            real_interval = now - last
            if real_interval >= interval:
                last = now
                img = snapshot(frame, box)
                if tofile:
                    fus.append(executors.submit(Saver(i, dir, bounds, borders, img, insets)))  # will flush img
                    i += 1
                else:
                    snaps.append(img)
                intervals.append(real_interval)
            else:
                time.sleep(interval / 5)
                # interrupt capturing:
            if IJ.escapePressed():
                IJ.showStatus("Recording user-interrupted")
                break

                # debug:
                # print "insets:", insets
                # print "bounds:", bounds
                # print "box:", box
                # print "snap dimensions:", snaps[0].getWidth(), snaps[0].getHeight()

                # Create stack
        stack = None
        if tofile:
            for fu in snaps:
                fu.get()  # wait on all
            stack = VirtualStack(bounds.width, bounds.height, None, dir)
            files = File(dir).list(TifFilter())
            Arrays.sort(files)
            for f in files:
                stack.addSlice(f)
        else:
            stack = ImageStack(bounds.width, bounds.height, None)
            t = 0
            for snap, real_interval in zip(snaps, intervals):
                bi = BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB)
                g = bi.createGraphics()
                g.drawImage(borders, 0, 0, None)
                g.drawImage(snap, insets.left, insets.top, None)
                stack.addSlice(str(IJ.d2s(t, 3)), ImagePlus("", bi).getProcessor())
                t += real_interval
                snap.flush()
                bi.flush()

        borders.flush()

        ImagePlus(frame.getTitle() + " recording", stack).show()
        IJ.showStatus("Done recording " + frame.getTitle())
    except Exception, e:
        print "Some error ocurred:"
        print e.printStackTrace()
        IJ.showStatus("")
        if borders is not None:
            borders.flush()
        for snap in snaps:
            snap.flush()
Beispiel #21
0
    # Create a CSV table documenting processed files
    csvPath = out_dir + "_ProcessedFileList.csv"
    csvExists = os.path.exists(csvPath)
    csvFile = open(csvPath, 'a')
    csvWriter = csv.writer(csvFile)

    # Specify column headings
    if not csvExists:
        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()
		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
	ys = find_tile_range(ymin,ymax,rowStarts)
	tiles = make_tile_series(xs,ys,xtiles,ytiles)
	print tiles

	# 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 ######
Beispiel #24
0
def run(title):
    gd = GenericDialog('Record Window')
    gd.addMessage(
        "Maximum number of frames to record.\nZero means infinite, interrupt with ESC key."
    )
    gd.addNumericField('Max. frames:', 50, 0)
    gd.addNumericField('Milisecond interval:', 300, 0)
    gd.addSlider('Start in (seconds):', 0, 20, 5)
    frames = []
    titles = []
    for f in Frame.getFrames():
        if f.isEnabled() and f.isVisible():
            frames.append(f)
            titles.append(f.getTitle())
    gd.addChoice('Window:', titles, titles[0])
    gd.addCheckbox("To file", False)
    gd.showDialog()
    if gd.wasCanceled():
        return
    n_frames = int(gd.getNextNumber())
    interval = gd.getNextNumber() / 1000.0  # in seconds
    frame = frames[gd.getNextChoiceIndex()]
    delay = int(gd.getNextNumber())
    tofile = gd.getNextBoolean()

    dir = None
    if tofile:
        dc = DirectoryChooser("Directory to store image frames")
        dir = dc.getDirectory()
        if dir is None:
            return  # dialog canceled

    snaps = []
    borders = None
    executors = Executors.newFixedThreadPool(1)
    try:
        while delay > 0:
            IJ.showStatus('Starting in ' + str(delay) + 's.')
            time.sleep(1)  # one second
            delay -= 1

        IJ.showStatus('Capturing frame borders...')
        bounds = frame.getBounds()
        robot = Robot()
        frame.toFront()
        time.sleep(0.5)  # half a second
        borders = robot.createScreenCapture(bounds)

        IJ.showStatus("Recording " + frame.getTitle())

        # Set box to the inside borders of the frame
        insets = frame.getInsets()
        box = bounds.clone()
        box.x = insets.left
        box.y = insets.top
        box.width -= insets.left + insets.right
        box.height -= insets.top + insets.bottom

        start = System.currentTimeMillis() / 1000.0  # in seconds
        last = start
        intervals = []
        real_interval = 0
        i = 1
        fus = None
        if tofile:
            fus = []

        # 0 n_frames means continuous acquisition
        while 0 == n_frames or (len(snaps) < n_frames
                                and last - start < n_frames * interval):
            now = System.currentTimeMillis() / 1000.0  # in seconds
            real_interval = now - last
            if real_interval >= interval:
                last = now
                img = snapshot(frame, box)
                if tofile:
                    fus.append(
                        executors.submit(
                            Saver(i, dir, bounds, borders, img,
                                  insets)))  # will flush img
                    i += 1
                else:
                    snaps.append(img)
                intervals.append(real_interval)
            else:
                time.sleep(interval / 5)
            # interrupt capturing:
            if IJ.escapePressed():
                IJ.showStatus("Recording user-interrupted")
                break

        # debug:
        #print "insets:", insets
        #print "bounds:", bounds
        #print "box:", box
        #print "snap dimensions:", snaps[0].getWidth(), snaps[0].getHeight()

        # Create stack
        stack = None
        if tofile:
            for fu in snaps:
                fu.get()  # wait on all
            stack = VirtualStack(bounds.width, bounds.height, None, dir)
            files = File(dir).list(TifFilter())
            Arrays.sort(files)
            for f in files:
                stack.addSlice(f)
        else:
            stack = ImageStack(bounds.width, bounds.height, None)
            t = 0
            for snap, real_interval in zip(snaps, intervals):
                bi = BufferedImage(bounds.width, bounds.height,
                                   BufferedImage.TYPE_INT_RGB)
                g = bi.createGraphics()
                g.drawImage(borders, 0, 0, None)
                g.drawImage(snap, insets.left, insets.top, None)
                stack.addSlice(str(IJ.d2s(t, 3)),
                               ImagePlus('', bi).getProcessor())
                t += real_interval
                snap.flush()
                bi.flush()

        borders.flush()

        ImagePlus(frame.getTitle() + " recording", stack).show()
        IJ.showStatus('Done recording ' + frame.getTitle())
    except Exception, e:
        print "Some error ocurred:"
        print e.printStackTrace()
        IJ.showStatus('')
        if borders is not None: borders.flush()
        for snap in snaps:
            snap.flush()
Beispiel #25
0
def regBf(fn=None, imp=None, refId=None):
    """ 
        Register a time series stack to a specified reference slice, 
            from a file (imported by BioFormat) or a stack ImagePlus.
        Returns a registered ImagePlus.
        The stack must have only 1 z layer.
        refId is in the format of [int channel, int slice, int frame]
            If no refId is supplied, will use the first slice [1,1,1]

        Note: since TurboReg is used for registeration, there will be 
            temporary opened image windows.

    """

    ## Prepare the right ImagePlus
    if imp is None:
        if fn is None:
            od = OpenDialog("Choose a file", None)
            filename = od.getFileName()

            if filename is None:
                print "User canceled the dialog!"
                return
            else:
                directory = od.getDirectory()
                filepath = directory + filename
                print "Selected file path:", filepath
        else:
            if os.path.exists(fn) and os.path.isfile(fn):
                filepath = fn
            else:
                print "File does not exist!"
                return

        imps = BF.openImagePlus(filepath)
        imp = imps[0]
        if imp is None:
            print "Cannot load file!"
            return

    else:
        if fn is not None:
            print "File or ImagePlus? Cannot load both."
            return

    width = imp.getWidth()
    height = imp.getHeight()
    # C
    nChannels = imp.getNChannels()
    # Z
    nSlices = imp.getNSlices()
    # T
    nFrames = imp.getNFrames()
    # pixel size
    calibration = imp.getCalibration()

    # Only supoort one z layer
    if nSlices != 1:
        print "Only support 1 slice at Z dimension."
        return

    # set registration reference slice
    if refId is None:
        refC = 1
        refZ = 1
        refT = 1
    else:
        refC = refId[0]
        refZ = refId[1]
        refT = refId[2]
        if (refC not in range(1, nChannels + 1)
                or refZ not in range(1, nSlices + 1)
                or refT not in range(1, nFrames + 1)):
            print "Invalid reference image!"
            return

    stack = imp.getImageStack()
    registeredStack = ImageStack(width, height, nChannels * nFrames * nSlices)

    # setup windows, these are needed by TurboReg
    tmpip = FloatProcessor(width, height)
    refWin = ImageWindow(ImagePlus("ref", tmpip))
    bounds = refWin.getBounds()
    # refWin.setVisible(False)
    toRegWin = ImageWindow(ImagePlus("toReg", tmpip))
    toRegWin.setLocation(bounds.width + bounds.x, bounds.y)
    # toRegWin.setVisible(False)
    toTransformWin = ImageWindow(ImagePlus("toTransform", tmpip))
    toTransformWin.setLocation(2 * bounds.width + bounds.x, bounds.y)
    # toTransformWin.setVisible(False)

    # get reference image
    refImp = ImagePlus("ref",
                       stack.getProcessor(imp.getStackIndex(refC, refZ, refT)))
    refWin.setImage(refImp)

    tr = TurboReg_()

    for t in xrange(1, nFrames + 1):
        IJ.showProgress(t - 1, nFrames)

        # print "t ", t
        # do TurboReg on reference channel
        toRegId = imp.getStackIndex(refC, refZ, t)
        toRegImp = ImagePlus("toReg", stack.getProcessor(toRegId))
        toRegWin.setImage(toRegImp)

        regArg =  "-align " +\
                  "-window " + toRegImp.getTitle() + " " +\
                  "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\
                  "-window " + refImp.getTitle() + " " +\
                  "0 0 " + str(width - 1) + " " + str(height - 1) + " " +\
                  "-rigidBody " +\
                  str(width / 2) + " " + str(height / 2) + " " +\
                  str(width / 2) + " " + str(height / 2) + " " +\
                  "0 " + str(height / 2) + " " +\
                  "0 " + str(height / 2) + " " +\
                  str(width - 1) + " " + str(height / 2) + " " +\
                  str(width - 1) + " " + str(height / 2) + " " +\
                  "-hideOutput"

        tr = TurboReg_()
        tr.run(regArg)
        registeredImp = tr.getTransformedImage()
        sourcePoints = tr.getSourcePoints()
        targetPoints = tr.getTargetPoints()

        registeredStack.setProcessor(registeredImp.getProcessor(), toRegId)

        # toRegImp.flush()

        # apply transformation on other channels
        for c in xrange(1, nChannels + 1):
            # print "c ", c
            if c == refC:
                continue

            toTransformId = imp.getStackIndex(c, 1, t)
            toTransformImp = ImagePlus("toTransform",
                                       stack.getProcessor(toTransformId))
            toTransformWin.setImage(toTransformImp)

            transformArg = "-transform " +\
                           "-window " + toTransformImp.getTitle() + " " +\
                           str(width) + " " + str(height) + " " +\
                           "-rigidBody " +\
                           str(sourcePoints[0][0]) + " " +\
                           str(sourcePoints[0][1]) + " " +\
                           str(targetPoints[0][0]) + " " +\
                           str(targetPoints[0][1]) + " " +\
                           str(sourcePoints[1][0]) + " " +\
                           str(sourcePoints[1][1]) + " " +\
                           str(targetPoints[1][0]) + " " +\
                           str(targetPoints[1][1]) + " " +\
                           str(sourcePoints[2][0]) + " " +\
                           str(sourcePoints[2][1]) + " " +\
                           str(targetPoints[2][0]) + " " +\
                           str(targetPoints[2][1]) + " " +\
                           "-hideOutput"

            tr = TurboReg_()
            tr.run(transformArg)
            registeredStack.setProcessor(
                tr.getTransformedImage().getProcessor(), toTransformId)

            # toTransformImp.flush()
            sourcePoints = None
            targetPoints = None

        IJ.showProgress(t, nFrames)
        IJ.showStatus("Frames registered: " + str(t) + "/" + str(nFrames))

    refWin.close()
    toRegWin.close()
    toTransformWin.close()

    imp2 = ImagePlus("reg_" + imp.getTitle(), registeredStack)
    imp2.setCalibration(imp.getCalibration().copy())
    imp2.setDimensions(nChannels, nSlices, nFrames)
    # print "type ", imp.getType()
    # print "type ", imp2.getType()
    # print nChannels, " ", nSlices, " ", nFrames
    # print registeredStack.getSize()

    for key in imp.getProperties().stringPropertyNames():
        imp2.setProperty(key, imp.getProperty(key))
    # comp = CompositeImage(imp2, CompositeImage.COLOR)
    # comp.show()
    # imp2 = imp.clone()
    # imp2.setStack(registeredStack)
    # imp2.setTitle("reg"+imp.getTitle())
    # imp2.show()
    # imp.show()

    return imp2
Beispiel #26
0
#for cell in listfilescells :
f1 = open(rootdir+now+"-R1-MT.txt", "w")
tab="\t"
f1.write("cell"+tab+"maxFrames"+tab+"maxcumul"+tab+"nrevs"+"\n")

for cle in listcellname :
	rm.runCommand("reset")
	#cle = cell.rsplit("/", 1)[1][:-len(".cell")]
	#cles.append(cle)
	rm.runCommand("Open", dictRois[cle])
	rm.runCommand("Show None")
	RawroisArray=rm.getRoisAsArray()
	if len(RawroisArray)< minLife : continue
	roisArray=[RawroisArray[i] for i in range(0,len(RawroisArray), subs)]
	IJ.showStatus(cle)
	IJ.showProgress(listcellname.index(cle), len(listcellname)) 

	dxA=[]
	dyA=[]
	dxB=[]
	dyB=[]
	dA=[]
	dB=[]

	sensA = 1
	sensB = -1
	nrev = 0
	
	color=colors.pop(0)
	colorA=color.brighter()
	verbose=gd.getNextBoolean()
	corestouse=gd.getNextNumber()
	outsuffix=gd.getNextString()
	regparams=gd.getNextChoice()
	print regparams
	regparams=gd.getNextString()
	mungeropts=gd.getNextString()
	action=gd.getNextChoice()

	if action == 'Test': mungeropts+=' -t'
	if verbose: mungeropts+=' -v'
	mungeropts+=' -T %d' % (int(corestouse))

	if not outsuffix == '':
		mungeropts += ' -d .'+outsuffix

	cmd='"%s" -b "%s" %s %s %s -s "%s" %s' % (munger,bindir,munger_actions,regparams,mungeropts,refBrain,image)
	print cmd

	if action !='Test':
		# make a script
		script=makescript(cmd,rootDir,outdir=os.path.join(rootDir,'commands'))
		print 'script is %s' % (script)
	
		if action != 'Write Script':
			# Actually run the script
			subprocess.call(script,shell=False)
except SystemExit, e:
	from ij import IJ
	IJ.showStatus(str(e))
	scale_info = estimate_scale_multiplier(parentLSMFilePath+"_tiles/tile_1.ome.tif",parentLSMFilePath+"_tiles/resized/tile_1.tif")
	print scale_info
	coords_list = read_tileconfig_file(tileConfigFilePath)
	coords_normed = normalize_coords_in_list(coords_list)
	coords_upscaled = round_coords(upscale_coords(coords_normed,scale_info[0]))
	write_tileconfig_file(parentLSMFilePath+"_tiles/v_img/TileConfiguration.fullsize.txt",coords_upscaled,".ome.tif")
	max_coords = get_max_coordinates(coords_upscaled)
	print max_coords
	print basic_info

	## 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)			
Beispiel #29
0
def show_status(msg):
    """Wrapper to update the ImageJ status bar and the log simultaneously."""
    log.info(msg)
    IJ.showStatus(msg)
def main_interactive():
    """The main routine for running interactively."""
    log.info('Running in interactive mode.')
    (base, fname) = ui_get_input_file()
    if (base is None):
        return
    log.warn("Parsing project file: %s" % (base + fname))
    IJ.showStatus("Parsing experiment file...")
    mosaics = fv.FluoViewMosaic(join(base, fname), runparser=False)
    IJ.showStatus("Parsing mosaics...")
    progress = 0.0
    count = len(mosaics.mosaictrees)
    step = 1.0 / count
    for subtree in mosaics.mosaictrees:
        IJ.showProgress(progress)
        mosaics.add_mosaic(subtree)
        progress += step
    IJ.showProgress(progress)
    IJ.showStatus("Parsed %i mosaics." % len(mosaics))
    dialog = GenericDialog('FluoView OIF / OIB Stitcher')
    if len(mosaics) == 0:
        msg = ("Couldn't find any (valid) mosaics in the project file.\n"
               " \n"
               "Please make sure to have all files available!\n"
               " \n"
               "Will stop now.\n")
        log.warn(msg)
        dialog.addMessage(msg)
        dialog.showDialog()
        return
    msg = "------------------------ EXPORT OPTIONS ------------------------"
    dialog.addMessage(msg)
    formats = ["OME-TIFF", "ICS/IDS"]
    dialog.addChoice("Export Format", formats, formats[0])
    dialog.addCheckbox("separate files by Z slices (OME-TIFF only)?", False)
    msg = "------------------------ EXPORT OPTIONS ------------------------"
    dialog.addMessage(msg)
    dialog.addMessage("")
    dialog.addMessage("")
    msg = gen_mosaic_details(mosaics)
    log.warn(msg)
    msg += "\n \nPress [OK] to write tile configuration files\n"
    msg += "and continue with running the stitcher."
    dialog.addMessage(msg)
    dialog.showDialog()

    opts = {}
    if dialog.getNextChoice() == 'ICS/IDS':
        opts['export_format'] = '".ids"'
    else:
        opts['export_format'] = '".ome.tif"'
        if dialog.getNextBoolean() == True:
            opts['split_z_slices'] = 'true'
    code = imagej.gen_stitching_macro_code(mosaics, 'templates/stitching',
                                           path=base, tplpath=imcftpl, opts=opts)
    log.warn("============= generated macro code =============")
    log.warn(flatten(code))
    log.warn("============= end of generated  macro code =============")

    if dialog.wasOKed():
        log.warn('Writing stitching macro.')
        imagej.write_stitching_macro(code, fname='stitch_all.ijm', dname=base)
        log.warn('Writing tile configuration files.')
        imagej.write_all_tile_configs(mosaics, fixsep=True)
        log.warn('Launching stitching macro.')
        IJ.runMacro(flatten(code))
try:
    download_url = 'https://github.com/jefferis/fiji-cmtk-gui/tarball/master'
    # check date
    installed_version = 'NA'
    local_version_info = cmtkgui.gui_local_versioninfo()
    if local_version_info.has_key('date'):
        installed_version = local_version_info['date']
    github_version_info = cmtkgui.gui_github_versioninfo()
    update_available = cmtkgui.gui_update_available(github_version_info)

    gd = GenericDialogPlus('Update CMTK GUI')
    if update_available:
        gd.addMessage('CMTK GUI update available')
        gd.setOKLabel("Download")
    else:
        gd.addMessage('CMTK GUI is up to date')

    gd.addMessage('Currently installed CMTK GUI version: ' + installed_version)

    gd.showDialog()
    if gd.wasOKed() and update_available:
        # nb url has a suffix to indicate that user agreed to license
        from ij import IJ
        IJ.showStatus('Downloading CMTK GUI')
        cmtkgui.download_and_untar_url(download_url, cmtkgui.gui_install_dir(),
                                       untar_github_archive)
        cmtkgui.gui_write_local_versioninfo(github_version_info)
except SystemExit, e:
    from ij import IJ
    IJ.showStatus(str(e))
Beispiel #32
0
	def __fmeasures(self) : 
		self.__Cutoff = float(self.__display4.text)
		nslices = self.__impRes.getImageStackSize() 
		rt = ResultsTable()
		rt.show("RT-"+self.__name)
		if self.__maxfinder : twpoints = TextWindow("points-"+self.__name, "index\tlabel\tname\tx\ty\taxis\tcellw\tcellh", "", 200, 450)
		twlabels = TextWindow("labels-"+self.__name, "index\tlabel\tname\tnpoints", "", 200, 450)

		isres = self.__impRes.getImageStack()
		
		for index in range(1, nslices+1):
			pc = (index*100)/nslices
			IJ.showStatus("Je suis a "+str(pc)+"%")
			self.__impRes.setSlice(index)
			self.__impRes.killRoi()
			roi = self.__listrois[index-1]
			self.__impRes.setRoi(roi)
			analyser= Analyzer(self.__impRes, Analyzer.LABELS+Analyzer.CENTER_OF_MASS+Analyzer.CENTROID+Analyzer.INTEGRATED_DENSITY+Analyzer.MEAN+Analyzer.KURTOSIS+Analyzer.SKEWNESS+Analyzer.MIN_MAX+Analyzer.SLICE+Analyzer.STACK_POSITION+Analyzer.STD_DEV, rt)
			analyser.measure()
			rt.show("RT-"+self.__name)
			
			rect=roi.getBounds()
			ip = self.__impRes.getProcessor()

			xCoord = []
			yCoord = []
			currentPixel = []

			m00 = 0.00
			m10 = 0.00
			m01 = 0.00
			
			mc20 = 0.00
			mc02 = 0.00
			mc11 = 0.00
			mc30 = 0.00
			mc03 = 0.00
			mc21 = 0.00
			mc12 = 0.00
			mc40 = 0.00
			mc04 = 0.00
			mc31 = 0.00
			mc13 = 0.00

			mm20 = 0.00
			mm02 = 0.00
			mm11 = 0.00
			mm30 = 0.00
			mm03 = 0.00
			mm21 = 0.00
			mm12 = 0.00
			mm40 = 0.00
			mm04 = 0.00
			mm31 = 0.00
			mm13 = 0.00
			
			
			#for y in range(rect.y, rect.y+rect.height, 1) :
			#	for x in range(rect.x, rect.x+rect.width, 1) :
			#		xCoord.append(x+0.5)
			#		yCoord.append(y+0.5)
			#		#pixel=ip.getf(x,y)-self.__Cutoff
			#		pixel = ip.getPixelValue(x,y)-self.__Cutoff
			#		if pixel < 0 : pixel = 0
			#		currentPixel.append(pixel)
			#		m00 += currentPixel[-1]
			#		m10 += currentPixel[-1]*xCoord[-1]
			#		m01 += currentPixel[-1]*yCoord[-1]


			#xm = m10/(m00+0.00000001)
			#ym = m01/(m00+0.00000001)

			#xc = rect.width/2.00
			#yc = rect.height/2.00

			#for i in range(rect.width*rect.height) :

			#	xcrel = xCoord[i]-xc
			#	ycrel = yCoord[i]-yc
			
			#	#mc20 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc)
			#	#mc02 += currentPixel[i]*(yCoord[i]-yc)*(yCoord[i]-yc)
			#	#mc11 += currentPixel[i]*(xCoord[i]-xc)*(yCoord[i]-yc)
			#	#
			#	#mc30 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc)*(xCoord[i]-xc)
			#	#mc03 += currentPixel[i]*(yCoord[i]-yc)*(yCoord[i]-yc)*(yCoord[i]-yc)
			#	#mc21 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc)*(yCoord[i]-yc)
			#	#mc12 += currentPixel[i]*(xCoord[i]-xc)*(yCoord[i]-yc)*(yCoord[i]-yc)
			#	#
			#	#mc40 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc)*(xCoord[i]-xc)*(xCoord[i]-xc)
			#	#mc04 += currentPixel[i]*(yCoord[i]-yc)*(yCoord[i]-yc)*(yCoord[i]-yc)*(yCoord[i]-yc)
			#	#mc31 += currentPixel[i]*(xCoord[i]-xc)*(xCoord[i]-xc)*(xCoord[i]-xc)*(yCoord[i]-yc)
			#	#mc13 += currentPixel[i]*(xCoord[i]-xc)*(yCoord[i]-yc)*(yCoord[i]-yc)*(yCoord[i]-yc)

			#	mc20 += currentPixel[i]*xcrel*xcrel
			#	mc02 += currentPixel[i]*ycrel*ycrel
			#	mc11 += currentPixel[i]*xcrel*ycrel
				
			#	mc30 += currentPixel[i]*xcrel*xcrel*xcrel
			#	mc03 += currentPixel[i]*ycrel*ycrel*ycrel
			#	mc21 += currentPixel[i]*xcrel*xcrel*ycrel
			#	mc12 += currentPixel[i]*xcrel*ycrel*ycrel
				
			#	mc40 += currentPixel[i]*xcrel*xcrel*xcrel*xcrel
			#	mc04 += currentPixel[i]*ycrel*ycrel*ycrel*ycrel
			#	mc31 += currentPixel[i]*xcrel*xcrel*xcrel*ycrel
			#	mc13 += currentPixel[i]*xcrel*ycrel*ycrel*ycrel

			
			#for i in range(rect.width*rect.height) :
			#	mm20 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm)
			#	mm02 += currentPixel[i]*(yCoord[i]-ym)*(yCoord[i]-ym)
			#	mm11 += currentPixel[i]*(xCoord[i]-xm)*(yCoord[i]-ym)

			#	mm30 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm)*(xCoord[i]-xm)
			#	mm03 += currentPixel[i]*(yCoord[i]-ym)*(yCoord[i]-ym)*(yCoord[i]-ym)
			#	mm21 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm)*(yCoord[i]-ym)
			#	mm12 += currentPixel[i]*(xCoord[i]-xm)*(yCoord[i]-ym)*(yCoord[i]-ym)

			#	mm40 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm)*(xCoord[i]-xm)*(xCoord[i]-xm)
			#	mm04 += currentPixel[i]*(yCoord[i]-ym)*(yCoord[i]-ym)*(yCoord[i]-ym)*(yCoord[i]-ym)
			#	mm31 += currentPixel[i]*(xCoord[i]-xm)*(xCoord[i]-xm)*(xCoord[i]-xm)*(yCoord[i]-ym)
			#	mm13 += currentPixel[i]*(xCoord[i]-xm)*(yCoord[i]-ym)*(yCoord[i]-ym)*(yCoord[i]-ym)

			
			
			#xxcVar = mc20/m00
			#yycVar = mc02/m00
			#xycVar = mc11/m00

			#xcSkew = mc30/(m00 * math.pow(xxcVar,(3.0/2.0)))
			#ycSkew = mc03/(m00 * math.pow(yycVar,(3.0/2.0)))

			#xcKurt = mc40 / (m00 * math.pow(xxcVar,2.0)) - 3.0
			#ycKurt = mc04 / (m00 * math.pow(yycVar,2.0)) - 3.0

			#ecc = (math.pow((mc20-mc02),2.0)+(4.0*mc11*mc11))/m00
			
			#xxmVar = mm20/m00
			#yymVar = mm02/m00
			#xymVar = mm11/m00

			#xmSkew = mm30/(m00 * math.pow(xxmVar,(3.0/2.0)))
			#ymSkew = mm03/(m00 * math.pow(yymVar,(3.0/2.0)))

			#xmKurt = mm40 / (m00 * math.pow(xxmVar,2.0)) - 3.0
			#ymKurt = mm04 / (m00 * math.pow(yymVar,2.0)) - 3.0

			#ecm = (math.pow((mm20-mm02),2.0)+(4.0*mm11*mm11))/m00

			#rt.addValue("xxcVar", xxcVar)
			#rt.addValue("yycVar", yycVar)
			#rt.addValue("xycVar", xycVar)

			#rt.addValue("xcSkew", xcSkew)
			#rt.addValue("ycSkew", ycSkew)

			#rt.addValue("xcKurt", xcKurt)
			#rt.addValue("ycKurt", ycKurt)

			#rt.addValue("Ecc", ecc)

			#rt.addValue("xxmVar", xxmVar)
			#rt.addValue("yymVar", yymVar)
			#rt.addValue("xymVar", xymVar)

			#rt.addValue("xmSkew", xmSkew)
			#rt.addValue("ymSkew", ymSkew)

			#rt.addValue("xmKurt", xmKurt)
			#rt.addValue("ymKurt", ymKurt)

			#rt.addValue("Ecm", ecm)

			rt.addValue("roiw", rect.width)
			rt.addValue("roih", rect.height)

			rt.addValue("cellw", self.__ipw[index-1])
			rt.addValue("cellh", self.__iph[index-1])

			self.__impRes.killRoi()

			xCoord[:] = []
			yCoord[:] = []
			currentPixel[:] = []
			points = []
			points[:] = []
			npointsmax = 0
			
			#lab = self.__labels[index-1]
			nameroi = self.__dictCells[index][0]
			lab = self.__dictCells[index][1]

			if self.__maxfinder : 
				self.__impMax.setSlice(index)
				ipmax = self.__impMax.getProcessor()
				for y in range(ipmax.getHeight()) :
					for x in range(ipmax.getWidth()) :
						if ipmax.getPixelValue(x,y) > 0 : 
							twpoints.append(str(index)+"\t"+lab+"\t"+nameroi+"\t"+str(x)+"\t"+str(y)+"\t"+str(self.__cellsrois[index-1][0].getLength())+"\t"+str(self.__ipw[index-1])+"\t"+str(self.__iph[index-1]))
							npointsmax+=1
				rt.addValue("npoints", npointsmax)

			twlabels.append(str(index)+"\t"+lab+"\t"+nameroi+"\t"+str(npointsmax))
			rt.show("RT-"+self.__name)
			
		rt.show("RT-"+self.__name)