From 0985d669882ef75915fba6912dd30f2979edca54 Mon Sep 17 00:00:00 2001
From: Laurent Guerard <laurent.guerard@unibas.ch>
Date: Wed, 8 Jan 2025 14:41:24 +0100
Subject: [PATCH] Add option to do batch

---
 1_identify_fibers.py | 176 ++++++++++++++++++++++++++++++++-----------
 1 file changed, 134 insertions(+), 42 deletions(-)

diff --git a/1_identify_fibers.py b/1_identify_fibers.py
index 6c3dc3e..9a9b104 100755
--- a/1_identify_fibers.py
+++ b/1_identify_fibers.py
@@ -677,34 +677,42 @@ imp_result = run_tm(membrane, 1, cellpose_dir.getPath(), PretrainedModel.CYTO2,
 IJ.saveAs(imp_result, "Tiff", output_dir + "/" + raw_image_title + "_all_fibers_binary")
 
 sys.exit()
+    file_list = pathtools.listdir_matching(
+        src_dir.getPath(), filename_filter, fullpath=True
+    )
 
-# modify rois
+    out_dir_info = pathtools.parse_path(output_dir)
 rm.hide()
 raw.hide()
-enlarge_all_rois( enlarge, rm, raw_image_calibration.pixelWidth )
-renumber_rois(rm)
-save_all_rois( rm, output_dir + "/" + raw_image_title + "_all_fiber_rois.zip" )
 
-# check for positive fibers
-if fiber_channel > 0:
-    if min_fiber_intensity == 0:
-        min_fiber_intensity = get_threshold_from_method(raw, fiber_channel, "Mean")[0]
-        IJ.log( "automatic intensity threshold detection: True" )
+    for index, file in enumerate(file_list):
+        # open image using Bio-Formats
+        file_info = pathtools.parse_path(file)
+        misc.progressbar(index + 1, len(file_list), 1, "Opening : ")
+        raw = bf.import_image(file_info["full"])[0]
 
-    IJ.log( "fiber intensity threshold: " + str(min_fiber_intensity) )
-    change_all_roi_color(rm, "blue")
-    positive_fibers = select_positive_fibers( raw, fiber_channel, rm, min_fiber_intensity  )
-    change_subset_roi_color(rm, positive_fibers, "magenta")
-    save_selected_rois( rm, positive_fibers, output_dir + "/" + raw_image_title + "_mhc_positive_fiber_rois.zip")
+        # get image info
+        raw_image_calibration = raw.getCalibration()
+        raw_image_title = fix_BF_czi_imagetitle(raw)
+        print("raw image title: ", str(raw_image_title))
 
-# measure size & shape, save
-IJ.run("Set Measurements...", "area perimeter shape feret's redirect=None decimal=4")
-IJ.run("Clear Results", "")
-measure_in_all_rois( raw, membrane_channel, rm )
+        # take care of paths and directories
+        output_dir = os.path.join(
+            out_dir_info["full"], str(raw_image_title), "1_identify_fibers"
+        )
+        print("output_dir: ", str(output_dir))
 
-rt = ResultsTable.getResultsTable("Results")
+        if not os.path.exists(str(output_dir)):
+            os.makedirs(str(output_dir))
 
-print rt.size()
+        # update the log for the user
+        misc.timed_log("Now working on " + str(raw_image_title))
+        if raw_image_calibration.scaled() is False:
+            IJ.log(
+                "Your image is not spatially calibrated! Size measurements are only possible in [px]."
+            )
+        # Only print it once since we'll use the same settings everytime
+        if index == 0:
             IJ.log(" -- settings used -- ")
             IJ.log("area = " + str(minAr) + "-" + str(maxAr))
             IJ.log("perimeter = " + str(minPer) + "-" + str(maxPer))
@@ -714,25 +722,109 @@ print rt.size()
             IJ.log("MHC positive fiber channel = " + str(fiber_channel))
             # IJ.log("sub-tiling = " + str(tiling_factor))
             IJ.log(" -- settings used -- ")
-print "saved the all_fibers_results.csv"
-# dress up the original image, save a overlay-png, present original to the user
-rm.show()
-raw.show()
-show_all_rois_on_image( rm, raw )
-raw.setDisplayMode(IJ.COMPOSITE)
-enhance_contrast( raw )
-IJ.run("From ROI Manager", "") # ROIs -> overlays so they show up in the saved png
-qc_duplicate = raw.duplicate()
-IJ.saveAs(qc_duplicate, "PNG", output_dir + "/" + raw_image_title + "_all_fibers")
-qc_duplicate.close()
-wm.toFront( raw.getWindow() )
-IJ.run("Remove Overlay", "")
-raw.setDisplayMode(IJ.GRAYSCALE)
-show_all_rois_on_image( rm, raw )
-total_execution_time_min = (time.time() - execution_start_time) / 60.0
-IJ.log("total time in minutes: " + str(total_execution_time_min))
-IJ.log( "~~ all done ~~" )
-IJ.selectWindow("Log")
-IJ.saveAs("Text", str(output_dir + "/" + raw_image_title + "_all_fibers_Log"))
-if close_raw == True:
-    raw.close()
\ No newline at end of file
+
+        # image (pre)processing and segmentation (-> ROIs)# imp, firstC, lastC, firstZ,
+        # lastZ, firstT, lastT
+        membrane = Duplicator().run(raw, membrane_channel, membrane_channel, 1, 1, 1, 1)
+        imp_bgd_corrected = do_background_correction(membrane)
+        IJ.run("Conversions...", "scale")
+        IJ.run(imp_bgd_corrected, "16-bit", "")
+
+        imp_result = run_tm(
+            imp_bgd_corrected,
+            1,
+            cellpose_dir.getPath(),
+            PretrainedModel.CYTO2,
+            30.0,
+            area_thresh=[minAr, maxAr],
+            circularity_thresh=[minCir, maxCir],
+            perimeter_thresh=[minPer, maxPer],
+        )
+        IJ.saveAs(
+            imp_result,
+            "Tiff",
+            os.path.join(output_dir, raw_image_title + "_all_fibers_binary"),
+        )
+
+        command.run(Labels2CompositeRois, True, "rm", rm, "imp", imp_result).get()
+
+        enlarge_all_rois(enlarge_radius, rm, raw_image_calibration.pixelWidth)
+        renumber_rois(rm)
+        save_all_rois(
+            rm, os.path.join(output_dir, raw_image_title + "_all_fiber_rois.zip")
+        )
+
+        # check for positive fibers
+        if fiber_channel > 0:
+            if min_fiber_intensity == 0:
+                min_fiber_intensity = get_threshold_from_method(
+                    raw, fiber_channel, "Mean"
+                )[0]
+                IJ.log("automatic intensity threshold detection: True")
+
+            IJ.log("fiber intensity threshold: " + str(min_fiber_intensity))
+            change_all_roi_color(rm, "blue")
+            positive_fibers = select_positive_fibers(
+                raw, fiber_channel, rm, min_fiber_intensity
+            )
+            change_subset_roi_color(rm, positive_fibers, "magenta")
+            save_selected_rois(
+                rm,
+                positive_fibers,
+                os.path.join(
+                    output_dir, raw_image_title + "_mhc_positive_fiber_rois.zip"
+                ),
+            )
+
+        # measure size & shape, save
+        IJ.run(
+            "Set Measurements...",
+            "area perimeter shape feret's redirect=None decimal=4",
+        )
+        IJ.run("Clear Results", "")
+        measure_in_all_rois(raw, membrane_channel, rm)
+
+        rt = ResultsTable.getResultsTable("Results")
+
+        # print(rt.size())
+
+        if fiber_channel > 0:
+            # print(rt.size())
+            preset_results_column(rt, "MHC Positive Fibers (magenta)", "NO")
+            # print(rt.size())
+            add_results(rt, "MHC Positive Fibers (magenta)", positive_fibers, "YES")
+            # print(rt.size())
+
+        rt.save(os.path.join(output_dir, raw_image_title + "_all_fibers_results.csv"))
+        # print("saved the all_fibers_results.csv")
+        # dress up the original image, save a overlay-png, present original to the user
+        rm.show()
+        raw.show()
+        show_all_rois_on_image(rm, raw)
+        raw.setDisplayMode(IJ.COMPOSITE)
+        enhance_contrast(raw)
+        IJ.run(
+            "From ROI Manager", ""
+        )  # ROIs -> overlays so they show up in the saved png
+        qc_duplicate = raw.duplicate()
+        IJ.saveAs(
+            qc_duplicate, "PNG", output_dir + "/" + raw_image_title + "_all_fibers"
+        )
+        qc_duplicate.close()
+        wm.toFront(raw.getWindow())
+        IJ.run("Remove Overlay", "")
+        raw.setDisplayMode(IJ.GRAYSCALE)
+        show_all_rois_on_image(rm, raw)
+
+        IJ.selectWindow("Log")
+        IJ.saveAs("Text", str(output_dir + "/" + raw_image_title + "_all_fibers_Log"))
+        membrane.close()
+        imp_bgd_corrected.close()
+        imp_result.close()
+
+        if close_raw == True:
+            raw.close()
+
+    total_execution_time_min = (time.time() - execution_start_time) / 60.0
+    IJ.log("total time in minutes: " + str(total_execution_time_min))
+    IJ.log("~~ all done ~~")
-- 
GitLab