Scripted Module: How to install and import tensorflow-cpu on M2 Mac

Hey up until recently I used an Intel Mac and was able to import and use tensorflow and my first ever extension worked fine :slight_smile:

With the M2 Mac Slicer crashes when the module tries to install tensorflow by slicer.util.pip_install("tensorflow") .

Installing the cpu-only version seems work: slicer.util.pip_install("tensorflow-cpu") but when I try to import it it seems to crash again. import tensorflow as tf

Thanks a lot for your patience.

In recent years, pytorch has become the dominant AI framework in medical image computing and all Slicer extensions use pytorch and not tensorflow. They use the PyTorch Slicer extension to install and configure PyTorch and it runs well on all platforms.

I’m not sure if anyone would want to invest time now into exploring how to install and run tensorflow in Slicer, so if you want to keep using tensorflow then it may be easier to run it outside Slicer’s Python environment. You can keep everything in the same in your Python scripted module except that you use tensorflow in the external Python environment (run the external Python.exe using slicer.util.launchConsoleProcess).

I converted my tensorflow model to ONNX format.
slicer.util.pip_install("onnxruntime") works and my extension is able to get similar result!

Is there a guide for optimal deployment of ML models in 3D Slicer?

Also is there proper way to install python libraries (ideally from a requirements.txt file)?
Currently I’m checking/installing them when the Slicer App initialises the Modules:

for module in requirements:
    try:
        importlib.import_module(module)
    except ModuleNotFoundError:
        slicer.util.pip_install(module)

Any relevant code example for this:

slicer.util.launchConsoleProcess

Thanks for taking your time!