示例#1
0
def generate_limit_labels(imp, limits, cb_fraction, params):
    """generate text ROIs in correct positions to label colorbar"""
    rois = []
    w = imp.getWidth()
    h = imp.getHeight()
    txt_h_px = float(h) / 15
    txt_sz_pt = int(round((18.0 / 24.0) * txt_h_px))
    for limit in limits:
        roi = TextRoi(1, 1, str(round(limit, 3)),
                      Font("SansSerif", Font.ITALIC, txt_sz_pt))
        roi.setJustification(TextRoi.RIGHT)
        roi.setFillColor(Color.BLACK)
        roi.setStrokeColor(Color.WHITE)
        rois.append(roi)
    roim = RoiManager(False)
    roim.reset()
    imp.show()
    mbui.autoset_zoom(imp)
    for fridx in range(1, imp.getNSlices() + 1):
        imp.setPosition(fridx)
        roi_uu = rois[1].clone()
        xpos = w - cb_fraction * w - float(w) / 100 - rois[1].getFloatWidth()
        roi_uu.setLocation(xpos, 1)
        imp.setRoi(roi_uu)
        roim.addRoi(roi_uu)
        roi_ll = rois[0].clone()
        roi_ll.setLocation(xpos, h - rois[0].getFloatHeight())
        imp.setRoi(roi_ll)
        roim.addRoi(roi_ll)
    roim.runCommand("Show All")
    FileSaver(imp).saveAsTiff(
        os.path.join(params.output_path,
                     "overlaid curvature nudged labels.tif"))
    # nudge positions
    roim.reset()
    imp.killRoi()
    for fridx in range(1, imp.getNSlices() + 1):
        imp.setPosition(fridx)
        roi_uu = rois[1].clone()
        xpos = w - cb_fraction * w - float(w) / 100
        roi_uu.setLocation(xpos, 1)
        imp.setRoi(roi_uu)
        roim.addRoi(roi_uu)
        roi_ll = rois[0].clone()
        roi_ll.setLocation(xpos, h - rois[0].getFloatHeight())
        imp.setRoi(roi_ll)
        roim.addRoi(roi_ll)
    roim.runCommand("Show All")
    FileSaver(imp).saveAsTiff(
        os.path.join(params.output_path, "overlaid curvature.tif"))
    return imp
def main():
    # ensure consistent preference settings
    Prefs.blackBackground = False

    # get locations for previous and new outputs
    params = Parameters()
    params.loadLastParams()
    output_folder_old, output_folder = mbio.rerun_location_chooser(
        params.input_image_path)
    params.loadParametersFromJson(
        os.path.join(output_folder_old, 'parameters used.json'))
    params.setOutputPath(output_folder)

    # present user with the familiar setup UI, with options that don't make sense/aren't yet implemented disabled
    params = mbui.analysis_parameters_gui(rerun_analysis=True, params=params)

    # get original image file (for overlays etc.)
    if not os.path.isfile(params.input_image_path):
        mbui.warning_dialog([
            "The original data can't be found at the location specified in saved parameters. ",
            "(Possibly something as simple as a change in network drive mapping has occurred)",
            "Please specify the location of the original image file..."
        ])
        params.setInputImagePath(
            mbio.input_file_location_chooser(params.output_path))

    import_opts, params = mbui.choose_series(params.input_image_path, params)
    imps = bf.openImagePlus(import_opts)
    imp = imps[0]

    if imp.getNSlices() > 1:
        mbui.warning_dialog([
            "More than one Z plane detected.",
            "I will do a maximum projection before proceeding", "Continue?"
        ])
        imp = ZProjector.run(imp, "max all")

    params = mbio.get_metadata(params)
    params.setCurvatureLengthUm(
        round(params.curvature_length_um / params.pixel_physical_size) *
        params.pixel_physical_size)
    params.persistParameters()
    IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel")
    imp.show()
    if imp.getNChannels() > 1:
        imp.setPosition(params.membrane_channel_number, 1, 1)
    mbui.autoset_zoom(imp)
    IJ.run("Enhance Contrast", "saturated=0.35")

    # prompt user to select ROI
    original_imp = Duplicator().run(imp)
    _, crop_params = mbui.crop_to_ROI(imp, params)
    imp.show()

    if crop_params is not None:
        params.perform_spatial_crop = True
        mbui.autoset_zoom(imp)
        imp.updateAndDraw()
        review_crop = mb.check_cropping(output_folder_old, params)
        keep_crop = not review_crop
        if review_crop:
            keep_crop = mbui.crop_review()
        if not keep_crop:
            imp.changes = False
            imp.close()
            imp = original_imp
        else:
            original_imp.close()
    else:
        original_imp.close()

    # prompt user to do time cropping
    imp, start_end_tuple = mbui.time_crop(imp, params)
    params.setTimeCropStartEnd(start_end_tuple)

    # import edges
    membrane_edges = mbio.load_qcd_edges2(
        os.path.join(output_folder_old, "user_defined_edges.zip"))
    mbio.save_qcd_edges2(membrane_edges, params.output_path)

    calculated_objects = CalculatedObjects()
    calculated_objects.membrane_edges = membrane_edges
    if params.time_crop_start_end[0] is not None:
        calculated_objects.timelist = [
            idx * params.frame_interval
            for idx in range(params.time_crop_start_end[0],
                             params.time_crop_start_end[1] + 1)
        ]
    else:
        calculated_objects.timelist = [
            idx * params.frame_interval for idx in range(imp.getNFrames())
        ]

    split_channels = mbfs.split_image_plus(imp, params)
    membrane_channel_imp = split_channels[0]
    actin_channel_imp = split_channels[1]
    segmentation_channel_imp = None
    if params.photobleaching_correction:
        if os.path.isfile(
                os.path.join(output_folder_old, 'binary_membrane_stack.tif')):
            segmentation_binary_path = os.path.join(
                output_folder_old, 'binary_membrane_stack.tif')
            segmentation_channel_imp = IJ.openImage(segmentation_binary_path)
        else:
            segmentation_channel_imp = split_channels[2]
            segmentation_channel_imp = mb.make_and_clean_binary(
                segmentation_channel_imp, params.threshold_method)
        split_channels[2] = segmentation_channel_imp

    calculated_objects = mbfs.calculate_outputs(params, calculated_objects,
                                                split_channels)

    # output colormapped images and kymographs
    fig_imp_list = mbfs.generate_and_save_figures(imp, calculated_objects,
                                                  params, membrane_channel_imp,
                                                  segmentation_channel_imp)
    mbfs.save_csvs(calculated_objects, params)

    params.saveParametersToJson(
        os.path.join(params.output_path, "parameters used.json"))
    imp.changes = False
    IJ.setTool("zoom")
    if params.close_on_completion:
        for fig_imp in fig_imp_list:
            fig_imp.close()
            imp.close()

    return
def main():
	### debug ###############################################################
	#print (sys.version_info);
	#print(sys.path);
	#file_path = "D:\\data\\Inverse blebbing\\MAX_2dpf marcksl1b-EGFP inj_TgLifeact-mCh_movie e4_split-bleb1.tif";
	#output_root = "D:\\data\\Inverse blebbing\\output";
	#from datetime import datetime
	#timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d %H-%M-%S');
	#output_folder = os.path.join(output_root, (timestamp + ' output')); 
	#os.mkdir(output_folder); 
	########################################################################
	
	# ensure consistent preference settings
	Prefs.blackBackground = False;

	# prompt user for input parameters
	params = mbui.analysis_parameters_gui();

	# prompt user for file locations
	file_path, output_folder = mbio.file_location_chooser(params.input_image_path);
	params.setInputImagePath(file_path);
	params.setOutputPath(output_folder);

	# get image file
	import_opts, params = mbui.choose_series(file_path, params);
	imps = bf.openImagePlus(import_opts);
	imp = imps[0];

	# catch unexpected image dimensions - for now, project in Z...:
	if  imp.getNSlices() > 1:
		mbui.warning_dialog(["More than one Z plane detected.", 
							"I will do a maximum projection before proceeding", 
							"Continue?"]);
		imp = ZProjector.run(imp,"max all");

	params = mbio.get_metadata(params);
	params.setCurvatureLengthUm(round(params.curvature_length_um / params.pixel_physical_size) * params.pixel_physical_size);
	params.persistParameters();
	IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel");
	imp.show();
	if imp.getNChannels() > 1:
		imp.setPosition(params.membrane_channel_number, 1, 1);
	mbui.autoset_zoom(imp);
	IJ.run("Enhance Contrast", "saturated=0.35");

	# prompt user to select ROI
	original_imp, crop_params = mbui.crop_to_ROI(imp, params);
	if crop_params is not None:
		params.perform_spatial_crop = True;
		mbui.autoset_zoom(imp);
	else:
		params.perform_spatial_crop = False;


	# prompt user to do time cropping
	imp, start_end_tuple = mbui.time_crop(imp, params);
	params.setTimeCropStartEnd(start_end_tuple);

	repeats = 1;
	inner_outer_comparisons = None;
	if params.inner_outer_comparison:
		inner_outer_comparisons = InnerOuterComparisonData();
		repeats = 2;

	IJ.selectWindow(imp.getTitle());
	IJ.run("Enhance Contrast", "saturated=0.35");
	for r in range(0, repeats):
		calculated_objects = CalculatedObjects();
		if params.time_crop_start_end[0] is not None:
			calculated_objects.timelist = [idx * params.frame_interval for idx in range(params.time_crop_start_end[0], params.time_crop_start_end[1]+1)]
		else:
			calculated_objects.timelist = [idx * params.frame_interval for idx in range(imp.getNFrames())];
		calculated_objects, params, split_channels = mbfs.generate_edges(imp, params, calculated_objects, (r+1)/repeats);
		membrane_channel_imp = split_channels[0];
		actin_channel_imp = split_channels[1];
		segmentation_channel_imp = split_channels[2];

		calculated_objects = mbfs.calculate_outputs(params,
													calculated_objects, 
													split_channels, 
													repeat_fraction=(r+1)/repeats);
						
		# output colormapped images and kymographs 
		fig_imp_list = mbfs.generate_and_save_figures(imp, calculated_objects, params, membrane_channel_imp, segmentation_channel_imp);
		mbfs.save_csvs(calculated_objects, params);
	
		params.saveParametersToJson(os.path.join(params.output_path, "parameters used.json"));
		imp.changes = False;
		IJ.setTool("zoom");
		if params.close_on_completion or (params.inner_outer_comparison and r!=(repeats-1)):
			for fig_imp in fig_imp_list:
				fig_imp.close();
		elif params.close_on_completion and (r==(repeats-1)):
			imp.close();
	
	if params.inner_outer_comparison:
		tname = "Time, " + params.interval_unit;
		output_folder = os.path.dirname(params.output_path);
		profile = [[((inner, outer), (float(outer)/inner)) for inner, outer in zip(calculated_objects.inner_outer_data.inner_means, calculated_objects.inner_outer_data.outer_means)]];
		mbio.save_profile_as_csv(profile, 
								os.path.join(output_folder, "Intensity ratios.csv"), 
								"outer/inner", 
								xname="inner", 
								yname="outer",
								tname=tname, 
								time_list=calculated_objects.timelist);
		sd_profile = [[((inner, outer), (float(outer)/inner)) for inner, outer in zip(calculated_objects.inner_outer_data.inner_sds, calculated_objects.inner_outer_data.outer_sds)]];
		mbio.save_profile_as_csv(profile, 
								os.path.join(output_folder, "Intensity standard deviation ratios.csv"), 
								"outer sd/inner sd", 
								xname="inner sd", 
								yname="outer sd",
								tname=tname, 
								time_list=calculated_objects.timelist);
	return;
def main():
	# ensure consistent preference settings
	Prefs.blackBackground = False;
	
	# get locations for previous and new outputs
	params = Parameters();
	params.loadLastParams();
	output_folder_old, output_folder = mbio.rerun_location_chooser(params.input_image_path);
	params.loadParametersFromJson(os.path.join(output_folder_old, 'parameters used.json'));
	params.setOutputPath(output_folder);

	# get original image file (for overlays etc.) 
	if not os.path.isfile(params.input_image_path):
		mbui.warning_dialog(["The original data can't be found at the location specified in saved parameters. ", 
							"(Possibly something as simple as a change in network drive mapping has occurred)",
							"Please specify the location of the original image file..."]);
		params.setInputImagePath(mbio.input_file_location_chooser(params.output_path));

	import_opts, params = mbui.choose_series(params.input_image_path, params);
	imps = bf.openImagePlus(import_opts);
	imp = imps[0];

	if imp.getNSlices() > 1:
		mbui.warning_dialog(["More than one Z plane detected.", 
							"I will do a maximum projection before proceeding", 
							"Continue?"]);
		imp = ZProjector.run(imp,"max all");

	# prompt user to select ROI
	original_imp = Duplicator().run(imp);
	_, crop_params = mbui.crop_to_ROI(imp, params);
	imp.show();

	if crop_params is not None:
		params.perform_spatial_crop = True;
		mbui.autoset_zoom(imp);
		imp.updateAndDraw();
		review_crop = mb.check_cropping(output_folder_old, params);
		keep_crop = not review_crop;
		if review_crop:
			keep_crop = mbui.crop_review();
		if not keep_crop:
			imp.changes = False;
			imp.close();
			imp = original_imp;
		else:
			original_imp.close();
	else:
		original_imp.close();

	# prompt user to do time cropping
	imp, start_end_tuple = mbui.time_crop(imp, params);
	params.setTimeCropStartEnd(start_end_tuple);

	params = mbio.get_metadata(params);
	params.setCurvatureLengthUm(round(params.curvature_length_um / params.pixel_physical_size) * params.pixel_physical_size);
	params.persistParameters();
	IJ.run(imp, "Set Scale...", "distance=0 known=0 pixel=1 unit=pixel");
	imp.show();
	if imp.getNChannels() > 1:
		imp.setPosition(params.membrane_channel_number, 1, 1);
	mbui.autoset_zoom(imp);
	IJ.run("Enhance Contrast", "saturated=0.35");

	split_channels = mbfs.split_image_plus(imp, params);
	membrane_test_channel_imp = Duplicator().run(split_channels[0]);
	segmentation_channel_imp = split_channels[-1];

	# import edges
	imp.hide();
	membrane_edges = mbio.load_qcd_edges2(os.path.join(output_folder_old, "user_defined_edges.zip"));
	dummy_anchors = [params.manual_anchor_positions for _ in membrane_edges]
	membrane_edges, fixed_anchors = mbui.perform_user_qc(membrane_test_channel_imp, membrane_edges, membrane_edges, dummy_anchors, params);
	imp.show();
	rgbstack = ImageStack(imp.getWidth(), imp.getHeight());
	for tidx in range(imp.getNFrames()): 
		imp.setT(tidx+1);
		ip = imp.getProcessor();
		rgbip = ip.convertToRGB();
		rgbstack.addSlice(rgbip);
	rgbimp = ImagePlus(("RGB " + imp.getTitle()), rgbstack);
	imp.close();
	rgbimp.show();
	IJ.run("Colors...", "foreground=yellow background=white selection=yellow");
	for tidx in range(rgbimp.getNSlices()):
		rgbimp.setSlice(tidx+1);
		rgbimp.setRoi(membrane_edges[tidx]);
		IJ.run(rgbimp, "Draw", "slice");
	IJ.run("Colors...", "foreground=red background=white selection=yellow");
	for tidx in range(rgbimp.getNSlices()):
		rgbimp.setSlice(tidx+1);
		for anchor in params.manual_anchor_positions:
			rgbimp.setRoi(PointRoi(anchor[0], anchor[1]));
			IJ.run(rgbimp, "Draw", "slice");
	params.saveParametersToJson(os.path.join(params.output_path, "parameters used.json"));
	params.persistParameters();	
	rgbimp.changes = False;