メインコンテンツ

Create an App to Generate Fly‑Through Animations of 3‑D Medical Data

R2026b
Since R2026b

This example shows how to build an app to interactively generate animations of 3-D medical volume data using App Designer. Using the FlyThroughAnimationGeneratorApp app, users can generate animations for 3-D medical data using a sequence of smaller preset animations. The app defines the start position of each animation in a sequence by using the end position of the previous animation in the sequence. The app supports these types of preset animations commonly used with 3-D medical data.

  • Translation — The app steps the camera properties linearly between two specified points. Users must specify the start and end points of the animation.

  • Rotation — The app assumes the data to be at the center of a sphere with a radius equal to the distance between the center and the camera position. The app steps the camera properties between two points along this sphere to simulate a third-person rotation, or an orbital motion, of the camera. Users must specify the start point of the animation, the nature of the orbital animation as pitch, roll, or yaw, and the angle of rotation.

Open App Designer

App Designer is an interactive development environment for designing apps and custom UI components and programming their behavior.

To build the app from scratch, open App Designer using this command. Alternatively, you can open App Designer by selecting the Design App option on the Apps tab of the MATLAB® toolstrip.

appdesigner

The FlyThroughAnimationGeneratorApp app is also attached to this example as a supporting file. For information on running the app, see the Generate Animation of 3-D Medical Data Using App section.

You can also open this example from the App Designer home page by clicking Show examples in the Apps section of the home page and selecting Animate Volume Data from the list of examples.

You can customize the code of the app in the attached supporting files. For information on customizing the app, see the Customize the App section.

App Layout Design

The FlyThroughAnimationGeneratorApp app has two main regions: a toolstrip and a working area.

The toolstrip contains these sections:

  • Import 3D medical data — Consists of UI components used to import 3-D medical volume data from a file or as a medicalVolume object from the workspace.

  • Animation Settings — Consists of UI components used to design and preview animations.

  • Export — Consists of UI components used to export the animation as a GIF file.

The working area of the app contains these sections:

  • Viewer — Displays the 3-D medical volume data. The app displays the image using the volshow function. The handle of the displayed image is an Volume object. A Viewer object is the parent of the Volume object. For more information about the Volume object, see Volume Properties. For more information about the Viewer object, see Viewer Properties.

  • Camera Settings — Consists of UI components used to specify camera settings such as the start point, duration, and number of interpolation steps in the selected type of animation.

  • Animation Pane — Displays a tabular list in which each row represents a committed animation in the sequence. Each row has a Preview button to enable the user to preview the result up to the corresponding animation in the sequence. Each row also has a Delete button to enable the user to delete the corresponding animation and all following animations in the sequence. To generate a smooth transition, the app starts each new animation in the sequence where the previous animation ends.

App layout.

The app uses a grid layout structure to create the defined layout.

  • Main App figure

    • Main app grid layout

      • Toolstrip grid layout

        • Toolstrip elements like import, animation settings, export

      • Working area grid layout

        • Viewer panel containing Volume object

        • Camera settings grid layout containing the Camera Settings panel with parameter inputs and Preview, Commit, and Cancel buttons

        • Animation history grid layout containing tabular list of committed animations

For more information on using grid layout with App Designer, see Use Grid Layout Managers in App Designer.

Define App Properties

The app stores the input volume and current and intermediate results in these properties.

  • Viewer — Viewer object used to display the 3-D medical volume data. The app creates animations by updating the Camera Controls properties of this Viewer object.

  • VolshowHandle — Volume object created by volshow and used to display and animate the loaded 3-D medical volume data.

  • AnimationHistory — Structure array representing the animation stack. Each element in the array corresponds to a committed animation in the sequence. The structure has these fields related to camera properties. For more information on camera graphics terminology, see Camera Graphics Terminology.

    • Type — Animation sequence preset type, represented as "Translate" or "Rotate".

    • Position — Camera position, represented as a matrix of size N-by-3 where N is the number of interpolation steps.

    • Target — Camera target, represented as a matrix of size N-by-3 where N is the number of interpolation steps.

    • CameraUp — Camera up vector, represented as a matrix of size N-by-3 where N is the number of interpolation steps.

    • Zoom — Camera zoom, represented as a vector of size N-by-1 where N is the number of interpolation steps.

    • NumSteps — Number of interpolation steps, represented as a numeric scalar.

    • Duration — Duration of animation, represented as a numeric scalar, in seconds.

Define App Methods

The app uses methods to import and visualize data, process user input and update the display, export the final results, and control the app state. The app also uses some helper functions to improve code readability and code reusability. These are some of the important app methods.

Reset App on New Data Load

When the user loads a new medical volume into the app, the app clears the existing volume data, displays the loaded volume, and clears all animation history. The app resets UI elements to their default state and enables the drop-down to select the preset animation. The resetAppOnNewDataLoad method defines this behavior.

function resetAppOnNewDataLoad(app,volData)
        % Function to reset app when new data is loaded

        % Set the newly loaded medicalVolume data, and reset viewer3d.
        app.VolshowHandle.Data = volData.Voxels;
        app.VolshowHandle.Transformation = volData.VolumeGeometry.intrinsicToWorldMapping;
        % Set orientation axes labels to match the PCS.
        pcs = volData.VolumeGeometry.PatientCoordinateSystem;
        if ~isempty(pcs) && (strlength(pcs) == 4)
            labels = split(pcs,"");  % For "LPS+" returns ["" "L" "P" "S" "+" ""]
            app.Viewer.Axes.OrientationAxesLabels = labels(2:4)';
        end
        app.Viewer.Interactions = ["pan","zoom","rotate","axes"];
        % Reset camera position to default position, target, up vector,
        % and zoom level
        reset(app.Viewer);

        % Reset UI elements to default state
        app.QualityDropDownLabel.Enable = "on";
        app.QualityDropDown.Enable = "on";

        app.ToFileLabel.Enable = "off";
        app.ExportBrowseButton.Enable = "off";

        app.PresetDropDownLabel.Enable = "on";
        app.PresetDropDown.Enable = "on";

        app.RunButton.Enable = "off";

        % Clear any previous rows of committed animation presets
        delete(app.AnimationGridLayout.Children(2:end));
        app.AnimationHistory = struct("Type",{},"Position",{},"Target",{}, ...
               "CameraUp",{},"Zoom",{},"NumSteps",{},"Duration",{});
    end

Add New Preset Animation

The app has two distinct modes.

  • Preview Mode — The app goes into preview mode when the user selects a preset animation. In this mode, the user can adjust the camera settings. The app configures the preset animation, but does not add it to the committed history until the user selects Commit. To enable users to safely experiment with parameters without accidentally committing experimental results, the app locks most other controls in preview mode by toggling the enable and visible states across other UI sections.

  • Default Mode — The app goes into default mode when no preset animation. The app saves the last committed result, and the user can import new data, pick a new animation, view or delete history, or export results.

When the user selects an operation in the Preset drop-down, the PresetDropDownValueChanged callback switches the app into preview mode and creates the appropriate parameter UI in the Camera Settings section.

For the Translate preset, the app requires these inputs for both the start and end points, and thus displays them in the UI. Both the start and end points also have a Use Current button to update all parameters with the current values of the camera properties in the Viewer object.

  • Camera position, specified as a 1-by-3 vector, where the three elements of the vector represent the X, Y, and Z coordinates, respectively.

  • Camera target, specified as a 1-by-3 vector, where the three elements of the vector represent the X, Y, and Z coordinates, respectively.

  • Camera up vector, specified as a 1-by-3 vector, where the three elements of the vector represent the X, Y, and Z coordinates, respectively.

  • Camera zoom level, specified as a numeric scalar.

For the Rotate preset, the app requires the camera position, camera target, camera up vector, and camera zoom level inputs, and has a Use Current button, for only its start point. Additionally, the Rotate preset requires these inputs for both the start and end points.

  • Rotation type, specified as "Pitch", "Roll", or "Yaw".

  • Angle of rotation, in degrees, specified as a numeric scalar.

If manually specifying the properties is difficult, users can interact with the Volume object in the Viewer section and select Use Current to use the updated value of the associated Viewer object for the camera properties. Users can specify the start camera properties for only the first animation in a sequence. For each subsequent animation in the sequence, the app computes the start point as the end point of the previous animation.

Both presets also require these inputs in the parameter UI.

  • Number of interpolation steps, specified as a numeric scalar.

  • Duration of animation, specified as a numeric scalar, in seconds.

% Value changed function: PresetDropDown
function PresetDropDownValueChanged(app,event)
    % Callback function to process user selecting an animation
    % preset
    value = app.PresetDropDown.Value;
    if ismember(value,"Select")
        return;
    end
    % Switch to preview mode by locking toolstrip and enabling
    % preset selection
    app.switchToPreviewMode(true);
    % Create selected animation input
    switch value
        case "Translate"
            app.createTranslateCameraSettings();
            app.setInitialCamValues();
        case "Rotate"
            app.createRotateCameraSettings();
            app.setInitialCamValuesStart();
    end
end

Preview Preset Animation

Once the user specifies camera inputs and selects Preview, the app computes per‑step camera properties based on the number of interpolation steps and updates the viewer frame‑by‑frame. Based on the total duration of the animation and the number of interpolation steps, the app computes the delay between each frame to display a smooth animation. The app then assigns the camera properties to the Viewer object for each frame to preview the preset animation. The PreviewButtonPushed method calls the setCameraProperties function to assign the camera properties to the Viewer object.

function PreviewButtonPushed(app,event)
    % Callback function to play the current animation as a preview
    value = app.PresetDropDown.Value;
    switch value
        case "Translate"
            [pos,tar,camUp,zoom] = app.getCameraSettingSteps();
        case "Rotate"
            [pos,tar,camUp,zoom] = app.getCameraSettingRotateSteps();
    end
    numSteps = app.NumStepsEditField.Value;
    delay = app.DurationSpinner.Value/numSteps; % 1/fps
    for idx = 1:numSteps
        app.setCameraProperties(pos(idx,:),tar(idx,:),camUp(idx,:),zoom(idx));
        pause(delay);
    end
end

function setCameraProperties(app,pos,target,camUp,zoom)
    % Function to set the camera properties of the Viewer object
    if isvalid(app)
        app.Viewer.CameraPosition = pos;
        app.Viewer.CameraTarget = target;
        app.Viewer.CameraUpVector = camUp;
        app.Viewer.CameraZoom = zoom;
    end
end

For the Translate preset, the PreviewButtonPushed method calls the getCameraSettings function to interpolate the camera properties linearly between the start and end points.

function [pos,tar,camUp,zoom] = getCameraSettingSteps(app)
    % Function to get 'Num Steps' samples for camera
    % translation of position, camera target, camera up vector, and
    % camera zoom  level from start to end values. 
    % Position, target, and camera up vector are
    % returned as a 'numSteps'-by-3 matrix, where each row is a
    % corresponding sample in XYZ-coordinate space. Zoom is
    % returned as a 'numSteps'-by-1 vector, where each row is a
    % corresponding zoom level sample.
    startPositionX = app.StartPositionXEditField.Value;
    startPositionY = app.StartPositionYEditField.Value;
    startPositionZ = app.StartPositionZEditField.Value;

    startTargetX = app.StartTargetXEditField.Value;
    startTargetY = app.StartTargetYEditField.Value;
    startTargetZ = app.StartTargetZEditField.Value;

    startCameraUpX = app.StartCameraUpXEditField.Value;
    startCameraUpY = app.StartCameraUpYEditField.Value;
    startCameraUpZ = app.StartCameraUpZEditField.Value;

    startZoom = app.StartZoomSpinner.Value;

    endPositionX = app.EndPositionXEditField.Value;
    endPositionY = app.EndPositionYEditField.Value;
    endPositionZ = app.EndPositionZEditField.Value;

    endTargetX = app.EndTargetXEditField.Value;
    endTargetY = app.EndTargetYEditField.Value;
    endTargetZ = app.EndTargetZEditField.Value;

    endCameraUpX = app.EndCameraUpXEditField.Value;
    endCameraUpY = app.EndCameraUpYEditField.Value;
    endCameraUpZ = app.EndCameraUpZEditField.Value;

    endZoom = app.EndZoomSpinner.Value;

    numSteps = app.NumStepsEditField.Value;
    pos = [linspace(startPositionX,endPositionX,numSteps).' linspace(startPositionY,endPositionY,numSteps).' linspace(startPositionZ,endPositionZ,numSteps).'];
    tar = [linspace(startTargetX,endTargetX,numSteps).' linspace(startTargetY,endTargetY,numSteps).' linspace(startTargetZ,endTargetZ,numSteps).'];
    camUp = [linspace(startCameraUpX,endCameraUpX,numSteps).' linspace(startCameraUpY,endCameraUpY,numSteps).' linspace(startCameraUpZ,endCameraUpZ,numSteps).'];
    zoom = linspace(startZoom,endZoom,numSteps);
end

For the Rotate preset, the PreviewButtonPushed method calls the getCameraSettingRotateSteps function to interpolate the camera properties using the Rodrigues rotation formula.

function [pos,tar,camUp,zoom] = getCameraSettingRotateSteps(app)
    % Function to get 'Num Steps' samples for camera
    % rotation of position, camera target, camera up vector and
    % camera zoom  level for start values. Position, target, and camera up vector are
    % returned as a 'numSteps'-by-3 matrix, where each row is a
    % corresponding sample in XYZ-coordinate space. Zoom is
    % returned as a 'numSteps'-by-1 vector, where each row is a
    % corresponding zoom level sample.
    % Camera position and up vector are updated to follow a path on
    % a sphere centered at the specified camera target, to provide an orbital or
    % third-person view.
    % Samples are computed using the Rodrigues rotation formula.

    startPositionX = app.StartPositionXEditField.Value;
    startPositionY = app.StartPositionYEditField.Value;
    startPositionZ = app.StartPositionZEditField.Value;

    startTargetX = app.StartTargetXEditField.Value;
    startTargetY = app.StartTargetYEditField.Value;
    startTargetZ = app.StartTargetZEditField.Value;

    startCameraUpX = app.StartCameraUpXEditField.Value;
    startCameraUpY = app.StartCameraUpYEditField.Value;
    startCameraUpZ = app.StartCameraUpZEditField.Value;

    startZoom = app.StartZoomSpinner.Value;

    numSteps = app.NumStepsEditField.Value;

    camPos = [startPositionX startPositionY startPositionZ];
    camTarget = [startTargetX startTargetY startTargetZ];
    camUpVec = [startCameraUpX startCameraUpY startCameraUpZ];
    angleToRotatePerStep = deg2rad(app.RotationAngleEditField.Value)/numSteps;

    pos = zeros(numSteps,3);
    tar = repmat(camTarget,numSteps,1);
    camUp = zeros(numSteps,3);
    zoom = repmat(startZoom,numSteps,1);

    pos(1,1:3) = camPos;
    camUp(1,1:3) = camUpVec;

    selectedRotation = app.RotationTypeDropDown.Value;
    for idx = 2:numSteps
        switch selectedRotation
            case "Roll"
                % Rotate around viewing direction axis
                viewDir = camTarget - camPos;
                viewDir = viewDir/norm(viewDir);
                camUpVec = camUpVec*cos(angleToRotatePerStep) + cross(viewDir,camUpVec)*sin(angleToRotatePerStep) + viewDir*dot(viewDir,camUpVec)*(1-cos(angleToRotatePerStep));
            case "Pitch"
                camVec = camPos - camTarget;
                % Right vector (side-to-side axis)
                right = cross(camUpVec,camVec);
                right = right/norm(right);
                % Rotate camVec around right axis
                v_rot = camVec*cos(angleToRotatePerStep) + cross(right,camVec)*sin(angleToRotatePerStep) + right*dot(right,camVec)*(1-cos(angleToRotatePerStep));
                camPos = camTarget + v_rot;
                % Rotate up vector as well
                camUpVec = camUpVec*cos(angleToRotatePerStep) + cross(right,camUpVec)*sin(angleToRotatePerStep) + right*dot(right,camUpVec)*(1-cos(angleToRotatePerStep));
            case "Yaw"
                camVec = camPos - camTarget;
                % Up axis (vertical axis)
                camUpVec = camUpVec/norm(camUpVec);
                v_rot = camVec*cos(angleToRotatePerStep) + cross(camUpVec,camVec)*sin(angleToRotatePerStep) + camUpVec*dot(camUpVec,camVec)*(1-cos(angleToRotatePerStep));
                camPos = camTarget + v_rot;
        end
        pos(idx,1:3) = camPos;
        camUp(idx,1:3) = camUpVec;
    end
end

Commit or Cancel Preset Animation

When the user commits a preset animation by selecting Commit, the CommitButtonPushed method switches the app back to default mode and calls the appendToHistory function to append the most recent preset animation to the AnimationHistory array. The app creates Preview and Delete buttons for the committed animation in the Animation Pane list, and adds key information about the last commit to the list.

% Button pushed function: CommitButton
function CommitButtonPushed(app,event)
    % Callback function to commit the current animation
    value = app.PresetDropDown.Value;
    switch value
        case "Translate"
            [pos,tar,camUp,zoom] = app.getCameraSettingSteps();
        case "Rotate"
            [pos,tar,camUp,zoom] = app.getCameraSettingRotateSteps();
    end
    presetToCommit.Type = app.PresetDropDown.Value;
    presetToCommit.Position = pos;
    presetToCommit.Target = tar;
    presetToCommit.CameraUp = camUp;
    presetToCommit.Zoom = zoom;
    presetToCommit.NumSteps = app.NumStepsEditField.Value;
    presetToCommit.Duration = app.DurationSpinner.Value;
    app.AnimationHistory(end+1) = presetToCommit;

    % Reset back from preview mode for next preset input
    app.switchToPreviewMode(false);
    app.PresetDropDown.Value = "Select";
    % Enable run full animation button as now at least one animation
    % exists
    app.RunButton.Enable = "on";

    % Add current animation to history
    info = "for " + presetToCommit.Duration + " seconds in " + presetToCommit.NumSteps + " steps. ";
    app.appendToHistory(value,info);
end

function appendToHistory(app,presetName,info)
    % Function to add a row of the performed animation to AnimationGridLayout

    % Compute the index of the new row. New row index = number of
    % existing rows, including 1 for title row, +1
    newRowIndx = length(app.AnimationGridLayout.Children)+1;

    % If elements were deleted previously and a row exists in
    % AnimationGridLayout, use it, else add a new row
    if newRowIndx>length(app.AnimationGridLayout.Children)
        app.AnimationGridLayout.RowHeight(newRowIndx) = {20};
    end

    % Create AnimationRowGridLayout
    animationRow = uigridlayout(app.AnimationGridLayout);
    animationRow.ColumnWidth = {60,60,120,"1x"}; % pixel units, the space allocated for each UI element to match the title spacing
    animationRow.RowHeight = {20};
    animationRow.Layout.Row = newRowIndx;
    animationRow.Layout.Column = 1;
    animationRow.Padding = 0;

    % Create Preview button
    previewBtn = uibutton(animationRow,Text="Preview");
    previewBtn.Layout.Row = 1;
    previewBtn.Layout.Column = 1;
    previewBtn.ButtonPushedFcn = @(~,~)app.previewHistoryButtonPushed(newRowIndx);

    % Create Delete button
    deleteBtn = uibutton(animationRow,Text="Delete");
    deleteBtn.Layout.Row = 1;
    deleteBtn.Layout.Column = 2;
    deleteBtn.ButtonPushedFcn = @(~,~)app.deleteButtonPushed(newRowIndx);

    % Create animation preset label
    presetLabel = uilabel(animationRow);
    presetLabel.Text = presetName;
    presetLabel.Layout.Row = 1;
    presetLabel.Layout.Column = 3;

    % Create Information label
    infoLabel = uilabel(animationRow);
    infoLabel.Text = info;
    infoLabel.Layout.Row = 1;
    infoLabel.Layout.Column = 4;
end

If the user selects Cancel, the app returns to default mode and resets the Preset drop-down. This explicit split between the commit and cancel operations makes it safe to experiment with different presets and camera settings without accidentally committing experimental results to the stack.

Preview or Delete Committed Animations

The app records each committed animation as a new row in the Animation Pane list. Each row contains a Preview button to preview the corresponding preset animation in the stack, a Delete button that deletes the selected row and all animations that follow it, and labels that record the animation name and information such as the duration and number of interpolation steps. When the user deletes animations back to the first committed row, the app locks the Run button and export controls because there is no committed result to run or export. The previewHistoryButtonPushed and deleteButtonPushed methods define these behaviors.

function previewHistoryButtonPushed(app,index)
    % Callback function for when user presses the preview button on any
    % of the previously performed animations to preview the
    % animation. 'index' input is passed as the row index in the
    % history table, including 1 for the header.
    animation = app.AnimationHistory(index-1);

    numSteps = animation.NumSteps;
    delay = animation.Duration/numSteps; % 1/fps
    pos = animation.Position;
    tar = animation.Target;
    camUp = animation.CameraUp;
    zoom = animation.Zoom;
    for idx = 1:numSteps
        app.setCameraProperties(pos(idx,:),tar(idx,:),camUp(idx,:),zoom(idx));
        pause(delay);
    end
end

function deleteButtonPushed(app,index)
    % Callback function to delete the current and following animations.
    % 'index' input is passed as the row index in the history
    % table, including 1 for the title.
    delete(app.AnimationGridLayout.Children(index:end));
    app.AnimationHistory(index-1:end) = [];
    if index == 2
        % Only table header is remains, so lock exporting and
        % running of full animation
        app.ExportBrowseButton.Enable = "off";
        app.ToFileLabel.Enable = "off";
        app.RunButton.Enable = "off";
    end
end

Run Animation Sequence

Users can run the full animation sequence by selecting the Run option in the Animation Settings section of the app toolstrip. The app plays all committed animations sequentially. For each preset animation, the app iterates through the stored per‑frame properties and updates the viewer camera properties. To avoid showing the same frame twice at the boundary between two segments, the app skips the first frame of each segment after the first because it is identical to the last frame of the previous segment. The RunButtonPushed method defines this behavior.

% Button pushed function: RunButton
function RunButtonPushed(app,event)
    % Callback function to play the entire animation history
    for idx = 1:length(app.AnimationHistory)
        % Set the camera properties to values for animation
        % history
        animation = app.AnimationHistory(idx);

        numSteps = animation.NumSteps;
        delay = animation.Duration/numSteps; % 1/fps
        pos = animation.Position;
        tar = animation.Target;
        camUp = animation.CameraUp;
        zoom = animation.Zoom;
        for j = 1:numSteps
            if idx ~= 1 && j == 1
                % Skip first frame of current animation as it is 
                % identical to the last frame of the previous animation
                continue;
            end
            app.setCameraProperties(pos(j,:),tar(j,:),camUp(j,:),zoom(j));
            pause(delay);
        end
    end
end

Export Animation Sequence

When the user clicks Browse in the Export section of the app toolstrip, the app exports the entire AnimationHistory sequence to a GIF file. The app opens a dialog box for the user to specify a name and location for the GIF file. The app also creates a progress dialog because the getframe function used to capture frames can require significant time. The app replays the entire animation sequence similarly to the RunButtonPushed method, but instead of pausing after each frame to match the timing of the display to the intended animation speed, the app calls the drawnow function, captures the current frame using getframe function, converts the frame to indexed color image using the rgb2ind function, and appends the frame to the GIF file using the imwrite function. If the user cancels the export, the app deletes any partially written file and stops the export. If the export completes, the app shows a success alert. The ExportBrowseButtonPushed method defines this behavior.

% Button pushed function: ExportBrowseButton
function ExportBrowseButtonPushed(app,event)
    % Callback function to write the entire animation history to disk
    loopCount = 1;
    fps = 30;
    % Get user input for write location
    [file,location] = uiputfile("*.gif","Save Animation","FlyThroughAnimation.gif");
    if file ~= 0
        d = uiprogressdlg(app.UIFigure,Title="Generating animation",Cancelable="on");

        % Total number of frames in entire animation
        numFrames = sum([app.AnimationHistory.NumSteps]);

        % Current frame write count
        frameCount = 1;
        try
            for idx = 1:length(app.AnimationHistory)
                % Set the camera properties to values for animation
                % history
                animation = app.AnimationHistory(idx);

                numSteps = animation.NumSteps;
                pos = animation.Position;
                tar = animation.Target;
                camUp = animation.CameraUp;
                zoom = animation.Zoom;

                for j = 1:numSteps
                    if idx ~= 1 && j == 1
                        % Skip first frame of current animation as it is 
                        % identical to the last frame of the previous animation
                        continue;
                    end
                    app.setCameraProperties(pos(j,:),tar(j,:),camUp(j,:),zoom(j));
                    drawnow;
                    if d.CancelRequested
                        if frameCount~=1
                            % If user cancels the export, and file
                            % is already written, delete the file
                            % before stopping export
                            delete(fullfile(location,file));
                        end
                        return;
                    end
                    % Update frame write progress
                    d.Value = frameCount/numFrames;
                    d.Message = sprintf("Progress: %.2f%%",100*frameCount/numFrames);

                    % Get the current viewer image as a screenshot.
                    img = getframe(app.Viewer);
                    [A,map] = rgb2ind(img.cdata,256);
                    % Write the screenshot to GIF file
                    if frameCount == 1
                        imwrite(A,map,fullfile(location,file),"gif", ...
                            LoopCount=loopCount,DelayTime=1/fps);
                    else
                        imwrite(A,map,fullfile(location,file),"gif",...
                            WriteMode="append",DelayTime=1/fps);
                    end
                    frameCount = frameCount + 1;
                end
            end
            close(d);
            uialert(app.UIFigure,"Animation saved successfully", ...
                "Export Success",Icon="success");
        catch ME
            close(d);
            uialert(app.UIFigure,ME.message,"Export Failed");
        end
    end
end

Generate Animation of 3-D Medical Data Using App

Run the FlyThroughAnimationGeneratorApp app.

Import a 3-D medical volume from a file or as a medicalVolume object from the workspace using the Import 3D medical data section of the app toolstrip. If you choose to import the volume from a file, the app opens a dialog box enabling you to browse files that have valid file formats. If you import the volume from the workspace, the app filters workspace variables for medicalVolume objects and displays the variable names in the drop-down. When you import the volume, the app resets and displays the imported volume in the Viewer section of the app.

Import 3-D medical volume into the app.

To add a translation animation, perform these steps.

  1. Select Translate from the Preset drop-down in the Animation Settings section of the app toolstrip.

  2. Specify the start and end camera properties in the Camera Settings section. You can manually specify the camera properties, or select the Use Current option to automatically populate the camera settings with the properties of the Viewer object reflected in the Viewer section. You can specify the start camera properties only if this is the first animation in the sequence.

  3. You can experiment with different camera settings and preview the resulting animation, without committing it, using the Preview option.

  4. Select Commit to add the animation to the stack and record it in the history, or select Cancel to discard it.

Translate preset in the app.

To add a rotation animation, perform these steps.

  1. Select Rotate from the Preset drop-down in the Animation Settings section of the app toolstrip.

  2. Specify the start camera properties in the Camera Settings section. You can manually specify the camera properties, or select the Use Current option to automatically populate the camera settings with the properties of the Viewer object reflected in the Viewer section. You can specify the start camera properties only if this is the first animation in the sequence.

  3. Select the type of rotation as Pitch, Roll, or Yaw and specify the angle of rotation in degrees.

  4. You can experiment with different camera settings and preview the resulting animation, without committing it, using the Preview option.

  5. Select Commit to add the animation to the stack and record it in the history, or select Cancel to discard it.

Rotate preset in the app.

Use the Animation Pane list to preview earlier results in the stack, or to delete animations back to a previous state. Once you finalize the animation sequence, select Run in the Animation Settings section of the app toolstrip to play the complete animation sequence. You can export the animation as a GIF file using the Export section of the app toolstrip.

Animation generated using the app.

Customize the App

You can customize the code of the FlyThroughAnimationGeneratorApp app in the attached supporting file. You can include support for more preset animations by adding them to the list of presets, adding the UI elements required for their parameters, and adding steps to perform the animation. You can also add support for complex camera trajectories and perspectives. Additionally, you can support export to different file types, such as MP4.

To customize the app, you can choose one of these options:

  • Open the attached MLAPP files in App Designer and edit the code in the Code View.

  • Open the attached MLAPP files in App Designer, select Share in the Designer tab and then Export to MATLAB Class (.m), and save the M file. You can then edit the M file.

See Also

Apps

Properties

Functions

Topics