File Exchange

image thumbnail

3D structuring element (sphere)

version (1.77 KB) by Luke Xie

Luke Xie (view profile)

strel3d creates a sphere as a 3D structuring element, which is important for 3D datasets


Updated 29 Sep 2014

View License

STREL3D creates a 3D sphere as a structuring element. Three-dimensional structuring elements are much better for morphological reconstruction and operations of 3D datasets. Otherwise the traditional MATLAB "strel" function will only operate on a slice-by-slice approach. This function uses the aribtrary neighborhood for "strel."


sesize - desired diameter size of a sphere (any positive integer)

the structuring element as a strel class (can be used directly for imopen, imclose, imerode, etc)


2014/09/26 - LX
2014/09/27 - simplification by Jan Simon

Comments and Ratings (6)

I've found it useful to use ellipsoidal elements. This seems to work. xr,yr,zr are the radii of the ellipsoid in each direction. Might need some refining?

%% 3D ellipsoid

xbase = 1:2*xr+1;
ybase = 1:2*yr+1;
zbase = 1:2*zr+1;
[xm,ym,zm] = ndgrid( xbase , ybase , zbase) ;

xc = xr + 1;
yc = yr + 1;
zc = zr + 1;

mask = ( ((xm-xc).^2/(xr.^2)) + ((ym-yc).^2/(yr.^2)) + ((zm-zc).^2/(zr.^2)) <= 1 ) ;
se = strel('arbitrary',mask);

Luke Xie

Luke Xie (view profile)

Gavin -
I received the same error and cannot get around it. Seems like 3D structuring elements are not supported by gpuArray. If you discover anything in the future, please share.


Gavin (view profile)

Very useful code. But when I tried to use it with the GPU array I encountered this hurdle:

'gpuarrayIM must be a gpuArray of type uint8 or logical. When used with a gpuarray, the structuring element must be flat and two-dimensional.'

Any idea if there is a way to sneak a 3D strel onto the gpu?


Gavin (view profile)

Luke Xie

Luke Xie (view profile)

Jan Simon -
Excellent catch. Your simplification is ~1.2x faster. The code is now updated.


Jan (view profile)

A simplification:

sw = (sesize-1)/2;
ses2 = ceil(sesize/2);
[y,x,z] = meshgrid(-sw:sw, -sw:sw, -sw:sw);
m = sqrt(x.^2 + y.^2 + z.^2);
b = (m <= m(ses2, ses2, sesize));
se = strel('arbitrary', b);


includes simplification suggested by Jan Simon

MATLAB Release Compatibility
Created with R2012b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Discover Live Editor

Create scripts with code, output, and formatted text in a single executable document.

Learn About Live Editor