Main Content

Rotate Image Interactively Using Rectangle ROI

This example shows how to rotate an image by using a Rectangle ROI with a callback function that callsimrotatewhen you move the ROI.

Image rotation is a common preprocessing step. In this example, an image needs to be rotated by an unknown amount to align the horizon with the x-axis. You can use theimrotatefunction to rotate the image, but you need prior knowledge of the rotation angle. By using an interactive rotatable ROI, you can rotate the image in real time to match the rotation of the ROI.

Create the Rotatable Rectangle ROI

Display an image in an Axes.

im = imread('baby.jpg'); hIm = imshow(im);

Get the size of the image.

sz = size(im);

Determine the position and size of the Rectangle ROI as a 4-element vector of the form [x y w h]. The ROI will be drawn at the center of the image and have half of the image width and height.

pos = [(sz(2)/4) + 0.5, (sz(1)/4) + 0.5, sz(2)/2, sz(1)/2];

Create a rotatable Rectangle ROI at the specified position and set the Rotatable property totrue. You can then rotate the rectangle by clicking and dragging near the corners. As the ROI moves, it broadcasts an event MovingROI. By adding a listener for that event and a callback function that executes when the event occurs, you can rotate the image in response to movements of the ROI.

h = drawrectangle('Rotatable',true,...'DrawingArea','unlimited',...'Position',pos,...'FaceAlpha',0);

Place a prompt in the label.

h.Label ='Rotate rectangle to rotate image';

添加一个侦听器,侦听th的任何运动e ROI.

addlistener(h,'MovingROI',@(src,evt) rotateImage(src,evt,hIm,im));

Callimrotatein Callback Function

Define a callback function that executes as the Rectangle ROI moves. This function retrieves the current rotation angle of the ROI, callsimrotateon the image with that rotation angle, and updates the display. The function also updates the label to display the current rotation angle.

functionrotateImage(src,evt,hIm,im)% Only rotate the image when the ROI is rotated. Determine if the% RotationAngle has changedifevt.PreviousRotationAngle ~= evt.CurrentRotationAngle% Update the label to display current rotationsrc.Label = [num2str(evt.CurrentRotationAngle,'%30.1f')' degrees'];% Rotate the image and update the displayim = imrotate(im,evt.CurrentRotationAngle,'nearest','crop'); hIm.CData = im;endend

See Also

|||

相关的话题