如何在MATLAB中测量图像的旋转?

时间:2011-09-19 21:41:56

标签: matlab image-processing

我有两张照片。一个是原件,另一个是旋转的。

Original Image

现在,我需要发现图像旋转的角度。到现在为止,我想到了发现每种颜色的质心(因为我将使用的每个图像都有颜色的正方形),并用它来发现图像旋转了多少,但我失败了。

我正在使用它来发现图像中较高方块的质心和颜色:

i = rgb2gray(img);
bw = im2bw(i,0.01);
s = regionprops(bw,'Centroid');
centroids = cat(1, s.Centroid);
colors = impixel(img,centroids(1),centroids(2));
top = max(centroids);
topcolor = impixel(img,top(1),top(2));

3 个答案:

答案 0 :(得分:3)

您可以在图像和旋转版本中检测其中一个彩色矩形的角,并使用这些作为控制点,使用CP2TFORM推断两个图像之间的转换(如图像注册)功能。然后我们可以从仿射变换矩阵计算旋转角度:

以下是一个示例代码:

%# read first image (indexed color image)
[I1 map1] = imread('http://i.stack.imgur.com/LwuW3.png');

%# constructed rotated image
deg = -15;
I2 = imrotate(I1, deg, 'bilinear', 'crop');

%# find blue rectangle
BW1 = (I1==2);
BW2 = imrotate(BW1, deg, 'bilinear', 'crop');

%# detect corners in both
p1 = corner(BW1, 'QualityLevel',0.5);
p2 = corner(BW2, 'QualityLevel',0.5);

%# sort corners coordinates in a consistent way (counter-clockwise)
p1 = sortrows(p1,[2 1]);
p2 = sortrows(p2,[2 1]);
idx = convhull(p1(:,1), p1(:,2)); p1 = p1(idx(1:end-1),:);
idx = convhull(p2(:,1), p2(:,2)); p2 = p2(idx(1:end-1),:);

%# make sure we have the same number of corner points
sz = min(size(p1,1),size(p2,1));
p1 = p1(1:sz,:); p2 = p2(1:sz,:);

%# infer transformation from corner points
t = cp2tform(p2,p1,'nonreflective similarity');    %# 'affine'

%# rotate image to match the other
II2 = imtransform(I2, t, 'XData',[1 size(I1,2)], 'YData',[1 size(I1,1)]);

%# recover affine transformation params (translation, rotation, scale)
ss = t.tdata.Tinv(2,1);
sc = t.tdata.Tinv(1,1);
tx = t.tdata.Tinv(3,1);
ty = t.tdata.Tinv(3,2);
translation = [tx ty];
scale = sqrt(ss*ss + sc*sc);
rotation = atan2(ss,sc)*180/pi;

%# plot the results
subplot(311), imshow(I1,map1), title('I1')
hold on, plot(p1(:,1),p1(:,2),'go')
subplot(312), imshow(I2,map1), title('I2')
hold on, plot(p2(:,1),p2(:,2),'go')
subplot(313), imshow(II2,map1)
title(sprintf('recovered angle = %g',rotation))

screenshot

答案 1 :(得分:1)

如果您可以识别仅对应于一个组件的颜色,则更容易:

  1. 计算每张图片的质心
  2. 计算每幅图像的质心平均值(x和y)。这是每张图片的“中心”
  3. 获取每个图像的红色分量颜色质心(在您的示例中)
  4. 从每个图像的红色成分颜色质心中减去每个图像的质心平均值
  5. 计算4)中计算的每个矢量的ArcTan2,并减去角度。那是你的结果。
  6. 如果每种颜色有多个图形,则需要计算旋转的所有可能组合,然后选择与其他可能旋转兼容的组合。

    如果您认为有用,我可以在Mathematica中发布代码。

答案 2 :(得分:1)

我会采用上述方法的变体:

% Crude binarization method to knock out background and retain foreground
% features. Note one looses the cube in the middle
im = im > 1

Enter image description here

然后我会得到2D自相关:

acf = normxcorr2(im, im);

Enter image description here

从该结果,可以容易地检测到峰值,并且当旋转进入自相关函数(ACF)域时,可以通过匹配来自旋转图像的原始ACF和ACF之间的峰值来确定旋转,例如使用所谓的Hungarian algorithm