自动检测图像旋转和缩放
本示例演示了如何自动确定两个图像之间的几何变换。具体来说,当一个图像因旋转和缩放而相对于另一个图像发生畸变时,可以利用函数 detectSIFTFeatures 和 estgeotform2d 来确定旋转角度和缩放因子。随后,可以利用这些参数将畸变的图像还原为原始外观。
读取图像
将一个图像加载到工作区中。
original = imread("cameraman.tif");
imshow(original);

调整图像大小并旋转图像
改变缩放因子。
scale = 0.7; J = imresize(original,scale);
调整旋转角度,theta。当 theta 的值是正数时,函数 imrotate 会将图像逆时针旋转。若要将图像顺时针旋转,请为 theta 设置负值。
theta = 30; distorted = imrotate(J,-theta); figure imshow(distorted)

尝试调整输入图像的不同缩放比例和旋转角度,可以改善处理效果。然而,尺度上的变化过于剧烈可能会影响特征检测器识别足够特征的能力,从而影响分析的准确性。
查找图像之间的特征匹配
检测两个图像中的特征。
ptsOriginal = detectSURFFeatures(original); ptsDistorted = detectSURFFeatures(distorted);
从原始特征和畸变特征中提取特征描述符。
[featuresOriginal,validPtsOriginal] = extractFeatures(original,ptsOriginal); [featuresDistorted,validPtsDistorted] = extractFeatures(distorted,ptsDistorted);
使用特征描述符来匹配特征。
indexPairs = matchFeatures(featuresOriginal,featuresDistorted,MatchThreshold=40,MaxRatio=0.7,Unique=true);
获取每个图像中对应点的坐标。
matchedOriginal = validPtsOriginal(indexPairs(:,1)); matchedDistorted = validPtsDistorted(indexPairs(:,2));
显示推测的点匹配。
figure
showMatchedFeatures(original,distorted,matchedOriginal,matchedDistorted);
title("Putatively matched points (including outliers)");

估计变换
基于点对匹配,利用 M-估计量样本共识 (MSAC) 算法(RANSAC 的一个稳健变体)确定一个变换。该算法会剔除异常值,以准确计算变换矩阵。由于依赖随机采样,MSAC 算法在变换计算中可能会产生不同的结果。
[tform,inlierIdx] = estgeotform2d(matchedDistorted,matchedOriginal,"similarity");
inlierDistorted = matchedDistorted(inlierIdx,:);
inlierOriginal = matchedOriginal(inlierIdx,:);
显示用于计算变换的匹配点对。
figure; showMatchedFeatures(original,distorted,inlierOriginal,inlierDistorted); title("Matching points (inliers only)"); legend("ptsOriginal","ptsDistorted");

求比例和角度
使用几何变换器 tform 来恢复缩放比例和角度。由于变换是从畸变图像计算到原始图像的,因此必须计算其逆变换以恢复畸变。
Let sc = s*cos(theta) Let ss = s*sin(theta)
Then, Ainv = [sc ss tx;
-ss sc ty;
0 0 1]where tx and ty are x and y translations, respectively.
计算逆变换矩阵。
invTform = invert(tform); Ainv = invTform.A; ss = Ainv(1,2); sc = Ainv(1,1); scaleRecovered = hypot(ss,sc); disp(["Recovered scale: ",num2str(scaleRecovered)]) % Recover the rotation in which a positive value represents a rotation in % the clockwise direction. thetaRecovered = atan2d(-ss,sc); disp(["Recovered theta: ",num2str(thetaRecovered)])
"Recovered scale: " "0.69893"
"Recovered theta: " "29.1554"
恢复后的值应与图像调整大小和旋转过程中所选的缩放比例和角度值相符。此外,缩放比例和旋转角度可在 simtform2d 对象的“缩放比例”和“旋转角度”属性中找到。
disp(["Scale: " num2str(invTform.Scale)]) disp(["RotationAngle: " num2str(invTform.RotationAngle)])
"Scale: " "0.69893"
"RotationAngle: " "29.1554"
恢复原始图像
通过对畸变的图像进行变换,恢复原始图像。
outputView = imref2d(size(original)); recovered = imwarp(distorted,tform,OutputView=outputView);
通过在蒙太奇中将 recovered 与 original 并排展示,对它们进行比较。
figure,imshowpair(original,recovered,"montage")

由于畸变和恢复处理的原因,recovered(右侧)的图像质量与 original(左侧)的图像不一致。特别是,图像缩小会导致信息丢失。边缘处的伪影是由于变换精度有限所致。在图像间寻找匹配特征的过程中,检测到更多的点将提高变换的准确性。