Create a figure with slider (before/after)

15 views (last 30 days)
Huy Nguyen Minh
Huy Nguyen Minh on 5 Oct 2024
Answered: Voss on 5 Oct 2024
I want to create a figure or an app that can show before and after image draw by plot(), the slider can be pull to show the before/after (the picture below for example). How can I do that in Matlab?

Answers (2)

Venkat Siddarth Reddy
Venkat Siddarth Reddy on 5 Oct 2024
Hi Huy Nguyen Minh,
You can achieve this functionality using the MATLAB feature called "uislider".
Firstly, create a horizontrol slider in an "uifigure" using the above feature and associate a callback to the slider such that the value selected in the slider determines the percentage of the image to be shown in the selected "uifigure".
Please refer to the following code snippet for the implementation of the above logic in MATLAB:
% Load the images
beforeImg = imread('peppers.png');
afterImg = imresize(imread('saturn.png'),[384,512]);% Ensure both images are of the same size
% Get the size of the images
[rows, cols, ~] = size(beforeImg);
%Create a uifigure and uiaxes to display the images and the slider
fig = uifigure('Name', 'Before v/s After');
ax = uiaxes('Parent', fig, 'Position', [100 100 600 400]);
% Display the "before" image first
imshow(beforeImg, 'Parent', ax);
% Create the slider and add the operation to be done when the value is
% changed
slider = uislider(fig, ...
'Position', [100 50 600 3], ...
'Limits', [1 cols], ...
'ValueChangedFcn', @(sld, event) updateImage(sld, ax, beforeImg, afterImg, rows));
% Callback function to update the image
function updateImage(slider, ax, beforeImg, afterImg, rows)
colPos = round(slider.Value);
% Create a composite image from the parts of "before" and "after" image
% needs to be displayed
compositeImg = beforeImg;
compositeImg(:, colPos:end, :) = afterImg(:, colPos:end, :);
% Display the composite image
imshow(compositeImg, 'Parent', ax);
end
To learn more about uislider, please refer to the following documentation:
I hope it helps!
Regards
Venkat Siddarth V

Voss
Voss on 5 Oct 2024

Products


Release

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!