[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73J0SZZGA5A649BDPPSJ2JH":3,"skill-same:01M73J0SZZGA5A649BDPPSJ2JH":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73J0SZZGA5A649BDPPSJ2JH","pyimagej-fiji-bridge",null,"Python bridge to ImageJ2\u002FFiji for macros, plugins (Bio-Formats, TrackMate, Analyze Particles), NumPy↔ImagePlus\u002FImgLib2 exchange, and ImageJ Ops. Automates Fiji headlessly from Python. Use scikit-image for pure Python without Fiji plugins; napari for visualization.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fpyimagej-fiji-bridge\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: \"pyimagej-fiji-bridge\"\ndescription: \"Python bridge to ImageJ2\u002FFiji for macros, plugins (Bio-Formats, TrackMate, Analyze Particles), NumPy↔ImagePlus\u002FImgLib2 exchange, and ImageJ Ops. Automates Fiji headlessly from Python. Use scikit-image for pure Python without Fiji plugins; napari for visualization.\"\nlicense: \"Apache-2.0\"\n---\n\n# PyImageJ — Python Bridge to ImageJ\u002FFiji\n\n## Overview\n\nPyImageJ provides a Python interface to ImageJ2 and Fiji through PyJNIus and scyjava, embedding a full Java Virtual Machine inside a Python process. It enables bidirectional data exchange between NumPy arrays and ImageJ's ImagePlus\u002FImgLib2 data structures, so you can preprocess images in Python, pass them into Fiji plugins (Bio-Formats, TrackMate, Analyze Particles, Weka segmentation), and return results back to pandas DataFrames. The library supports headless operation for scripting and batch processing, as well as GUI mode for interactive Fiji sessions.\n\n## When to Use\n\n- Running Fiji-specific plugins from Python: Bio-Formats multi-format I\u002FO, TrackMate particle tracking, CLIJ2 GPU processing, or community Fiji update site plugins\n- Automating ImageJ macro pipelines headlessly without opening the Fiji GUI, e.g., batch processing an entire experiment overnight\n- Applying the ImageJ Ops framework (150+ image processing operations) with the full ImageJ type system\n- Converting between NumPy arrays (SciPy ecosystem) and ImageJ hyperstacks (TZCYX channel order) for round-trip processing\n- Parsing ImageJ Results tables and ROI Manager measurements into pandas DataFrames for downstream statistical analysis\n- Executing existing `.ijm` macro files as part of a Python workflow without rewriting them\n- Use `scikit-image` instead when you need pure Python processing without Fiji plugins — scikit-image is faster to install and avoids JVM overhead\n- Use `napari` instead for interactive multi-dimensional image visualization and annotation; PyImageJ does not replace a viewer\n\n## Prerequisites\n\n- **Python packages**: `pyimagej`, `scyjava`, `numpy`, `pandas`\n- **Java**: Java 8 or Java 11 (Java 17 is not supported); use conda for reliable Java management\n- **Fiji\u002FImageJ2**: Downloaded automatically on first init, or specify a local Fiji installation path\n- **Environment**: conda environment strongly recommended; pip-only installs often have JVM path issues\n\n```bash\n# Recommended: conda installation\nconda create -n pyimagej -c conda-forge pyimagej openjdk=11\nconda activate pyimagej\n\n# Install additional dependencies\npip install pandas tifffile\n\n# Verify\npython -c \"import imagej; ij = imagej.init('sc.fiji:fiji', mode='headless'); print(ij.getVersion())\"\n```\n\n## Quick Start\n\n```python\nimport imagej\nimport numpy as np\n\n# Initialize Fiji in headless mode (downloads on first run, ~500 MB)\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\nprint(f\"ImageJ version: {ij.getVersion()}\")\n\n# Create a test image, process with Gaussian blur via Ops, convert back\narr = np.random.randint(0, 1000, (256, 256), dtype=np.uint16)\nimp = ij.py.to_imageplus(arr)\nblurred = ij.op().filter().gauss(imp.getProcessor(), 2.0)\nresult = ij.py.from_imageplus(imp)\nprint(f\"Processed array shape: {result.shape}, dtype: {result.dtype}\")\n```\n\n## Core API\n\n### Module 1: Initialization\n\nPyImageJ must be initialized once per Python session. The `mode` and endpoint determine which ImageJ distribution and GUI behavior to use.\n\n```python\nimport imagej\n\n# Headless Fiji — most common for scripts and batch jobs\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\n# GUI mode — opens the Fiji window (requires a display)\nij = imagej.init(\"sc.fiji:fiji\", mode=\"gui\")\n\n# Local Fiji installation — faster startup, no download\nij = imagej.init(\"\u002Fpath\u002Fto\u002FFiji.app\", mode=\"headless\")\n\n# Specific Fiji version\nij = imagej.init(\"sc.fiji:fiji:2.14.0\", mode=\"headless\")\n\n# Bare ImageJ2 without Fiji plugins\nij = imagej.init(\"net.imagej:imagej\", mode=\"headless\")\n\nprint(f\"ImageJ version: {ij.getVersion()}\")\nprint(f\"Headless: {ij.ui().isHeadless()}\")\n```\n\n### Module 2: Image I\u002FO\n\nOpen and save images using ImageJ's I\u002FO layer (which includes Bio-Formats for proprietary formats) and convert between ImageJ and NumPy representations.\n\n```python\nimport imagej\nimport numpy as np\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\n# Open any format Bio-Formats supports: CZI, LIF, ND2, ICS, TIFF, etc.\nimp = ij.io().open(\"\u002Fdata\u002Fexperiment.czi\")\nprint(f\"Dimensions: {imp.getDimensions()}\")   # [W, H, C, Z, T]\nprint(f\"nSlices: {imp.getNSlices()}, nFrames: {imp.getNFrames()}\")\n\n# Save image\nij.io().save(imp, \"\u002Fdata\u002Foutput.tif\")\nprint(\"Saved output.tif\")\n```\n\n```python\n# NumPy ↔ ImageJ conversion\narr = np.zeros((100, 100), dtype=np.uint16)\narr[30:70, 30:70] = 1000   # bright square\n\n# NumPy → ImagePlus\nimp = ij.py.to_imageplus(arr)\nprint(f\"ImagePlus: {imp.getWidth()}×{imp.getHeight()}, type={imp.getType()}\")\n\n# ImagePlus → NumPy (returns a view where possible)\narr_back = ij.py.from_imageplus(imp)\nprint(f\"NumPy array: shape={arr_back.shape}, dtype={arr_back.dtype}\")\n\n# Multi-channel array: shape (C, H, W)\nrgb = np.random.randint(0, 255, (3, 256, 256), dtype=np.uint8)\nimp_rgb = ij.py.to_imageplus(rgb)\nprint(f\"Channels: {imp_rgb.getNChannels()}\")\n```\n\n### Module 3: Macro Execution\n\nRun ImageJ macro language (IJM) snippets or macro files. Macros execute inside the ImageJ environment and can call any built-in ImageJ command.\n\n```python\nimport imagej\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\n# Run an inline macro string\nij.macro.run(\"print('Hello from ImageJ macro');\")\n\n# Run a macro with options string (key=value pairs)\n# Options string mirrors the dialog parameters of ImageJ commands\nmacro_code = \"\"\"\nrun(\"Gaussian Blur...\", \"sigma=2\");\nrun(\"Auto Threshold\", \"method=Otsu white\");\n\"\"\"\nij.macro.run(macro_code)\n\n# Run a macro file from disk\nij.macro.runMacroFile(\"\u002Fscripts\u002Fmy_analysis.ijm\")\n\n# Run macro that returns a value via getResult or output string\nresult = ij.macro.run(\"\"\"\nx = 42 * 2;\nreturn x;\n\"\"\")\nprint(f\"Macro returned: {result}\")\n```\n\n```python\n# Macro with current image: open → process → measure\nij.io().open(\"\u002Fdata\u002Fcells.tif\")   # sets current active image\n\nmeasure_macro = \"\"\"\nrun(\"Set Measurements...\", \"area mean min integrated redirect=None decimal=3\");\nrun(\"Analyze Particles...\", \"size=50-Infinity display clear summarize\");\n\"\"\"\nij.macro.run(measure_macro)\nprint(\"Analyze Particles complete; results in Results table\")\n```\n\n### Module 4: ImageJ Ops\n\nImageJ Ops is a framework of 150+ image processing operations with type-safe dispatch. Ops work on ImgLib2 `Img` objects and are the preferred way to call image processing algorithms programmatically.\n\n```python\nimport imagej\nimport numpy as np\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\narr = np.random.randint(100, 900, (512, 512), dtype=np.uint16)\nimg = ij.py.to_java(arr)   # converts to ImgLib2 RandomAccessibleInterval\n\n# Gaussian blur\nblurred = ij.op().filter().gauss(img, 2.0)\nblurred_np = ij.py.from_java(blurred)\nprint(f\"Blurred: {blurred_np.shape}\")\n\n# Otsu threshold → binary image\nbinary = ij.op().threshold().otsu(img)\nbinary_np = ij.py.from_java(binary)\nprint(f\"Binary unique values: {np.unique(binary_np)}\")\n\n# Morphological operations\nfrom jnius import autoclass\nBitType = autoclass(\"net.imglib2.type.logic.BitType\")\nopened = ij.op().morphology().open(binary, [3, 3])\nopened_np = ij.py.from_java(opened)\nprint(f\"After opening: {opened_np.shape}\")\n```\n\n```python\n# Statistics ops\nmean_val = ij.op().stats().mean(img)\nstd_val  = ij.op().stats().stdDev(img)\nprint(f\"Mean intensity: {mean_val:.1f}, StdDev: {std_val:.1f}\")\n\n# Math ops: multiply image by scalar\nscaled = ij.op().math().multiply(img, ij.py.to_java(2.0))\nprint(f\"Scaled max: {ij.py.from_java(scaled).max()}\")\n```\n\n### Module 5: Plugin and Command Calls\n\nSciJava commands are the primary way to invoke Fiji plugins programmatically. Commands accept a dict of named parameters mirroring the plugin dialog.\n\n```python\nimport imagej\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\n# Open a file using Bio-Formats opener command\nfuture = ij.command().run(\n    \"loci.plugins.LociImporter\",\n    True,\n    {\"id\": \"\u002Fdata\u002Fimage.lif\", \"open_files\": True, \"autoscale\": True}\n)\nmodule = future.get()\nimp = module.getOutput(\"imp\")\nprint(f\"Opened via Bio-Formats: {imp.getDimensions()}\")\n```\n\n```python\n# Run Analyze Particles as a SciJava command\nij.io().open(\"\u002Fdata\u002Fbinary_mask.tif\")\n\nfuture = ij.command().run(\n    \"ij.plugin.filter.ParticleAnalyzer\",\n    True,\n    {\n        \"minSize\": 50.0,\n        \"maxSize\": float(\"inf\"),\n        \"options\": 0,      # SHOW_NONE\n        \"measurements\": 1,  # AREA\n    }\n)\nfuture.get()\nprint(\"Analyze Particles command complete\")\n\n# Alternatively, run via macro string for simpler plugin invocation\nij.macro.run(\"\"\"\nrun(\"Analyze Particles...\", \"size=50-Infinity display clear summarize\");\n\"\"\")\n```\n\n### Module 6: Results Table and ROI Analysis\n\nRetrieve measurement results from ImageJ's Results table and ROI Manager after running Analyze Particles or other measurement commands.\n\n```python\nimport imagej\nimport pandas as pd\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\n# After running Analyze Particles, read the Results table\ndef results_to_dataframe(ij) -> pd.DataFrame:\n    \"\"\"Convert ImageJ Results table to pandas DataFrame.\"\"\"\n    rt = ij.ResultsTable.getResultsTable()\n    if rt is None or rt.size() == 0:\n        return pd.DataFrame()\n    headings = list(rt.getHeadings())\n    data = {col: [rt.getValue(col, i) for i in range(rt.size())]\n            for col in headings}\n    return pd.DataFrame(data)\n\n# Run segmentation + measurement macro\nij.io().open(\"\u002Fdata\u002Fcells.tif\")\nij.macro.run(\"\"\"\nrun(\"Gaussian Blur...\", \"sigma=1.5\");\nsetAutoThreshold(\"Otsu dark\");\nrun(\"Convert to Mask\");\nrun(\"Analyze Particles...\", \"size=20-Infinity display clear\");\n\"\"\")\n\ndf = results_to_dataframe(ij)\nprint(f\"Found {len(df)} objects\")\nprint(df[[\"Area\", \"Mean\", \"IntDen\"]].describe())\ndf.to_csv(\"particle_measurements.csv\", index=False)\nprint(\"Saved particle_measurements.csv\")\n```\n\n```python\n# Access the ROI Manager\ndef get_roi_manager(ij):\n    \"\"\"Return the ImageJ ROI Manager instance, creating if needed.\"\"\"\n    RoiManager = ij.py.jclass(\"ij.plugin.frame.RoiManager\")\n    rm = RoiManager.getInstance()\n    if rm is None:\n        rm = RoiManager(False)   # headless=False means no GUI window\n    return rm\n\nrm = get_roi_manager(ij)\nroi_count = rm.getCount()\nprint(f\"ROIs in manager: {roi_count}\")\n\n# Extract bounding boxes for all ROIs\nrois = []\nfor i in range(roi_count):\n    roi = rm.getRoi(i)\n    bounds = roi.getBounds()\n    rois.append({\"index\": i, \"x\": bounds.x, \"y\": bounds.y,\n                 \"width\": bounds.width, \"height\": bounds.height})\nroi_df = pd.DataFrame(rois)\nprint(roi_df.head())\n```\n\n## Common Workflows\n\n### Workflow 1: Automated Fluorescence Quantification\n\n**Goal**: Open a multi-channel TIFF stack, apply Gaussian blur, threshold nuclei channel, run Analyze Particles, and export per-cell measurements as CSV.\n\n```python\nimport imagej\nimport pandas as pd\nimport numpy as np\nfrom pathlib import Path\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\ndef quantify_nuclei(tiff_path: str, output_csv: str,\n                    channel: int = 1, sigma: float = 1.5,\n                    min_size: int = 50) -> pd.DataFrame:\n    \"\"\"\n    Segment and measure nuclei in a fluorescence TIFF.\n\n    Parameters\n    ----------\n    tiff_path  : path to single- or multi-channel TIFF\n    output_csv : where to save results\n    channel    : 1-based channel index for nuclear stain (e.g., DAPI)\n    sigma      : Gaussian blur radius in pixels\n    min_size   : minimum nucleus area in pixels\n    \"\"\"\n    # Step 1: Open image\n    imp = ij.io().open(tiff_path)\n    print(f\"Loaded: {Path(tiff_path).name}  dims={imp.getDimensions()}\")\n\n    # Step 2: Extract channel if multi-channel\n    if imp.getNChannels() > 1:\n        imp.setC(channel)\n\n    # Step 3: Apply Gaussian blur and threshold via macro\n    ij.macro.run(f\"\"\"\nselectWindow(\"{imp.getTitle()}\");\nrun(\"Gaussian Blur...\", \"sigma={sigma}\");\nsetAutoThreshold(\"Otsu dark\");\nrun(\"Convert to Mask\");\nrun(\"Fill Holes\");\nrun(\"Watershed\");\n\"\"\")\n\n    # Step 4: Measure\n    ij.macro.run(f\"\"\"\nrun(\"Set Measurements...\", \"area mean min centroid integrated shape redirect=None decimal=3\");\nrun(\"Analyze Particles...\", \"size={min_size}-Infinity display clear include summarize\");\n\"\"\")\n\n    # Step 5: Collect results\n    rt = ij.ResultsTable.getResultsTable()\n    if rt is None or rt.size() == 0:\n        print(\"No objects detected\")\n        return pd.DataFrame()\n\n    headings = list(rt.getHeadings())\n    df = pd.DataFrame(\n        {col: [rt.getValue(col, i) for i in range(rt.size())]\n         for col in headings}\n    )\n    df[\"source_file\"] = Path(tiff_path).stem\n    df.to_csv(output_csv, index=False)\n    print(f\"Saved {len(df)} measurements → {output_csv}\")\n    return df\n\n\ndf = quantify_nuclei(\n    tiff_path=\"\u002Fdata\u002Fexperiment_dapi.tif\",\n    output_csv=\"nuclei_measurements.csv\",\n    channel=1,\n    sigma=1.5,\n    min_size=50\n)\nprint(df[[\"Area\", \"Mean\", \"Circ.\"]].describe())\n```\n\n### Workflow 2: Batch Fiji Macro Processing\n\n**Goal**: Process a folder of images with an existing Fiji `.ijm` macro file, collect the Results table from each image into a single DataFrame.\n\n```python\nimport imagej\nimport pandas as pd\nfrom pathlib import Path\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\ndef run_macro_on_image(ij, image_path: str, macro_file: str) -> pd.DataFrame:\n    \"\"\"Open one image, run a macro file, return its Results table.\"\"\"\n    ij.io().open(image_path)\n\n    # Clear any previous results before running\n    ij.macro.run(\"run(\\\"Clear Results\\\");\")\n\n    # Run macro file (macro must operate on the active image)\n    ij.macro.runMacroFile(macro_file)\n\n    rt = ij.ResultsTable.getResultsTable()\n    if rt is None or rt.size() == 0:\n        return pd.DataFrame()\n    headings = list(rt.getHeadings())\n    return pd.DataFrame(\n        {col: [rt.getValue(col, i) for i in range(rt.size())]\n         for col in headings}\n    )\n\n\ninput_dir  = Path(\"\u002Fdata\u002Fimages\")\nmacro_file = \"\u002Fscripts\u002Fmeasure_cells.ijm\"\noutput_csv = \"batch_results.csv\"\n\nall_results = []\nimage_files = sorted(input_dir.glob(\"*.tif\"))\n\nfor img_path in image_files:\n    print(f\"Processing: {img_path.name}\")\n    df = run_macro_on_image(ij, str(img_path), macro_file)\n    if not df.empty:\n        df[\"filename\"] = img_path.name\n        all_results.append(df)\n\n    # Close all windows to free memory between images\n    ij.macro.run(\"close('*');\")\n\nif all_results:\n    combined = pd.concat(all_results, ignore_index=True)\n    combined.to_csv(output_csv, index=False)\n    print(f\"Batch complete: {len(image_files)} images, \"\n          f\"{len(combined)} total measurements → {output_csv}\")\nelse:\n    print(\"No results collected from any image\")\n```\n\n## Key Parameters\n\n| Parameter | Module | Default | Range \u002F Options | Effect |\n|-----------|--------|---------|-----------------|--------|\n| `mode` | Initialization | `\"headless\"` | `\"headless\"`, `\"gui\"`, `\"interactive\"` | Controls whether Fiji GUI window opens; use `\"headless\"` for scripts |\n| `endpoint` | Initialization | `\"sc.fiji:fiji\"` | Maven coordinate or `\u002Fpath\u002Fto\u002FFiji.app` | Selects ImageJ2 distribution; `sc.fiji:fiji` includes all Fiji plugins |\n| `sigma` (Gaussian blur) | Macro \u002F Ops | `2.0` | `0.5`–`10.0` | Spatial smoothing radius in pixels; higher reduces noise but blurs edges |\n| `minSize` (Analyze Particles) | Plugin \u002F Macro | `0` | pixels² or `0`–`Infinity` | Smallest object area to include; eliminates noise particles |\n| `method` (Auto Threshold) | Macro \u002F Ops | `\"Otsu\"` | `\"Otsu\"`, `\"Triangle\"`, `\"MaxEntropy\"`, `\"Huang\"`, `\"Li\"` | Threshold algorithm; Otsu works well for bimodal histograms |\n| `measurements` bitmask | Results \u002F Macro | varies | OR combination of `AREA=1`, `MEAN=2`, `CENTROID=4`, etc. | Selects which columns appear in the Results table |\n| Java heap size | Initialization (env) | JVM default (~25% RAM) | set via `JAVA_TOOL_OPTIONS` | Limits memory for large stacks; set `-Xmx8g` for big images |\n\n## Best Practices\n\n1. **Initialize once per session and reuse `ij`**: Starting a new JVM is expensive (5–15 seconds). Create `ij` at module level or pass it as a parameter rather than calling `imagej.init()` inside a loop.\n\n   ```python\n   # At module top level — initialized once\n   import imagej\n   ij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\n   def process(path):\n       imp = ij.io().open(path)   # reuse ij\n       ...\n   ```\n\n2. **Use conda for Java management**: pip-only installs frequently fail because `JAVA_HOME` is not set or the wrong JDK version is on `PATH`. A conda environment with `openjdk=11` avoids 90% of JVM-not-found errors.\n\n3. **Clear Results and ROI Manager between images in batch loops**: ImageJ accumulates results across calls in the same session. Always call `run(\"Clear Results\")` and `rm.reset()` before each image to prevent row contamination.\n\n   ```python\n   ij.macro.run(\"run('Clear Results');\")\n   rm = get_roi_manager(ij)\n   rm.reset()\n   ```\n\n4. **Prefer `ij.macro.run()` for simple commands over `ij.command().run()`**: Macro strings are shorter, easier to read, and use the same syntax as the Fiji Macro Recorder. Use `ij.command().run()` only when you need programmatic access to command outputs (module return values).\n\n5. **Convert to NumPy as late as possible**: `ij.py.from_imageplus()` copies data from the JVM to Python. For multi-step processing inside ImageJ, keep data in ImagePlus or ImgLib2 form and convert only at the end to minimize memory-copy overhead.\n\n6. **Use `ij.py.to_java()` \u002F `ij.py.from_java()` for ImgLib2 Ops**: The `to_imageplus()` \u002F `from_imageplus()` pair works with the classic ImageProcessor; `to_java()` \u002F `from_java()` target the modern ImgLib2 type system required by `ij.op()`.\n\n7. **Set a Fiji update site plugins list during init for reproducibility**: Specify a pinned Fiji version (`sc.fiji:fiji:2.14.0`) rather than `sc.fiji:fiji` (latest) so your pipeline behavior does not change when Fiji releases new plugin updates.\n\n## Common Recipes\n\n### Recipe: TrackMate Headless Spot Detection\n\nWhen to use: Run TrackMate particle tracking programmatically and retrieve detected spots as a DataFrame without opening the TrackMate GUI.\n\n```python\nimport imagej\nimport pandas as pd\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\n# TrackMate headless via macro (scripting interface)\ntrackmate_macro = \"\"\"\nrun(\"TrackMate\", \"\");\n\u002F\u002F For fully scripted TrackMate, use the Scripting Interface\n\u002F\u002F documented at https:\u002F\u002Fimagej.net\u002Fplugins\u002Ftrackmate\u002Fscripting\n\"\"\"\n\n# Scripted TrackMate via Jython-style Java interop\ndef run_trackmate_headless(ij, imp, radius=3.0, threshold=100.0):\n    \"\"\"Detect spots with LoG detector; return DataFrame of spot coordinates.\"\"\"\n    from jnius import autoclass\n\n    # Import TrackMate classes\n    Model          = autoclass(\"fiji.plugin.trackmate.Model\")\n    Settings       = autoclass(\"fiji.plugin.trackmate.Settings\")\n    TrackMate      = autoclass(\"fiji.plugin.trackmate.TrackMate\")\n    LogDetectorFactory = autoclass(\n        \"fiji.plugin.trackmate.detection.LogDetectorFactory\")\n\n    model    = Model()\n    settings = Settings(imp)\n\n    # Configure LoG spot detector\n    settings.detectorFactory = LogDetectorFactory()\n    settings.detectorSettings = {\n        \"DO_SUBPIXEL_LOCALIZATION\": True,\n        \"RADIUS\": radius,\n        \"TARGET_CHANNEL\": 1,\n        \"THRESHOLD\": threshold,\n        \"DO_MEDIAN_FILTERING\": False,\n    }\n\n    tm = TrackMate(model, settings)\n    tm.process()\n\n    # Extract spot table\n    spots = model.getSpots()\n    spots.setVisible(True)\n    records = []\n    for spot in spots.iterable(True):\n        records.append({\n            \"id\":       spot.ID(),\n            \"x\":        spot.getDoublePosition(0),\n            \"y\":        spot.getDoublePosition(1),\n            \"z\":        spot.getDoublePosition(2),\n            \"frame\":    spot.getFeature(\"FRAME\"),\n            \"quality\":  spot.getFeature(\"QUALITY\"),\n        })\n    return pd.DataFrame(records)\n\n\nimp = ij.io().open(\"\u002Fdata\u002Ftimelapse.tif\")\ndf  = run_trackmate_headless(ij, imp, radius=3.0, threshold=50.0)\nprint(f\"Detected {len(df)} spots across {df['frame'].nunique()} frames\")\ndf.to_csv(\"spots.csv\", index=False)\nprint(df.head())\n```\n\n### Recipe: Convert ImageJ Hyperstack to NumPy 5D Array (TZCYX)\n\nWhen to use: Import a multi-dimensional Fiji hyperstack into Python as a 5D NumPy array with the standard TZCYX axis order used by most scientific image analysis libraries.\n\n```python\nimport imagej\nimport numpy as np\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\ndef hyperstack_to_numpy(ij, imp) -> np.ndarray:\n    \"\"\"\n    Convert an ImageJ hyperstack to a NumPy array with shape (T, Z, C, Y, X).\n\n    ImageJ internal order is C-Z-T (slowest to fastest in stack index).\n    This function reorders to the TZCYX convention used by tifffile, OME, etc.\n    \"\"\"\n    nC = imp.getNChannels()\n    nZ = imp.getNSlices()\n    nT = imp.getNFrames()\n    H  = imp.getHeight()\n    W  = imp.getWidth()\n\n    arr = np.zeros((nT, nZ, nC, H, W), dtype=np.uint16)\n\n    for t in range(1, nT + 1):\n        for z in range(1, nZ + 1):\n            for c in range(1, nC + 1):\n                idx = imp.getStackIndex(c, z, t)\n                imp.setSlice(idx)\n                arr[t-1, z-1, c-1] = ij.py.from_imageplus(imp)\n\n    return arr\n\n\nimp = ij.io().open(\"\u002Fdata\u002F4d_experiment.tif\")\nprint(f\"ImageJ dims (W,H,C,Z,T): {imp.getDimensions()}\")\n\nstack = hyperstack_to_numpy(ij, imp)\nprint(f\"NumPy TZCYX shape: {stack.shape}\")  # e.g., (10, 15, 2, 512, 512)\nprint(f\"dtype: {stack.dtype}, max: {stack.max()}\")\n\n# Save as OME-TIFF with correct axis metadata\nimport tifffile\ntifffile.imwrite(\n    \"output_TZCYX.ome.tif\",\n    stack,\n    imagej=True,\n    metadata={\"axes\": \"TZCYX\"},\n    photometric=\"minisblack\"\n)\nprint(\"Saved output_TZCYX.ome.tif\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `JVMNotFoundException` on init | `JAVA_HOME` not set or wrong JDK version | Install via conda: `conda install -c conda-forge openjdk=11`; avoid Java 17 |\n| `RuntimeError: Fiji download failed` | No internet or corporate proxy | Download Fiji manually from fiji.sc, then use `imagej.init(\"\u002Fpath\u002Fto\u002FFiji.app\")` |\n| `java.lang.OutOfMemoryError` on large stacks | JVM default heap is too small | Set `export JAVA_TOOL_OPTIONS=\"-Xmx8g\"` before importing imagej |\n| Macro `run(...)` silently does nothing | No active image when macro expects one | Call `ij.io().open(path)` before running processing macros; check `ij.WindowManager.getImageCount()` |\n| Results table empty after Analyze Particles | Threshold not applied, or mask not binary | Verify mask is 8-bit binary (0\u002F255) with `imp.getType() == 0`; run `Convert to Mask` before Analyze Particles |\n| `AttributeError: 'NoneType' object` on `ij.ResultsTable.getResultsTable()` | No measurements run yet in this session | Confirm Analyze Particles macro completed; run `ij.macro.run(\"print(nResults);\")` to check count |\n| Plugin class not found (`ClassNotFoundException`) | Plugin not in this Fiji installation | Add the Fiji update site (e.g., TrackMate) or use `sc.fiji:fiji` endpoint which includes all default plugins |\n| `gui` mode crashes with `HeadlessException` | No display available (SSH\u002Fcluster) | Use `mode=\"headless\"` for remote environments; GUI mode requires `DISPLAY` or X11 forwarding |\n\n## Related Skills\n\n- **scikit-image-processing** — pure Python image processing without JVM; use when Fiji plugins are not needed\n- **napari-image-viewer** — interactive multi-dimensional image viewer for Python; complement to PyImageJ for visualization\n- **trackpy-particle-tracking** — Python-native Crocker-Grier SPT; alternative to TrackMate for simple 2D tracking\n- **cellpose-cell-segmentation** — deep learning cell segmentation; can be run standalone or as a Fiji plugin\n- **omero-integration** — OMERO server image management; PyImageJ can process images retrieved via omero-py\n\n## References\n\n- [PyImageJ documentation](https:\u002F\u002Fpyimagej.readthedocs.io\u002F) — official API reference, initialization guide, data conversion\n- [PyImageJ GitHub repository](https:\u002F\u002Fgithub.com\u002Fimagej\u002Fpyimagej) — source, issue tracker, notebooks, examples\n- [ImageJ Ops framework](https:\u002F\u002Fimagej.net\u002Flibs\u002Fimagej-ops\u002F) — Ops namespace reference and algorithm catalog\n- [TrackMate scripting guide](https:\u002F\u002Fimagej.net\u002Fplugins\u002Ftrackmate\u002Fscripting) — headless TrackMate Java API patterns\n- [Bio-Formats supported formats](https:\u002F\u002Fbio-formats.readthedocs.io\u002Fen\u002Flatest\u002Fsupported-formats.html) — list of proprietary microscopy formats openable via `ij.io().open()`\n- [ImageJ Macro Language reference](https:\u002F\u002Fimagej.nih.gov\u002Fij\u002Fdeveloper\u002Fmacro\u002Fmacros.html) — built-in functions for `ij.macro.run()` strings\n","# PyImageJ — Python Bridge to ImageJ\u002FFiji\n\n## Overview\n\nPyImageJ provides a Python interface to ImageJ2 and Fiji through PyJNIus and scyjava, embedding a full Java Virtual Machine inside a Python process. It enables bidirectional data exchange between NumPy arrays and ImageJ's ImagePlus\u002FImgLib2 data structures, so you can preprocess images in Python, pass them into Fiji plugins (Bio-Formats, TrackMate, Analyze Particles, Weka segmentation), and return results back to pandas DataFrames. The library supports headless operation for scripting and batch processing, as well as GUI mode for interactive Fiji sessions.\n\n## When to Use\n\n- Running Fiji-specific plugins from Python: Bio-Formats multi-format I\u002FO, TrackMate particle tracking, CLIJ2 GPU processing, or community Fiji update site plugins\n- Automating ImageJ macro pipelines headlessly without opening the Fiji GUI, e.g., batch processing an entire experiment overnight\n- Applying the ImageJ Ops framework (150+ image processing operations) with the full ImageJ type system\n- Converting between NumPy arrays (SciPy ecosystem) and ImageJ hyperstacks (TZCYX channel order) for round-trip processing\n- Parsing ImageJ Results tables and ROI Manager measurements into pandas DataFrames for downstream statistical analysis\n- Executing existing `.ijm` macro files as part of a Python workflow without rewriting them\n- Use `scikit-image` instead when you need pure Python processing without Fiji plugins — scikit-image is faster to install and avoids JVM overhead\n- Use `napari` instead for interactive multi-dimensional image visualization and annotation; PyImageJ does not replace a viewer\n\n## Prerequisites\n\n- **Python packages**: `pyimagej`, `scyjava`, `numpy`, `pandas`\n- **Java**: Java 8 or Java 11 (Java 17 is not supported); use conda for reliable Java management\n- **Fiji\u002FImageJ2**: Downloaded automatically on first init, or specify a local Fiji installation path\n- **Environment**: conda environment strongly recommended; pip-only installs often have JVM path issues\n\n```bash\n# Recommended: conda installation\nconda create -n pyimagej -c conda-forge pyimagej openjdk=11\nconda activate pyimagej\n\n# Install additional dependencies\npip install pandas tifffile\n\n# Verify\npython -c \"import imagej; ij = imagej.init('sc.fiji:fiji', mode='headless'); print(ij.getVersion())\"\n```\n\n## Quick Start\n\n```python\nimport imagej\nimport numpy as np\n\n# Initialize Fiji in headless mode (downloads on first run, ~500 MB)\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\nprint(f\"ImageJ version: {ij.getVersion()}\")\n\n# Create a test image, process with Gaussian blur via Ops, convert back\narr = np.random.randint(0, 1000, (256, 256), dtype=np.uint16)\nimp = ij.py.to_imageplus(arr)\nblurred = ij.op().filter().gauss(imp.getProcessor(), 2.0)\nresult = ij.py.from_imageplus(imp)\nprint(f\"Processed array shape: {result.shape}, dtype: {result.dtype}\")\n```\n\n## Core API\n\n### Module 1: Initialization\n\nPyImageJ must be initialized once per Python session. The `mode` and endpoint determine which ImageJ distribution and GUI behavior to use.\n\n```python\nimport imagej\n\n# Headless Fiji — most common for scripts and batch jobs\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\n# GUI mode — opens the Fiji window (requires a display)\nij = imagej.init(\"sc.fiji:fiji\", mode=\"gui\")\n\n# Local Fiji installation — faster startup, no download\nij = imagej.init(\"\u002Fpath\u002Fto\u002FFiji.app\", mode=\"headless\")\n\n# Specific Fiji version\nij = imagej.init(\"sc.fiji:fiji:2.14.0\", mode=\"headless\")\n\n# Bare ImageJ2 without Fiji plugins\nij = imagej.init(\"net.imagej:imagej\", mode=\"headless\")\n\nprint(f\"ImageJ version: {ij.getVersion()}\")\nprint(f\"Headless: {ij.ui().isHeadless()}\")\n```\n\n### Module 2: Image I\u002FO\n\nOpen and save images using ImageJ's I\u002FO layer (which includes Bio-Formats for proprietary formats) and convert between ImageJ and NumPy representations.\n\n```python\nimport imagej\nimport numpy as np\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\n# Open any format Bio-Formats supports: CZI, LIF, ND2, ICS, TIFF, etc.\nimp = ij.io().open(\"\u002Fdata\u002Fexperiment.czi\")\nprint(f\"Dimensions: {imp.getDimensions()}\")   # [W, H, C, Z, T]\nprint(f\"nSlices: {imp.getNSlices()}, nFrames: {imp.getNFrames()}\")\n\n# Save image\nij.io().save(imp, \"\u002Fdata\u002Foutput.tif\")\nprint(\"Saved output.tif\")\n```\n\n```python\n# NumPy ↔ ImageJ conversion\narr = np.zeros((100, 100), dtype=np.uint16)\narr[30:70, 30:70] = 1000   # bright square\n\n# NumPy → ImagePlus\nimp = ij.py.to_imageplus(arr)\nprint(f\"ImagePlus: {imp.getWidth()}×{imp.getHeight()}, type={imp.getType()}\")\n\n# ImagePlus → NumPy (returns a view where possible)\narr_back = ij.py.from_imageplus(imp)\nprint(f\"NumPy array: shape={arr_back.shape}, dtype={arr_back.dtype}\")\n\n# Multi-channel array: shape (C, H, W)\nrgb = np.random.randint(0, 255, (3, 256, 256), dtype=np.uint8)\nimp_rgb = ij.py.to_imageplus(rgb)\nprint(f\"Channels: {imp_rgb.getNChannels()}\")\n```\n\n### Module 3: Macro Execution\n\nRun ImageJ macro language (IJM) snippets or macro files. Macros execute inside the ImageJ environment and can call any built-in ImageJ command.\n\n```python\nimport imagej\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\n# Run an inline macro string\nij.macro.run(\"print('Hello from ImageJ macro');\")\n\n# Run a macro with options string (key=value pairs)\n# Options string mirrors the dialog parameters of ImageJ commands\nmacro_code = \"\"\"\nrun(\"Gaussian Blur...\", \"sigma=2\");\nrun(\"Auto Threshold\", \"method=Otsu white\");\n\"\"\"\nij.macro.run(macro_code)\n\n# Run a macro file from disk\nij.macro.runMacroFile(\"\u002Fscripts\u002Fmy_analysis.ijm\")\n\n# Run macro that returns a value via getResult or output string\nresult = ij.macro.run(\"\"\"\nx = 42 * 2;\nreturn x;\n\"\"\")\nprint(f\"Macro returned: {result}\")\n```\n\n```python\n# Macro with current image: open → process → measure\nij.io().open(\"\u002Fdata\u002Fcells.tif\")   # sets current active image\n\nmeasure_macro = \"\"\"\nrun(\"Set Measurements...\", \"area mean min integrated redirect=None decimal=3\");\nrun(\"Analyze Particles...\", \"size=50-Infinity display clear summarize\");\n\"\"\"\nij.macro.run(measure_macro)\nprint(\"Analyze Particles complete; results in Results table\")\n```\n\n### Module 4: ImageJ Ops\n\nImageJ Ops is a framework of 150+ image processing operations with type-safe dispatch. Ops work on ImgLib2 `Img` objects and are the preferred way to call image processing algorithms programmatically.\n\n```python\nimport imagej\nimport numpy as np\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\narr = np.random.randint(100, 900, (512, 512), dtype=np.uint16)\nimg = ij.py.to_java(arr)   # converts to ImgLib2 RandomAccessibleInterval\n\n# Gaussian blur\nblurred = ij.op().filter().gauss(img, 2.0)\nblurred_np = ij.py.from_java(blurred)\nprint(f\"Blurred: {blurred_np.shape}\")\n\n# Otsu threshold → binary image\nbinary = ij.op().threshold().otsu(img)\nbinary_np = ij.py.from_java(binary)\nprint(f\"Binary unique values: {np.unique(binary_np)}\")\n\n# Morphological operations\nfrom jnius import autoclass\nBitType = autoclass(\"net.imglib2.type.logic.BitType\")\nopened = ij.op().morphology().open(binary, [3, 3])\nopened_np = ij.py.from_java(opened)\nprint(f\"After opening: {opened_np.shape}\")\n```\n\n```python\n# Statistics ops\nmean_val = ij.op().stats().mean(img)\nstd_val  = ij.op().stats().stdDev(img)\nprint(f\"Mean intensity: {mean_val:.1f}, StdDev: {std_val:.1f}\")\n\n# Math ops: multiply image by scalar\nscaled = ij.op().math().multiply(img, ij.py.to_java(2.0))\nprint(f\"Scaled max: {ij.py.from_java(scaled).max()}\")\n```\n\n### Module 5: Plugin and Command Calls\n\nSciJava commands are the primary way to invoke Fiji plugins programmatically. Commands accept a dict of named parameters mirroring the plugin dialog.\n\n```python\nimport imagej\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\n# Open a file using Bio-Formats opener command\nfuture = ij.command().run(\n    \"loci.plugins.LociImporter\",\n    True,\n    {\"id\": \"\u002Fdata\u002Fimage.lif\", \"open_files\": True, \"autoscale\": True}\n)\nmodule = future.get()\nimp = module.getOutput(\"imp\")\nprint(f\"Opened via Bio-Formats: {imp.getDimensions()}\")\n```\n\n```python\n# Run Analyze Particles as a SciJava command\nij.io().open(\"\u002Fdata\u002Fbinary_mask.tif\")\n\nfuture = ij.command().run(\n    \"ij.plugin.filter.ParticleAnalyzer\",\n    True,\n    {\n        \"minSize\": 50.0,\n        \"maxSize\": float(\"inf\"),\n        \"options\": 0,      # SHOW_NONE\n        \"measurements\": 1,  # AREA\n    }\n)\nfuture.get()\nprint(\"Analyze Particles command complete\")\n\n# Alternatively, run via macro string for simpler plugin invocation\nij.macro.run(\"\"\"\nrun(\"Analyze Particles...\", \"size=50-Infinity display clear summarize\");\n\"\"\")\n```\n\n### Module 6: Results Table and ROI Analysis\n\nRetrieve measurement results from ImageJ's Results table and ROI Manager after running Analyze Particles or other measurement commands.\n\n```python\nimport imagej\nimport pandas as pd\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\n# After running Analyze Particles, read the Results table\ndef results_to_dataframe(ij) -> pd.DataFrame:\n    \"\"\"Convert ImageJ Results table to pandas DataFrame.\"\"\"\n    rt = ij.ResultsTable.getResultsTable()\n    if rt is None or rt.size() == 0:\n        return pd.DataFrame()\n    headings = list(rt.getHeadings())\n    data = {col: [rt.getValue(col, i) for i in range(rt.size())]\n            for col in headings}\n    return pd.DataFrame(data)\n\n# Run segmentation + measurement macro\nij.io().open(\"\u002Fdata\u002Fcells.tif\")\nij.macro.run(\"\"\"\nrun(\"Gaussian Blur...\", \"sigma=1.5\");\nsetAutoThreshold(\"Otsu dark\");\nrun(\"Convert to Mask\");\nrun(\"Analyze Particles...\", \"size=20-Infinity display clear\");\n\"\"\")\n\ndf = results_to_dataframe(ij)\nprint(f\"Found {len(df)} objects\")\nprint(df[[\"Area\", \"Mean\", \"IntDen\"]].describe())\ndf.to_csv(\"particle_measurements.csv\", index=False)\nprint(\"Saved particle_measurements.csv\")\n```\n\n```python\n# Access the ROI Manager\ndef get_roi_manager(ij):\n    \"\"\"Return the ImageJ ROI Manager instance, creating if needed.\"\"\"\n    RoiManager = ij.py.jclass(\"ij.plugin.frame.RoiManager\")\n    rm = RoiManager.getInstance()\n    if rm is None:\n        rm = RoiManager(False)   # headless=False means no GUI window\n    return rm\n\nrm = get_roi_manager(ij)\nroi_count = rm.getCount()\nprint(f\"ROIs in manager: {roi_count}\")\n\n# Extract bounding boxes for all ROIs\nrois = []\nfor i in range(roi_count):\n    roi = rm.getRoi(i)\n    bounds = roi.getBounds()\n    rois.append({\"index\": i, \"x\": bounds.x, \"y\": bounds.y,\n                 \"width\": bounds.width, \"height\": bounds.height})\nroi_df = pd.DataFrame(rois)\nprint(roi_df.head())\n```\n\n## Common Workflows\n\n### Workflow 1: Automated Fluorescence Quantification\n\n**Goal**: Open a multi-channel TIFF stack, apply Gaussian blur, threshold nuclei channel, run Analyze Particles, and export per-cell measurements as CSV.\n\n```python\nimport imagej\nimport pandas as pd\nimport numpy as np\nfrom pathlib import Path\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\ndef quantify_nuclei(tiff_path: str, output_csv: str,\n                    channel: int = 1, sigma: float = 1.5,\n                    min_size: int = 50) -> pd.DataFrame:\n    \"\"\"\n    Segment and measure nuclei in a fluorescence TIFF.\n\n    Parameters\n    ----------\n    tiff_path  : path to single- or multi-channel TIFF\n    output_csv : where to save results\n    channel    : 1-based channel index for nuclear stain (e.g., DAPI)\n    sigma      : Gaussian blur radius in pixels\n    min_size   : minimum nucleus area in pixels\n    \"\"\"\n    # Step 1: Open image\n    imp = ij.io().open(tiff_path)\n    print(f\"Loaded: {Path(tiff_path).name}  dims={imp.getDimensions()}\")\n\n    # Step 2: Extract channel if multi-channel\n    if imp.getNChannels() > 1:\n        imp.setC(channel)\n\n    # Step 3: Apply Gaussian blur and threshold via macro\n    ij.macro.run(f\"\"\"\nselectWindow(\"{imp.getTitle()}\");\nrun(\"Gaussian Blur...\", \"sigma={sigma}\");\nsetAutoThreshold(\"Otsu dark\");\nrun(\"Convert to Mask\");\nrun(\"Fill Holes\");\nrun(\"Watershed\");\n\"\"\")\n\n    # Step 4: Measure\n    ij.macro.run(f\"\"\"\nrun(\"Set Measurements...\", \"area mean min centroid integrated shape redirect=None decimal=3\");\nrun(\"Analyze Particles...\", \"size={min_size}-Infinity display clear include summarize\");\n\"\"\")\n\n    # Step 5: Collect results\n    rt = ij.ResultsTable.getResultsTable()\n    if rt is None or rt.size() == 0:\n        print(\"No objects detected\")\n        return pd.DataFrame()\n\n    headings = list(rt.getHeadings())\n    df = pd.DataFrame(\n        {col: [rt.getValue(col, i) for i in range(rt.size())]\n         for col in headings}\n    )\n    df[\"source_file\"] = Path(tiff_path).stem\n    df.to_csv(output_csv, index=False)\n    print(f\"Saved {len(df)} measurements → {output_csv}\")\n    return df\n\n\ndf = quantify_nuclei(\n    tiff_path=\"\u002Fdata\u002Fexperiment_dapi.tif\",\n    output_csv=\"nuclei_measurements.csv\",\n    channel=1,\n    sigma=1.5,\n    min_size=50\n)\nprint(df[[\"Area\", \"Mean\", \"Circ.\"]].describe())\n```\n\n### Workflow 2: Batch Fiji Macro Processing\n\n**Goal**: Process a folder of images with an existing Fiji `.ijm` macro file, collect the Results table from each image into a single DataFrame.\n\n```python\nimport imagej\nimport pandas as pd\nfrom pathlib import Path\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\ndef run_macro_on_image(ij, image_path: str, macro_file: str) -> pd.DataFrame:\n    \"\"\"Open one image, run a macro file, return its Results table.\"\"\"\n    ij.io().open(image_path)\n\n    # Clear any previous results before running\n    ij.macro.run(\"run(\\\"Clear Results\\\");\")\n\n    # Run macro file (macro must operate on the active image)\n    ij.macro.runMacroFile(macro_file)\n\n    rt = ij.ResultsTable.getResultsTable()\n    if rt is None or rt.size() == 0:\n        return pd.DataFrame()\n    headings = list(rt.getHeadings())\n    return pd.DataFrame(\n        {col: [rt.getValue(col, i) for i in range(rt.size())]\n         for col in headings}\n    )\n\n\ninput_dir  = Path(\"\u002Fdata\u002Fimages\")\nmacro_file = \"\u002Fscripts\u002Fmeasure_cells.ijm\"\noutput_csv = \"batch_results.csv\"\n\nall_results = []\nimage_files = sorted(input_dir.glob(\"*.tif\"))\n\nfor img_path in image_files:\n    print(f\"Processing: {img_path.name}\")\n    df = run_macro_on_image(ij, str(img_path), macro_file)\n    if not df.empty:\n        df[\"filename\"] = img_path.name\n        all_results.append(df)\n\n    # Close all windows to free memory between images\n    ij.macro.run(\"close('*');\")\n\nif all_results:\n    combined = pd.concat(all_results, ignore_index=True)\n    combined.to_csv(output_csv, index=False)\n    print(f\"Batch complete: {len(image_files)} images, \"\n          f\"{len(combined)} total measurements → {output_csv}\")\nelse:\n    print(\"No results collected from any image\")\n```\n\n## Key Parameters\n\n| Parameter | Module | Default | Range \u002F Options | Effect |\n|-----------|--------|---------|-----------------|--------|\n| `mode` | Initialization | `\"headless\"` | `\"headless\"`, `\"gui\"`, `\"interactive\"` | Controls whether Fiji GUI window opens; use `\"headless\"` for scripts |\n| `endpoint` | Initialization | `\"sc.fiji:fiji\"` | Maven coordinate or `\u002Fpath\u002Fto\u002FFiji.app` | Selects ImageJ2 distribution; `sc.fiji:fiji` includes all Fiji plugins |\n| `sigma` (Gaussian blur) | Macro \u002F Ops | `2.0` | `0.5`–`10.0` | Spatial smoothing radius in pixels; higher reduces noise but blurs edges |\n| `minSize` (Analyze Particles) | Plugin \u002F Macro | `0` | pixels² or `0`–`Infinity` | Smallest object area to include; eliminates noise particles |\n| `method` (Auto Threshold) | Macro \u002F Ops | `\"Otsu\"` | `\"Otsu\"`, `\"Triangle\"`, `\"MaxEntropy\"`, `\"Huang\"`, `\"Li\"` | Threshold algorithm; Otsu works well for bimodal histograms |\n| `measurements` bitmask | Results \u002F Macro | varies | OR combination of `AREA=1`, `MEAN=2`, `CENTROID=4`, etc. | Selects which columns appear in the Results table |\n| Java heap size | Initialization (env) | JVM default (~25% RAM) | set via `JAVA_TOOL_OPTIONS` | Limits memory for large stacks; set `-Xmx8g` for big images |\n\n## Best Practices\n\n1. **Initialize once per session and reuse `ij`**: Starting a new JVM is expensive (5–15 seconds). Create `ij` at module level or pass it as a parameter rather than calling `imagej.init()` inside a loop.\n\n   ```python\n   # At module top level — initialized once\n   import imagej\n   ij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\n   def process(path):\n       imp = ij.io().open(path)   # reuse ij\n       ...\n   ```\n\n2. **Use conda for Java management**: pip-only installs frequently fail because `JAVA_HOME` is not set or the wrong JDK version is on `PATH`. A conda environment with `openjdk=11` avoids 90% of JVM-not-found errors.\n\n3. **Clear Results and ROI Manager between images in batch loops**: ImageJ accumulates results across calls in the same session. Always call `run(\"Clear Results\")` and `rm.reset()` before each image to prevent row contamination.\n\n   ```python\n   ij.macro.run(\"run('Clear Results');\")\n   rm = get_roi_manager(ij)\n   rm.reset()\n   ```\n\n4. **Prefer `ij.macro.run()` for simple commands over `ij.command().run()`**: Macro strings are shorter, easier to read, and use the same syntax as the Fiji Macro Recorder. Use `ij.command().run()` only when you need programmatic access to command outputs (module return values).\n\n5. **Convert to NumPy as late as possible**: `ij.py.from_imageplus()` copies data from the JVM to Python. For multi-step processing inside ImageJ, keep data in ImagePlus or ImgLib2 form and convert only at the end to minimize memory-copy overhead.\n\n6. **Use `ij.py.to_java()` \u002F `ij.py.from_java()` for ImgLib2 Ops**: The `to_imageplus()` \u002F `from_imageplus()` pair works with the classic ImageProcessor; `to_java()` \u002F `from_java()` target the modern ImgLib2 type system required by `ij.op()`.\n\n7. **Set a Fiji update site plugins list during init for reproducibility**: Specify a pinned Fiji version (`sc.fiji:fiji:2.14.0`) rather than `sc.fiji:fiji` (latest) so your pipeline behavior does not change when Fiji releases new plugin updates.\n\n## Common Recipes\n\n### Recipe: TrackMate Headless Spot Detection\n\nWhen to use: Run TrackMate particle tracking programmatically and retrieve detected spots as a DataFrame without opening the TrackMate GUI.\n\n```python\nimport imagej\nimport pandas as pd\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\n# TrackMate headless via macro (scripting interface)\ntrackmate_macro = \"\"\"\nrun(\"TrackMate\", \"\");\n\u002F\u002F For fully scripted TrackMate, use the Scripting Interface\n\u002F\u002F documented at https:\u002F\u002Fimagej.net\u002Fplugins\u002Ftrackmate\u002Fscripting\n\"\"\"\n\n# Scripted TrackMate via Jython-style Java interop\ndef run_trackmate_headless(ij, imp, radius=3.0, threshold=100.0):\n    \"\"\"Detect spots with LoG detector; return DataFrame of spot coordinates.\"\"\"\n    from jnius import autoclass\n\n    # Import TrackMate classes\n    Model          = autoclass(\"fiji.plugin.trackmate.Model\")\n    Settings       = autoclass(\"fiji.plugin.trackmate.Settings\")\n    TrackMate      = autoclass(\"fiji.plugin.trackmate.TrackMate\")\n    LogDetectorFactory = autoclass(\n        \"fiji.plugin.trackmate.detection.LogDetectorFactory\")\n\n    model    = Model()\n    settings = Settings(imp)\n\n    # Configure LoG spot detector\n    settings.detectorFactory = LogDetectorFactory()\n    settings.detectorSettings = {\n        \"DO_SUBPIXEL_LOCALIZATION\": True,\n        \"RADIUS\": radius,\n        \"TARGET_CHANNEL\": 1,\n        \"THRESHOLD\": threshold,\n        \"DO_MEDIAN_FILTERING\": False,\n    }\n\n    tm = TrackMate(model, settings)\n    tm.process()\n\n    # Extract spot table\n    spots = model.getSpots()\n    spots.setVisible(True)\n    records = []\n    for spot in spots.iterable(True):\n        records.append({\n            \"id\":       spot.ID(),\n            \"x\":        spot.getDoublePosition(0),\n            \"y\":        spot.getDoublePosition(1),\n            \"z\":        spot.getDoublePosition(2),\n            \"frame\":    spot.getFeature(\"FRAME\"),\n            \"quality\":  spot.getFeature(\"QUALITY\"),\n        })\n    return pd.DataFrame(records)\n\n\nimp = ij.io().open(\"\u002Fdata\u002Ftimelapse.tif\")\ndf  = run_trackmate_headless(ij, imp, radius=3.0, threshold=50.0)\nprint(f\"Detected {len(df)} spots across {df['frame'].nunique()} frames\")\ndf.to_csv(\"spots.csv\", index=False)\nprint(df.head())\n```\n\n### Recipe: Convert ImageJ Hyperstack to NumPy 5D Array (TZCYX)\n\nWhen to use: Import a multi-dimensional Fiji hyperstack into Python as a 5D NumPy array with the standard TZCYX axis order used by most scientific image analysis libraries.\n\n```python\nimport imagej\nimport numpy as np\n\nij = imagej.init(\"sc.fiji:fiji\", mode=\"headless\")\n\ndef hyperstack_to_numpy(ij, imp) -> np.ndarray:\n    \"\"\"\n    Convert an ImageJ hyperstack to a NumPy array with shape (T, Z, C, Y, X).\n\n    ImageJ internal order is C-Z-T (slowest to fastest in stack index).\n    This function reorders to the TZCYX convention used by tifffile, OME, etc.\n    \"\"\"\n    nC = imp.getNChannels()\n    nZ = imp.getNSlices()\n    nT = imp.getNFrames()\n    H  = imp.getHeight()\n    W  = imp.getWidth()\n\n    arr = np.zeros((nT, nZ, nC, H, W), dtype=np.uint16)\n\n    for t in range(1, nT + 1):\n        for z in range(1, nZ + 1):\n            for c in range(1, nC + 1):\n                idx = imp.getStackIndex(c, z, t)\n                imp.setSlice(idx)\n                arr[t-1, z-1, c-1] = ij.py.from_imageplus(imp)\n\n    return arr\n\n\nimp = ij.io().open(\"\u002Fdata\u002F4d_experiment.tif\")\nprint(f\"ImageJ dims (W,H,C,Z,T): {imp.getDimensions()}\")\n\nstack = hyperstack_to_numpy(ij, imp)\nprint(f\"NumPy TZCYX shape: {stack.shape}\")  # e.g., (10, 15, 2, 512, 512)\nprint(f\"dtype: {stack.dtype}, max: {stack.max()}\")\n\n# Save as OME-TIFF with correct axis metadata\nimport tifffile\ntifffile.imwrite(\n    \"output_TZCYX.ome.tif\",\n    stack,\n    imagej=True,\n    metadata={\"axes\": \"TZCYX\"},\n    photometric=\"minisblack\"\n)\nprint(\"Saved output_TZCYX.ome.tif\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `JVMNotFoundException` on init | `JAVA_HOME` not set or wrong JDK version | Install via conda: `conda install -c conda-forge openjdk=11`; avoid Java 17 |\n| `RuntimeError: Fiji download failed` | No internet or corporate proxy | Download Fiji manually from fiji.sc, then use `imagej.init(\"\u002Fpath\u002Fto\u002FFiji.app\")` |\n| `java.lang.OutOfMemoryError` on large stacks | JVM default heap is too small | Set `export JAVA_TOOL_OPTIONS=\"-Xmx8g\"` before importing imagej |\n| Macro `run(...)` silently does nothing | No active image when macro expects one | Call `ij.io().open(path)` before running processing macros; check `ij.WindowManager.getImageCount()` |\n| Results table empty after Analyze Particles | Threshold not applied, or mask not binary | Verify mask is 8-bit binary (0\u002F255) with `imp.getType() == 0`; run `Convert to Mask` before Analyze Particles |\n| `AttributeError: 'NoneType' object` on `ij.ResultsTable.getResultsTable()` | No measurements run yet in this session | Confirm Analyze Particles macro completed; run `ij.macro.run(\"print(nResults);\")` to check count |\n| Plugin class not found (`ClassNotFoundException`) | Plugin not in this Fiji installation | Add the Fiji update site (e.g., TrackMate) or use `sc.fiji:fiji` endpoint which includes all default plugins |\n| `gui` mode crashes with `HeadlessException` | No display available (SSH\u002Fcluster) | Use `mode=\"headless\"` for remote environments; GUI mode requires `DISPLAY` or X11 forwarding |\n\n## Related Skills\n\n- **scikit-image-processing** — pure Python image processing without JVM; use when Fiji plugins are not needed\n- **napari-image-viewer** — interactive multi-dimensional image viewer for Python; complement to PyImageJ for visualization\n- **trackpy-particle-tracking** — Python-native Crocker-Grier SPT; alternative to TrackMate for simple 2D tracking\n- **cellpose-cell-segmentation** — deep learning cell segmentation; can be run standalone or as a Fiji plugin\n- **omero-integration** — OMERO server image management; PyImageJ can process images retrieved via omero-py\n\n## References\n\n- [PyImageJ documentation](https:\u002F\u002Fpyimagej.readthedocs.io\u002F) — official API reference, initialization guide, data conversion\n- [PyImageJ GitHub repository](https:\u002F\u002Fgithub.com\u002Fimagej\u002Fpyimagej) — source, issue tracker, notebooks, examples\n- [ImageJ Ops framework](https:\u002F\u002Fimagej.net\u002Flibs\u002Fimagej-ops\u002F) — Ops namespace reference and algorithm catalog\n- [TrackMate scripting guide](https:\u002F\u002Fimagej.net\u002Fplugins\u002Ftrackmate\u002Fscripting) — headless TrackMate Java API patterns\n- [Bio-Formats supported formats](https:\u002F\u002Fbio-formats.readthedocs.io\u002Fen\u002Flatest\u002Fsupported-formats.html) — list of proprietary microscopy formats openable via `ij.io().open()`\n- [ImageJ Macro Language reference](https:\u002F\u002Fimagej.nih.gov\u002Fij\u002Fdeveloper\u002Fmacro\u002Fmacros.html) — built-in functions for `ij.macro.run()` strings\n",{"name":5,"license":15,"description":7},"master","63f17866001c5ca854bf2fa0b678ce277133de5b","skills\u002Fawesome-skills\u002Fpyimagej-fiji-bridge",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill pyimagej-fiji-bridge",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill pyimagej-fiji-bridge",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill pyimagej-fiji-bridge","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fpyimagej-fiji-bridge\u002FSKILL.md",true,[],[49,58,65,72,79,86],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":57},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":57},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":57},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":57},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":57},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":57},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]