using slider to rotate image in Matlab

Ofir A. picture Ofir A. · Jul 1, 2011 · Viewed 8.1k times · Source

I have a GUI (using GUIDE) in Matlab, this is how it looks:

enter image description here

I want to rotate the image using slider and to show the change in real time.

I use axes to display the image.

how can I do this?

EDIT: I'm building OCR application. this is how the plate looks when I'm rotate it, the numbers are totally deformed.

enter image description here

thanks.

Answer

Amro picture Amro · Jul 2, 2011

Here is an example GUI:

function rotationGUI()
    %# read image
    I = imread('cameraman.tif');

    %# setup GUI
    hFig = figure('menu','none');
    hAx = axes('Parent',hFig);
    uicontrol('Parent',hFig, 'Style','slider', 'Value',0, 'Min',0,...
        'Max',360, 'SliderStep',[1 10]./360, ...
        'Position',[150 5 300 20], 'Callback',@slider_callback) 
    hTxt = uicontrol('Style','text', 'Position',[290 28 20 15], 'String','0');

    %# show image
    imshow(I, 'Parent',hAx)

    %# Callback function
    function slider_callback(hObj, eventdata)
        angle = round(get(hObj,'Value'));        %# get rotation angle in degrees
        imshow(imrotate(I,angle), 'Parent',hAx)  %# rotate image
        set(hTxt, 'String',num2str(angle))       %# update text
    end
end

enter image description here


If you prefer to build the GUI in GUIDE, follow these steps:

  • create GUI, and add necessary components: axis, slider, static text (drag-and-drop)

  • Using the "Property Inspector", change slider properties as required:: Min/Max/Value/SliderStep. Also would help if you assign a Tag to be able to find components in the code.

  • In the figure's xxxx_OpeningFcn function, read and store the image in the handles structure, then show it:

    handles.I = imread('cameraman.tif');
    imshow(I, 'Parent',findobj(hObject,'Tag','imgAxis'))  %# use tag you assigned
    guidata(hObject, handles);         %# Update handles structure
  • Create a callback event handler for your slider, and add the code:
    angle = round( get(hObject,'Value') );
    imshow( imrotate(handles.I,angle) )

EDIT: Image rotation is an affine transformation which maps the position (x,y) of input image pixels onto new coordinates (x2,y2) for the output image. The problem is that the output coordinates may not always be integers. Since digital images are represented on a grid of discrete pixels, thus some form of resampling/interpolation is employed (which is why straight lines might look jagged when rotated at certain angles).

enter image description here

(Illustration borrowed from: Understanding Digital Image Interpolation)