How to convert ImagePlus to Dataset in a python script

Hi Fiji/ImageJ scripter,

I have already developed a script in which I am using ImagePlus but I want to use the ImageJ Ops opportunity to make operation on images and for that I need to convert the ImagePlus to Dataset and i do not want to rewrite the first part of my script.
If i understand correctly the process, I have written:

ij = ImageJ()
context = ij.getContext()
convertService = context.service(ConvertService.class)
data = convertService.convert(imp, net.imagej.Dataset.class)

And I have this error : AttributeError: instance attr: class

Maybe I missed something but I do not understand why i am getting this error.
Could you help me
thank you by advance
regards
Philippe

1 Like

Hi @philgi and welcome to the forum,

from your description and the post title, I figure you’re using the script editor with Jython, and not a native python via #pyimagej, right? (I ask for clarification because @LThomas added the pyimagej tag to your post, which I think is inaccurate in this case).

Regarding your script, there are several issues:

  • In Python (Jython), you specify Java classes without the .class, just with the class name. That’s what the error message tries to explain.
  • If you create a new ImageJ instance with ij = ImageJ(), it will be a different context than your current Fiji/ImageJ instance, and therefore not be aware of any ImagePlus object you created previously.

I suggest you get the ImageJ context via script parameters. The following modified script works for me in an up-to-date Fiji installation:

#@ ImagePlus imp
#@ ImageJ ij

from net.imagej import ImageJ
from org.scijava.convert import ConvertService
from net.imagej import Dataset

context = ij.getContext()
convertService = context.service(ConvertService)
data = convertService.convert(imp, Dataset)

print data

Alternatively, you can use script parameters to get the ConvertService directly, thereby making the script very concise:

#@ ImagePlus imp
#@ ConvertService convertService

from net.imagej import Dataset

data = convertService.convert(imp, Dataset)

print data

Sorry my mistake, I though ij=ImageJ() is a pyimagej command. I did not know it is used in Fiji too

Hi @imagejan,
thank you for your answer. It is working now. I did know that i do not have to specify “.class” in jython. I am more a java developper
By the way, to be ride of the script parameter “#@ImageJ ij”, I am using:
context = IJ1Helper.getLegacyContext()
thank you again