Cast Exception when obtaining the firstElement() of an image

I am getting a cast exception when trying to get the firstElement() of an image.
This is the part of my code that fails:

39 Img lineImg = ops.create().img( imgp );
40 RandomAccess ra = lineImg.randomAccess();
41 ByteType elmnt = lineImg.firstElement();
42 double maxV = elmnt.getMaxValue();

***imgp is an ImgPlus

The error says the following:

[ERROR] Module threw exception
java.lang.ClassCastException: net.imglib2.type.numeric.integer.UnsignedShortType cannot be cast to net.imglib2.type.numeric.integer.ByteType
at testing.test_ops.run(test_ops.java:41)
at org.scijava.command.CommandModule.run(CommandModule.java:199)
at org.scijava.module.ModuleRunner.run(ModuleRunner.java:168)
at org.scijava.module.ModuleRunner.call(ModuleRunner.java:127)
at org.scijava.module.ModuleRunner.call(ModuleRunner.java:66)
at org.scijava.thread.DefaultThreadService$3.call(DefaultThreadService.java:238)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

What is confusing me is that the description of firstElement() says it expects a ByteType.
“ByteType net.imglib2.IterableRealInterval.firstElement()”
image
Any help is much appreciated!

Hi @Rody,

Thing is, while you write your code, your IDE cannot know the type of your Img (and RandomAccess). They could be ByteType, ShortType. In this case, it seems your ImagePlus at the beggining is of UnsignedShortType. If it will always be UnsignedShortType you could do this

Img<UnsignedShortType> lineImg = ops.create().img( imgp );
RandomAccess<UnsignedShortType> ra = lineImg.randomAccess();
UnsignedShortType elmnt = lineImg.firstElement();
double maxV = elmnt.getMaxValue();

If you do not know the Type of your image initially (You’ll be working with different image types (8-bit, 16-bit, etc…) you probably need to have your class declaration like this

public class MyClass<T extends RealType<T>> implements... 

But at some point, when you actually need to use the value, you will have to convert it…

So you can convert your initial image to the type you want (Like 32-bits) and then work everything from there…

Img<FloatType> lineImg = ij.op( ).convert( ).float32( imgp );
...

Then you can keep on working with FloatType

Note that I am by no means an expert, but hopefully this is useful. :smile:

1 Like

Thank you for your reply @oburri, I initialized the imgp as ImgPlus < ByteType >. Also I forgot to mention that the error occurs at line 41 : ByteType elmnt = lineImg.firstElement();