1 ## Copyright (C) 2004-2005 Justus H. Piater
3 ## This program is free software; you can redistribute it and/or
4 ## modify it under the terms of the GNU General Public License
5 ## as published by the Free Software Foundation; either version 2
6 ## of the License, or (at your option) any later version.
8 ## This program is distributed in the hope that it will be useful, but
9 ## WITHOUT ANY WARRANTY; without even the implied warranty of
10 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 ## General Public License for more details.
13 ## You should have received a copy of the GNU General Public License
14 ## along with this program; If not, see <http://www.gnu.org/licenses/>.
17 ## @deftypefn {Function File} {} imrotate(@var{imgPre}, @var{theta}, @var{method}, @var{bbox}, @var{extrapval})
18 ## Rotation of a 2D matrix about its center.
22 ## @var{imgPre} a gray-level image matrix
24 ## @var{theta} the rotation angle in degrees counterclockwise
28 ## @item "nearest" neighbor: fast, but produces aliasing effects (default).
29 ## @item "bilinear" interpolation: does anti-aliasing, but is slightly slower.
30 ## @item "bicubic" interpolation: does anti-aliasing, preserves edges better than bilinear interpolation, but gray levels may slightly overshoot at sharp edges. This is probably the best method for most purposes, but also the slowest.
31 ## @item "Fourier" uses Fourier interpolation, decomposing the rotation matrix into 3 shears. This method often results in different artifacts than homography-based methods. Instead of slightly blurry edges, this method can result in ringing artifacts (little waves near high-contrast edges). However, Fourier interpolation is better at maintaining the image information, so that unrotating will result in an image closer to the original than the other methods.
36 ## @item "loose" grows the image to accommodate the rotated image (default).
37 ## @item "crop" rotates the image about its center, clipping any part of the image that is moved outside its boundaries.
40 ## @var{extrapval} sets the value used for extrapolation. The default value
41 ## is @code{NA} for images represented using doubles, and 0 otherwise.
42 ## This argument is ignored of Fourier interpolation is used.
46 ## @var{imgPost} the rotated image matrix
48 ## @var{H} the homography mapping original to rotated pixel
49 ## coordinates. To map a coordinate vector c = [x;y] to its
50 ## rotated location, compute round((@var{H} * [c; 1])(1:2)).
52 ## @var{valid} a binary matrix describing which pixels are valid,
53 ## and which pixels are extrapolated. This output is
54 ## not available if Fourier interpolation is used.
57 ## Author: Justus H. Piater <Justus.Piater@ULg.ac.be>
58 ## Created: 2004-10-18
61 function [imgPost, H, valid] = imrotate(imgPre, thetaDeg, interp="nearest", bbox="loose", extrapval=NA)
64 error("imrotate: not enough input arguments");
66 [imrows, imcols, imchannels, tmp] = size(imgPre);
67 if (tmp != 1 || (imchannels != 1 && imchannels != 3))
68 error("imrotate: first input argument must be an image");
70 if (!isscalar(thetaDeg))
71 error("imrotate: the angle must be given as a scalar");
73 if (!any(strcmpi(interp, {"nearest", "linear", "bilinear", "cubic", "bicubic", "Fourier"})))
74 error("imrotate: unsupported interpolation method");
76 if (any(strcmpi(interp, {"bilinear", "bicubic"})))
77 interp = interp(3:end); # Remove "bi"
79 if (!any(strcmpi(bbox, {"loose", "crop"})))
80 error("imrotate: bounding box must be either 'loose' or 'crop'");
82 if (!isscalar(extrapval))
83 error("imrotate: extrapolation value must be a scalar");
86 ## Input checking done. Start working
87 thetaDeg = mod(thetaDeg, 360); # some code below relies on positive angles
88 theta = thetaDeg * pi/180;
90 sizePre = size(imgPre);
92 ## We think in x,y coordinates here (rather than row,column), except
93 ## for size... variables that follow the usual size() convention. The
94 ## coordinate system is aligned with the pixel centers.
96 R = [cos(theta) sin(theta); -sin(theta) cos(theta)];
98 if (nargin >= 4 && strcmp(bbox, "crop"))
101 ## Compute new size by projecting zero-base image corner pixel
102 ## coordinates through the rotation:
104 (R * [sizePre(2) - 1; 0 ])';
105 (R * [sizePre(2) - 1; sizePre(1) - 1])';
106 (R * [0 ; sizePre(1) - 1])' ];
107 sizePost(2) = round(max(corners(:,1)) - min(corners(:,1))) + 1;
108 sizePost(1) = round(max(corners(:,2)) - min(corners(:,2))) + 1;
109 ## This size computation yields perfect results for 0-degree (mod
110 ## 90) rotations and, together with the computation of the center of
111 ## rotation below, yields an image whose corresponding region is
112 ## identical to "crop". However, we may lose a boundary of a
113 ## fractional pixel for general angles.
116 ## Compute the center of rotation and the translational part of the
118 oPre = ([ sizePre(2); sizePre(1)] + 1) / 2;
119 oPost = ([sizePost(2); sizePost(1)] + 1) / 2;
120 T = oPost - R * oPre; # translation part of the homography
122 ## And here is the homography mapping old to new coordinates:
123 H = [[R; 0 0] [T; 1]];
125 ## Treat trivial rotations specially (multiples of 90 degrees):
126 if (mod(thetaDeg, 90) == 0)
127 nRot90 = mod(thetaDeg, 360) / 90;
128 if (mod(thetaDeg, 180) == 0 || sizePre(1) == sizePre(2) ||
129 strcmpi(bbox, "loose"))
130 imgPost = rot90(imgPre, nRot90);
132 elseif (mod(sizePre(1), 2) == mod(sizePre(2), 2))
133 ## Here, bbox is "crop" and the rotation angle is +/- 90 degrees.
134 ## This works only if the image dimensions are of equal parity.
135 imgRot = rot90(imgPre, nRot90);
136 imgPost = zeros(sizePre);
137 hw = min(sizePre) / 2 - 0.5;
138 imgPost (round(oPost(2) - hw) : round(oPost(2) + hw),
139 round(oPost(1) - hw) : round(oPost(1) + hw) ) = ...
140 imgRot(round(oPost(1) - hw) : round(oPost(1) + hw),
141 round(oPost(2) - hw) : round(oPost(2) + hw) );
144 ## Here, bbox is "crop", the rotation angle is +/- 90 degrees, and
145 ## the image dimensions are of unequal parity. This case cannot
146 ## correctly be handled by rot90() because the image square to be
147 ## cropped does not align with the pixels - we must interpolate. A
148 ## caller who wants to avoid this should ensure that the image
149 ## dimensions are of equal parity.
153 ## Now the actual rotations happen
154 if (strcmpi(interp, "Fourier"))
156 imgPre = im2double (imgPre);
158 imgPost = imrotate_Fourier(imgPre, thetaDeg, interp, bbox);
161 imgPost(:,:,i) = imrotate_Fourier(imgPre(:,:,i), thetaDeg, interp, bbox);
168 imgPost = im2uint8 (imgPost);
170 imgPost = im2uint16 (imgPost);
172 imgPost = single (imgPost);
175 [imgPost, valid] = imperspectivewarp(imgPre, H, interp, bbox, extrapval);
180 %! ## Verify minimal loss across six rotations that add up to 360 +/- 1 deg.:
181 %! methods = { "nearest", "bilinear", "bicubic", "Fourier" };
182 %! angles = [ 59 60 61 ];
183 %! tolerances = [ 7.4 8.5 8.6 # nearest
184 %! 3.5 3.1 3.5 # bilinear
185 %! 2.7 2.0 2.7 # bicubic
186 %! 2.7 1.6 2.8 ]/8; # Fourier
188 %! # This is peaks(50) without the dependency on the plot package
189 %! x = y = linspace(-3,3,50);
190 %! [X,Y] = meshgrid(x,y);
191 %! x = 3*(1-X).^2.*exp(-X.^2 - (Y+1).^2) \
192 %! - 10*(X/5 - X.^3 - Y.^5).*exp(-X.^2-Y.^2) \
193 %! - 1/3*exp(-(X+1).^2 - Y.^2);
195 %! x -= min(x(:)); # Fourier does not handle neg. values well
197 %! for m = 1:(length(methods))
200 %! y = imrotate(y, 60, methods{m}, "crop", 0);
202 %! for a = 1:(length(angles))
203 %! assert(norm((x - imrotate(y, angles(a), methods{m}, "crop", 0))
204 %! (10:40, 10:40)) < tolerances(m,a));
210 %! ## Verify exactness of near-90 and 90-degree rotations:
212 %! for angle = [90 180 270]
213 %! for da = [-0.1 0.1]
214 %! Y = imrotate(X, angle + da , "nearest", :, 0);
215 %! Z = imrotate(Y, -(angle + da), "nearest", :, 0);
216 %! assert(norm(X - Z) == 0); # exact zero-sum rotation
217 %! assert(norm(Y - imrotate(X, angle, "nearest", :, 0)) == 0); # near zero-sum
223 %! ## Verify preserved pixel density:
224 %! methods = { "nearest", "bilinear", "bicubic", "Fourier" };
225 %! ## This test does not seem to do justice to the Fourier method...:
226 %! tolerances = [ 4 2.2 2.0 209 ];
228 %! for m = 1:(length(methods))
231 %! t(end + 1) = sum(imrotate(eye(n), 20, methods{m}, :, 0)(:));
233 %! assert(t, range, tolerances(m));