How can I use ImageJ from within a MATLAB function?

matlab
imagej
Tags: #<Tag:0x00007fb88363df88> #<Tag:0x00007fb88363ddf8>

#1

ImageJ-MATLAB’s ImageJ command in MATLAB will launch an instance of Fiji from within MATLAB command window.

addpath '/Applications/Fiji.app/scripts'
ImageJ

This will create an net.imagej.matlab.ImageJMATLABCommands Java object named IJM in MATLAB base workspace. And this IJM offers verious useful tools for communication between MATLAB and ImageJ, for example IJM.show(name) to show a MATLAB array as an image in ImageJ.

However, how can I use ImageJ from within a MATLAB function, rather than from base workspace?

For example, following code launches Fiji from within a function, but workspace of test1 is empty, because IJM is always created in base workspace. So, you cannot use IJM.show() within test1.

function test1()

addpath '/Applications/Fiji.app/scripts'
ImageJ

w = who

end
w =

  0×0 empty cell array

#2

You can make IJM gobal, or create a global copy of IJM in base workspace from a script, so that you can access IJM from any function workspace.

addpath '/Applications/Fiji.app/scripts'
ImageJ
global IJM % turn IJM into a global 

The example below is a little bit more complicated, but future versions of MATLAB won’t accept the conversion of an already existing non-global variable to global.

addpath '/Applications/Fiji.app/scripts'
ImageJ
global ijm % this way you can avoid conversion of IJM to be global.
ijm = IJM;
clear IJM

Then in your function, you declare global again for IJM or ijm to make it available within the function workspace.

function test2()

global ijm % or global IJM

A = zeros(512,512);

assignin('base','A____temp',A) % to avoid potential confilect with another variable in base workspace, use a weird name
IJM.show('A____temp') % IJM.show() can only work with a variable in base workspace. 
evalin('base','clear A____temp'); % to release memory

end


#3

You don’t need to use global. You can use assignin and evalin to access IJM object in the MATLAB base workspace.

Execute the following in the base workspace.

addpath '/Applications/Fiji.app/scripts'
ImageJ % this will add IJM to base workspace

The MATLAB function below can plot the array A with IJM.show()

function test3()

A = zeros(512,512);

assignin('base','A____temp',A); 
% to avoid potential conflict with another variable in base workspace, use a weird name

assert(evalin('base','exist(''IJM'',''var'')') == 1) % assert IJM exist

assert(evalin('base','isa(IJM,''net.imagej.matlab.ImageJMATLABCommands'')')) % assert the class  of IJM exist

evalin('base','IJM.show(''A____temp'')'); % use IJM.show() in base workspace

evalin('base','clear A____temp'); % to release memory

end