imagej / pyimagej

Use ImageJ from Python
https://pyimagej.readthedocs.io/
Other
462 stars 81 forks source link

TypeError: 'NoneType' object is not callable when initializing imagej #308

Open belenal opened 1 month ago

belenal commented 1 month ago

This is my code:

import scyjava as sj

def print_classpath():
    System = sj.jimport('java.lang.System')
    import re
    classpath = re.split('[:;]', str(System.getProperty('java.class.path')))
    print("\n".join(classpath))

sj.when_jvm_starts(print_classpath)

import imagej

import jpype
import jpype.imports
from jpype.types import *

jvm_path = "C:\\Program Files\\Eclipse Adoptium\\jdk-8.0.362.9-hotspot\\jre\\bin\\server\\jvm.dll"

if not jpype.isJVMStarted():
    jpype.startJVM(jvm_path, "-ea")
    print("JVM started successfully!")

if jpype.isJVMStarted():
    print("JVM is running!")
else:
    raise RuntimeError("Failed to start JVM")

ij = imagej.init()
print("ImageJ initialized successfully!")

and I am getting:

JVM started successfully!
JVM is running!
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_18744\3541298497.py in <module>
     29 
     30 
---> 31 ij = imagej.init(['net.imagej:imagej:2.1.0', 'net.imagej:imagej-legacy'])
     32 
     33 # Inicializar Fiji

c:\Users\\AppData\Local\Programs\Python\Python37\lib\site-packages\imagej\__init__.py in init(ij_dir_or_version_or_endpoint, mode, add_legacy, headless)
   1236     else:
   1237         # HEADLESS or INTERACTIVE mode: create the gateway and return it.
-> 1238         return _create_gateway()
   1239 
   1240 

c:\Users\\AppData\Local\Programs\Python\Python37\lib\site-packages\imagej\__init__.py in _create_gateway()
   1266         return False
   1267 
-> 1268     ij = ImageJ()
   1269 
   1270     # Forward stdout and stderr from Java to Python.

TypeError: 'NoneType' object is not callable

I am using python 3.7.9. I also tried using Python 3.9 and downloading pyimagej from github, and I get:

TypeError                                 Traceback (most recent call last)
Cell In[1], [line 31](vscode-notebook-cell:?execution_count=1&line=31)
     [27](vscode-notebook-cell:?execution_count=1&line=27) else:
     [28](vscode-notebook-cell:?execution_count=1&line=28)     raise RuntimeError("Failed to start JVM")
---> [31](vscode-notebook-cell:?execution_count=1&line=31) ij = imagej.init()
     [33](vscode-notebook-cell:?execution_count=1&line=33) # Inicializar Fiji
     [34](vscode-notebook-cell:?execution_count=1&line=34) #ij = imagej.init(["net.imagej:imagej", "sc.fiji:fiji", "org.morphonets:SNT:4.2.1"])
     [35](vscode-notebook-cell:?execution_count=1&line=35) #ij = imagej.init('C:/Users//Downloads/Fiji.app/Fiji.app/')  # Ajusta el path a la ubicación de tu instalación de Fiji
     [36](vscode-notebook-cell:?execution_count=1&line=36) #ij = imagej.init('C:\\Users\\\\Downloads\\fiji-win64\\Fiji.app')
     [37](vscode-notebook-cell:?execution_count=1&line=37) #ij = imagej.init('C:\\Users\\\\Downloads\\ij154-win-java8\\ImageJ')
     [38](vscode-notebook-cell:?execution_count=1&line=38) print("ImageJ initialized successfully!")

File c:\Users\\AppData\Local\Programs\Python\Python39\lib\site-packages\imagej\__init__.py:1249, in init(ij_dir_or_version_or_endpoint, mode, add_legacy, headless)
   [1246](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1246)         return None
   [1247](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1247) else:
   [1248](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1248)     # HEADLESS or INTERACTIVE mode: create the gateway and return it.
-> [1249](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1249)     return _create_gateway()

File c:\Users\\AppData\Local\Programs\Python\Python39\lib\site-packages\imagej\__init__.py:1279, in _create_gateway()
   [1270](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1270)     _logger.error(
   [1271](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1271)         "***Invalid initialization: ImageJ2 was not found***\n"
   [1272](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1272)         "Please update your initialization call to include an ImageJ2 "
   (...)
   [1275](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1275)         "be started once."
...
   [1281](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1281) # Register a Python-side script runner object, used by the
   [1282](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1282) # org.scijava:scripting-python script language plugin.
   [1283](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1283) if callable(getattr(sj, "enable_python_scripting", None)):

TypeError: 'NoneType' object is not callable

I used doctor checkup and everything looks fine:

Checking Python:
--> Python executable = [c:\Users\\AppData\Local\Programs\Python\Python39\python.exe](file:///C:/Users//AppData/Local/Programs/Python/Python39/python.exe)

Checking environment:
--> It looks like you are NOT running inside a Conda environment.

Checking Python dependencies:
--> jgo: [c:\Users\\AppData\Local\Programs\Python\Python39\lib\site-packages\jgo\__init__.py](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/jgo/__init__.py)
--> scyjava: [c:\Users\\AppData\Local\Programs\Python\Python39\lib\site-packages\scyjava\__init__.py](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/scyjava/__init__.py)
--> imglyb: [c:\Users\\AppData\Local\Programs\Python\Python39\lib\site-packages\imglyb\__init__.py](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imglyb/__init__.py)
--> pyimagej: [c:\Users\\AppData\Local\Programs\Python\Python39\lib\site-packages\imagej\__init__.py](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py)

Checking Maven:
--> Maven executable = [C:\Users\\Downloads\apache-maven-3.9.8-bin\apache-maven-3.9.8\bin\mvn.CMD](file:///C:/Users//Downloads/apache-maven-3.9.8-bin/apache-maven-3.9.8/bin/mvn.CMD)
$ mvn -v
Apache Maven 3.9.8 (36645f6c9b5079805ea5009217e36f2cffd34256)
Maven home: [C:\Users\\Downloads\apache-maven-3.9.8-bin\apache-maven-3.9.8](file:///C:/Users//Downloads/apache-maven-3.9.8-bin/apache-maven-3.9.8)
Java version: 1.8.0_362, vendor: Temurin, runtime: [C:\Program](file:///C:/Program) Files\Eclipse Adoptium\jdk-8.0.362.9-hotspot\jre
Default locale: es_ES, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

Checking Java:
--> JAVA_HOME = [C:\Program](file:///C:/Program) Files\Eclipse Adoptium\jdk-8.0.362.9-hotspot
--> Java executable = [C:\Program](file:///C:/Program) Files\Eclipse Adoptium\jdk-8.0.362.9-hotspot\bin\java.EXE
...
OpenJDK 64-Bit Server VM (Temurin)(build 25.362-b09, mixed mode)

Questions and advice for you:
--> Did you intend to activate a Conda environment?

Any idea what might be the problem? I have tried all the possible initializations endpoints and I keep getting the same error. Thank you

elevans commented 1 month ago

Hi @belenal,

You shouldn't need to configure or start the JVM before initializing ImageJ. These things are handled internally as part of the initialization routine. See the PyImageJ initialization documentation here for more info.

It looks like you're not using a conda/mamba environment. Can you try to install and initialize PyImageJ via mamba? This installation path is what we recommend most folks use as it'll ensure you'll have all the components you need to successfully get PyImageJ working. Here are the installation instructions.

belenal commented 1 month ago

Hello @elevans I configured the start because otherwise I get:

Failed to bootstrap the artifact.

Possible solutions:
* Double check the endpoint for correctness (https://search.maven.org/).
* Add needed repositories to [~/.jgorc](https://file+.vscode-resource.vscode-cdn.net/c%3A/Users//~/.jgorc) [repositories] block (see README).
* Try with an explicit version number (release metadata might be wrong).

Full Maven error output:
    [ERROR] [ERROR] Some problems were encountered while processing the POMs:
    [ERROR] Non-resolvable import POM: The following artifacts could not be resolved: net.imagej:imagej:pom:RELEASE: Failed to resolve version for net.imagej:imagej:pom:RELEASE: Could not find metadata net.imagej:imagej/maven-metadata.xml in local (C:\Users\\.m2\repository) @ line 8, column 29
    [ERROR] 'dependencies.dependency.version' for net.imagej:imagej-legacy:jar is missing. @ line 10, column 256
    [ERROR] 'dependencies.dependency.version' for org.scijava:scijava-config:jar is missing. @ line 10, column 466
    [ERROR] The build could not read 1 project -> [Help 1]
    [ERROR]   
    [ERROR]   The project net.imagej-BOOTSTRAPPER:imagej-BOOTSTRAPPER:0 (C:\Users\\.jgo\net.imagej\imagej\RELEASE\28b74e6959b0634f2a8e10c27afe06e7039fb4a0dc582d9746d028ba40e5bd04\pom.xml) has 3 errors
    [ERROR]     Non-resolvable import POM: The following artifacts could not be resolved: net.imagej:imagej:pom:RELEASE: Failed to resolve version for net.imagej:imagej:pom:RELEASE: Could not find metadata net.imagej:imagej/maven-metadata.xml in local (C:\Users\\.m2\repository) @ line 8, column 29 -> [Help 2]
    [ERROR]     'dependencies.dependency.version' for net.imagej:imagej-legacy:jar is missing. @ line 10, column 256
    [ERROR]     'dependencies.dependency.version' for org.scijava:scijava-config:jar is missing. @ line 10, column 466
    [ERROR] 
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR] 
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
    [ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException
...
***Invalid Initialization: you may be using a primary endpoint that lacks pom-scijava as a parent***
To keep all Java components at compatible versions we recommend using a primary endpoint with a pom-scijava parent.
For example, by putting 'net.imagej:imagej' first in your list of endpoints.
If you are sure you DO NOT want a primary endpoint with a pom-scijava parent, please re-initialize with 'add_legacy=False'.
Output is truncated. View as a [scrollable element](command:cellOutput.enableScrolling?a582276b-f09d-4e12-816b-5b412259a737) or open in a [text editor](command:workbench.action.openLargeOutput?a582276b-f09d-4e12-816b-5b412259a737). Adjust cell output [settings](command:workbench.action.openSettings?%5B%22%40tag%3AnotebookOutputLayout%22%5D)...

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[1], [line 2](vscode-notebook-cell:?execution_count=1&line=2)
      [1](vscode-notebook-cell:?execution_count=1&line=1) import imagej
----> [2](vscode-notebook-cell:?execution_count=1&line=2) ij = imagej.init()

File c:\Users\\AppData\Local\Programs\Python\Python39\lib\site-packages\imagej\__init__.py:1213, in init(ij_dir_or_version_or_endpoint, mode, add_legacy, headless)
   [1211](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1211)     success = _create_jvm(ij_dir_or_version_or_endpoint, mode, add_legacy)
   [1212](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1212)     if not success:
-> [1213](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1213)         raise RuntimeError("Failed to create a JVM with the requested environment.")
   [1215](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1215) if mode == Mode.GUI:
   [1216](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1216)     # Show the GUI and block.
   [1217](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1217)     if macos:
   [1218](file:///C:/Users//AppData/Local/Programs/Python/Python39/lib/site-packages/imagej/__init__.py:1218)         # NB: This will block the calling (main) thread forever!

RuntimeError: Failed to create a JVM with the requested environment.

I cannot use mamba or conda that is why I am trying via pip.

ctrueden commented 1 month ago

@belenal Your first error TypeError: 'NoneType' object is not callable happens when the net.imagej.ImageJ class is not present on the classpath, which happens when you start the JVM manually without configuring a classpath.

The Maven error you are seeing—when running imagej.init() immediately as @elevans suggested—is unfortunate. The crux of the error message is:

Non-resolvable import POM: The following artifacts could not be resolved: net.imagej:imagej:pom:RELEASE: Failed to resolve version for net.imagej:imagej:pom:RELEASE

This looks like a bug in Maven to me. I see you are running 3.9.8, which is a very new version. IIRC, there was a similar bug in Maven 3.9.7 which was supposedly fixed, but it seems 3.9.8 still has problems? Could you please try with version 3.9.6 and see if you can import imagej; ij = imagej.init(); print(ij.getVersion())?

(I have plans in the near term to replace jgo's Maven dependency resolution with a pure-Python implementation, which will make these mvn bugs moot...)

belenal commented 1 month ago

I downloaded 3.9.6 and the problem persists.

I am getting this error:

Full Maven error output:
    [ERROR] [ERROR] Some problems were encountered while processing the POMs:
    [ERROR] Non-resolvable import POM: The following artifacts could not be resolved: net.imglib2:imglib2-imglyb:pom:1.1.0 (absent): Could not transfer artifact net.imglib2:imglib2-imglyb:pom:1.1.0 from/to scijava.public (https://maven.scijava.org/content/groups/public): PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target @ line 8, column 29
    [ERROR] The build could not read 1 project -> [Help 1]
    [ERROR]   
    [ERROR]   The project net.imglib2-BOOTSTRAPPER:imglib2-imglyb-BOOTSTRAPPER:0 (C:\Users\beia\.jgo\net.imglib2\imglib2-imglyb\1.1.0\0414d8274ab28cfc94250aa08011fc25de85a945899109fb7b2eca48a45f0983\pom.xml) has 1 error
    [ERROR]     Non-resolvable import POM: The following artifacts could not be resolved: net.imglib2:imglib2-imglyb:pom:1.1.0 (absent): Could not transfer artifact net.imglib2:imglib2-imglyb:pom:1.1.0 from/to scijava.public (https://maven.scijava.org/content/groups/public): PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target @ line 8, column 29 ->

Actually the file in Fiji.app/jars/ is imglib2-imglyb-2.0.0. I think this might be the problem? how can I indicate the version I want? Thank you

ctrueden commented 1 month ago

@belenal The error is different now. Progress!

PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

This error means it is having trouble downloading things securely over HTTPS due to disliking the certificate. It might be a problem with that version of Java. Could you please try with OpenJDK 11 rather than OpenJDK 8?