Trying to use cooccurencematrix

Tags: #<Tag:0x00007fb87e46d618>


I am trying to use cooccurencematx and the constructor is empty

coocm = new CooccurrenceMatrix2D();
glcm = coocm.compute(img);

The program crashes on the constructor.
Somehow I need to tell it what orientation to use, presumably in the compute routine, but that has only an iterative image as input. Is there some example code I can use which uses the basic elements of the class?



Dear @ilan,

I assume you are talking about CooccurrenceMatrix2D from imagej-ops? If that’s the case, please take a look at the tutorial on what ops are and how to use them:



Thanks for the reply Stefan.
I am trying to use this which uses the function directly.

For example I build an ImageJ ImagePlus which I wrap

ImagePlus imp = new ImagePlus("radio", stk1);
Img < T > img = ImagePlusAdapter.wrap(imp);

and I can use that to find the min and max.
Not that I really need to min and max, it was just an exercise to see everything is working.

The cooccurrence matrix crashes on the constructor in some future task run program.
It is as if I am doing something wrong, but what can one do wrong with an empty contructor?



The Ops framework does alot of stuff behind the scenes…

If you post the error message you’re getting, it would be helpful for the folks here to help you figure out.

That being said, the “right” way of using ops is given in the tutorial @stelfrich linked to above.
e.g. this worked ( read didn’t crash ) for me:

int nGray = 8;
int dist = 2;
double[][] res = ij.op().image().cooccurrenceMatrix( composite, nGray, dist, MatrixOrientation2D.HORIZONTAL);

Hope this helps,


Thanks again for your patience with me. I am obviously doing something stupid, but I don’t know what.
My code looks like

		ImagePlus imp = new ImagePlus("radio", stk1);
		ImageJ  ij = IJ.getInstance();
		Img < T > img = ImagePlusAdapter.wrap(imp);
//		glcm = ij.op().img().cooccurrenceMatrix( 0, 0, 0, MatrixOrientation2D.HORIZONTAL);
		coocm = new CooccurrenceMatrix2D();

First, for the error message, it is in

    public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result =;
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;

I catch it in result = null; It is inside the constructor call.

The glcm = ij.op()… is commented out because I can’t satisfy any import for op().
Ignore the 3 zeros, as I will fill in something else when op() can be satisfied.
Presumably I need an additonal jar file.

Thanks again,


You’ll have to add net.imagej:imagej-ops as a dependency.

Also, the ij that @bogovicj is using in his example is an instance of net.imagej.ImageJ not ij.ImageJ (which I assume you are importing). Are you implementing a standalone application or something that’s supposed to be run within ImageJ/Fiji?


Thanks. My application is a Fiji plugin
So one stupid mistake is using the wrong ij.
Presumably, I need to make a new instance of that since my existing instance is a standard ij object.
I’ll poke around to find what I need.


I’ve made some progress. My code now looks like

		ImagePlus imp = new ImagePlus("radio", stk1);
		Img < T > img = ImagePlusAdapter.wrap(imp);
		IterableInterval<T> it1 = (IterableInterval<T>) img;
		net.imagej.ImageJ  ij = new net.imagej.ImageJ();
		glcm = ij.op().image().cooccurrencematrix( it1, COOCCURRENCE_HI, 2, MatrixOrientation2D.HORIZONTAL);

Presumably I still don’t have the ij correct. The compilation is OK but the constructor for the net.imagej.ImageJ crashes with the same, at the same position.
One other question while i am at it. I have the distance at 2, as in the example. Does 2 mean nearest neighbor, or should I use 1 for that?


If your code is executed from within Fiji, then there already is a Context (which is what the net.imagej.ImageJ constructor creates). If you are implementing something as a SciJava Command, you are able to use the @Parameter annotation to directly get hold of an OpService (which is what ij.op() returns). If you want to see what that looks like in code, take a look at one of the examples:

You can also find more information on Commands and Plugins at as well as a collection of helpful resources at's_Perspective#Details_of_Writing_Plugins.


I’m still stuck on the

net.imagej.ImageJ  ij = new net.imagej.ImageJ();

missing what context it should have. My project is based upon that classic ImageJ and not upon net.imagej.ImageJ.
I looked at all the links. OpenScaleSaveImage is using net.imagej.ImageJ, which is what I need to create. The context is supposed to be created when the application starts, but I started the classic version.

I can do Object con = IJ.getInstance().getAccessibleContext(); but it isn’t clear that accessible context is what I want. There is also getInputContext(), which probably not what I want.

My plugin does
public class Pet_Ct_Viewer implements PlugIn {

I can change that to
public class Pet_Ct_Viewer {
if that would help anything.

Thanks again for the help.


Hi @ilan,

As you’re using an update site for PET-CT Viewer, you do use an ImageJ2 feature already :slight_smile:. It should be relatively straightforward to implement your plugin as an org.scijava.Plugin instead of an ij.plugin.PlugIn, and get the @OpService for free as a plugin parameter that lets you use Ops with ease. For combining ImageJ2/SciJava commands with ImageJ1 classes, you can take the mixed-world-command tutorial as an example:

In general, it would help if you posted the full stack trace here, so others can draw their own conclusions and give better advice.

I noticed you have the source code on github:

but the latest commits are from eight years ago. It might also help others helping you if you link to complete examples on github, instead of posting code snippets that aren’t self-contained.


Thanks Jan,
As you see a lot of my code is old. I am taking your advice and switching over a couple of plugins to net.imagej.ImageJ.
In OpenScaleSaveImage there is a convience main:

 * This main method is for convenience - so you can run this command
 * directly from Eclipse (or other IDE).
 * It will launch ImageJ and then run this command using the CommandService.
 * This is equivalent to clicking "Tutorials>Open+Scale+Save Image" in the UI.
public static void main(final String... args) throws Exception {
	// Launch ImageJ as usual.
	final ImageJ ij = net.imagej.Main.launch(args);

	// Launch the "OpenScaleSaveImage" command.
	ij.command().run(OpenScaleSaveImage.class, true);

This is supposed to be for launching the app from inside the IDE and I would like to exploit it to launch my updated app, but I have no idea what the args should be inside final ImageJ ij = net.imagej.Main.launch(args);.
An empty string and null fail, so what could be a valid argument?

There is a lot of work to convert over all my plugins, so I will try it one step at a time.


To try and get what args are used, I converted over one of my plugins and ran it from Netbeans.
The idea was I could put a break point at the start of the main and look at the args which was passed in.
The first line of the main had my breakpoint, which it never reached.

import net.imagej.ImageJ;
import org.scijava.command.Command;
import org.scijava.plugin.Plugin;

 * @author ilan
@Plugin(type = Command.class, menuPath = "Plugins>Nuclear Medicine>Avataxer")
public class Ava_taxer implements Command {

	public void run() {
		if( Avataxer.instance != null) return;
		Avataxer dlg = new Avataxer(null, false, "ava");

	public static void main(final String... args)  {
		// Launch ImageJ as usual.
		int i = 0;
//		ImageJ ij = net.imagej.Main.launch(args);

		// Launch the "Ava_taxer" command.
//		ij.command().run(Ava_taxer.class, true);

Since it never reached the first line: int i = 0; I decided to go one step further and comment out the launch.
Even after commenting out the launch, the debug log showed that something tried to use it.


[ECLIPSE HELPER] Indexing annotations...
Exception in thread "main" java.lang.IllegalArgumentException: Invalid service: io.scif.img.cell.cache.MapDBCache
	at org.scijava.service.ServiceHelper.createExactService(
	at org.scijava.service.ServiceHelper.loadService(
	at org.scijava.service.ServiceHelper.loadService(
	at org.scijava.service.ServiceHelper.loadServices(
	at org.scijava.Context.<init>(
	at org.scijava.Context.<init>(
	at org.scijava.Context.<init>(
	at org.scijava.Context.<init>(
	at net.imagej.ImageJ.<init>(
	at net.imagej.Main.launch(
	at Ava_taxer.main(
Caused by: java.lang.NullPointerException
	at java.util.ArrayList.addAll(
	at org.scijava.util.ClassUtils.getAnnotatedFields(
	at org.scijava.util.ClassUtils.getAnnotatedFields(
	at org.scijava.service.ServiceHelper.createServiceRecursively(
	at org.scijava.service.ServiceHelper.createExactService(
	... 10 more
/home/ilan/.cache/netbeans/8.1/executor-snippets/debug.xml:83: Java returned: 1

The bottom line is I need something, anything at all, which will do the job and give me an
final ImageJ ij = net.imagej.Main.launch(args);

It does have to be launch, a wrapper on the legacy IJ would do just as well.
I do however need SOMETHING.



Sorry, I’m not sure why it doesn’t work (@ctrueden or @stelfrich might be able to tell you more), and I’m not using Netbeans. But maybe I should’ve pointed you to a more up-to-date example for an IJ2 command, example-imagej-command. It has a slightly different convenience main() method that should work:

Can you try this? Anyhow, the main() method should not interfere with the functionality of the plugin, as it is merely used to start the plugin from an IDE, but not when run from within ImageJ.


First and foremost I would like to sincerely thank everyone for their generous help.
I couldn’t have done it without your help.

My original question as to the value of args in
public static void main(final String… args)
is that for Netbeans it is a String array of length zero.

I used Jan’s suggestion and replaced
ImageJ ij = net.imagej.Main.launch(args);
final ImageJ ij = new ImageJ();

It was simpler and had no args problem.
The error message was the same so I guessed I was missing some jar files.
Instead of a shotgun approach, I went into the source code to see what the problem might be.
If you want to run the program from Eclipse or Netbeans, there is a minimum number of jar files which must be present in the libraries tab.
I made a screen shot of my properties window and the ones in red must be included.

The Pet_Ct_Viewer.jar is obviously just for this application and the ij.jar I need because I use IJ.log() for errors.
The red ones are the needed glue.

Not that I really have any intention of running the plugin directly from Netbeans, but it was in fact a nice way to start with a simple case before moving on to the real problem. The ImageJ ij = new ImageJ(); was what killed me way back when.

Thanks again for all your help,


I guess using Maven would have helped you to avoid all those troubles. The whole purpose of Maven is to make sure that all the (direct and indirect) dependencies are present on your classpath when you start your application.

Here’s the dependencies of imagej as they’re shown in Eclipse:


The minimum I got is less than what you have. On the other hand, that plugin is running only legacy programs.
The minimum I got is enough to run the command to activate the plugin.
Without my list the won’t work. With the list, it will.