pluton
pluton

Reputation: 242

Visualize a 3D image in Matlab

Think of a 3 dimensional image V stored, in matlab, as an array for red, green, and blue. For pixel (i,j,k) we would have

V(i,j,k,1)=0.1 (red)
V(i,j,k,2)=0.9 (green)
V(i,j,k,3)=0.2 (blue)

I would then like to visualize this 3D image as a moving 2D slice. I thought the "slice" command could do the trick but it is designed to visualize 3D functions only, not 3D images. Do you have any suggestion?

I am adding a script that could help but does not achieve what is requested:

clear all; clc; close all;

N=35;
w=zeros(N,N,N);
x=linspace(-5,5,N); y=linspace(-5,5,N); z=linspace(-5,5,N);

for i=1:N
    for j=1:N
        for k=1:N
            w(i,j,k)=cos(k)/(1+i+j)^2;
        end
    end
end

for k = 0:.1:10
hsp = surf(linspace(-5,5,Nx),linspace(-5,5,Ny),zeros(Nz));
rotate(hsp,[1,0,0],18*k,[0 0 0]) %rotate a slice where the image is shown
xd = hsp.XData;
yd = hsp.YData;
zd = hsp.ZData;
delete(hsp)
slice(x,y,z,w,xd,yd,zd)
shading flat
hold off
view(-25,20)
axis([-5 5 -5 5 -5 5]);
drawnow
end

The above w array should now be a 3D image instead.

Upvotes: 1

Views: 375

Answers (1)

KQS
KQS

Reputation: 1597

It sounds like you want the functionality of slice but you want it to operate on an [N x M x P x 3] array instead of an [N x M x P] array.

One way to do this is by setting up an interpolator for each channel:

red   = griddedInterpolant({x,y,z},V(:,:,:,1));
green = griddedInterpolant({x,y,z},V(:,:,:,2));
blue  = griddedInterpolant({x,y,z},V(:,:,:,3));

and then replacing

slice(x,y,z,w,xd,yd,zd)

with

cdata = cat(3, red(xd,yd,zd), green(xd,yd,zd), blue(xd,yd,zd));
surface(xd,yd,zd,cdata);

I tried this on your example and found that the colors in w were all very close to black. So I loaded a different image to work on:

% An orange-and-black skull for Halloween
load mri
V = permute(double(D), [1 2 4 3]);
V = V / max(V(:));
V = bsxfun(@times, V, reshape([1 .3 0], [1 1 1 3]));

% Define grid coordinates and interpolator
[Nx, Ny, Nz, nCh] = size(V);
x = linspace(-5,5,Nx); 
y = linspace(-5,5,Ny); 
z = linspace(-5,5,Nz);
red = griddedInterpolant({x,y,z},V(:,:,:,1));
green = griddedInterpolant({x,y,z},V(:,:,:,2));
blue = griddedInterpolant({x,y,z},V(:,:,:,3));

for k = 0:.1:10
    hsp = surf(linspace(-5,5,Nx),linspace(-5,5,Ny),zeros(Ny,Nx));
    rotate(hsp,[1,0,0],18*k,[0 0 0])
    xd = hsp.XData;
    yd = hsp.YData;
    zd = hsp.ZData;
    delete(hsp)

    cdata = cat(3, red(xd,yd,zd), green(xd,yd,zd), blue(xd,yd,zd));
    surface(xd,yd,zd,cdata)

    shading flat
    hold off
    view(-25,20)
    axis([-5 5 -5 5 -5 5]);
    drawnow
end

Upvotes: 1

Related Questions