I am trying to use SimpleITK via PythonCall inside a Pluto notebook. I want to load a DICOM image and then convert it to a numpy array. The code to do this is straightforward and works in pure python, but with PythonCall this produces an error.
It also errors in the other direction, trying to convert julia array to sitk Image
function load_dcm_array(dcm_data::Vector{DICOM.DICOMData})
return array = cat(
[dcm_data[i][tag"Pixel Data"] for i in 1:length(dcm_data)]...; dims=3
)
end
dcms_jl = DICOM.dcmdir_parse(fixed_dicom_dir);
fixed_image_jl = load_dcm_array(dcms_jl);
fixed_image_pyarr = PyArray(fixed_image_jl);
sitk.GetImageFromArray(fixed_image_pyarr)
I figured out that I get the same error if I run this in a Jupyter notebook using Python kernel. And after restarting the kernel, the error goes away. Maybe something like that is occurring in Julia?
I have only briefly looked at how PythonCall.jl links to Python, but I think that since it is already imported, PythonCall.jl is pointing to the original Python version (3.11).
One fix would be to create the environment before importing PythonCall.jl. This can be done with a CondaPkg.toml file, or the following modification to your code:
This is a known (but undocumented) gotcha - similar to how you shouldnβt install Julia packages after importing anything (it can lead to incompatible packages) - only in this case itβs the python interpreter itself which is incompatible, with more disastrous consequences.
I.e. 3.9, but itβs unclear to me why. SimpleITK supports 3.11, and in Conda, i.e. conda-forge, 3.11 is support (as opposed to Anaconda, which supports at least 3.10 seemingly).
Python 3.9 should still work (with or without Julia).
What version of Julia are you using? PythonCall.jl adds libstdcxx-ng bounds in conda to ensure that the Python packages are compatible with Julia. This means that the latest Python package versions may not be installed when using older Julia versions since there would be incompatibilities. With Julia v1.9.3, your original code runs for me without any errors.
Additionally, CondaPkg.jl uses the channel conda-forge by default. This version of SimpleITK is being installed: Simpleitk :: Anaconda.org. To install the simpleitk channel version, you can specify the channel when adding the package. CondaPkg.add("SimpleITK"; channel="simpleitk"). However, I think the conda-forge version is more up to date.