比如有圖像1,將其旋轉n度得到圖像2,問如何比較兩張圖像得到旋轉的度數n。
算法思路參考logpolar變換:
1.從圖像中心位置向四周引出射線。
2.計算每根射線所打到圖像上的像素累計和,得到極坐標灰度曲線。
3.比較兩張圖的灰度曲線,得到最相關的偏移位置,即為兩張圖像的旋轉角度。
原圖:
旋轉了10°的圖像:
灰度曲線:
代碼如下:
main.m
1 clear all; 2 close all; 3 clc; 4
5 img1 = imread('lena.jpg'); 6 img2 = imrotate(img1,15); 7
8 imshow(img1) 9 figure; 10 imshow(img2) 11
12 re1 = getCurve(img1); 13 re2 = getCurve(img2); 14
15 figure; 16 plot(re1); 17 hold on; 18 plot(re2); 19
20 su=zeros(length(re1),1); 21 for i=1:length(re1) 22 tmp = circshift(re2,i); 23 su(i) =sum(tmp.*re1); 24 end 25
26 [ma,ind] = max(su); 27 ind/10
getCurve.m
1 function re = getCurve(img) 2
3 [m,n]=size(img); 4
5 oy=m/2; 6 ox=n/2; 7
8 %求中心點到圖像四個角的距離 9 up_left=sqrt((oy-0)^2+(ox-0)^2); 10 up_right=sqrt((oy-0)^2+(ox-n)^2); 11 down_left=sqrt((oy-m)^2+(ox-0)^2); 12 down_right=sqrt((oy-m)^2+(ox-n)^2); 13
14 num=3600; 15 %求中心點距離四角距離的最大值,作為變換后圖像的高。 16 %這個最大值也是極坐標變換的極徑 17 radius=round(max([up_left up_right down_left down_right])); 18 re = zeros(num,1); 19
20 for i=0:1:radius %縱坐標代表極徑,不同情況不一樣 21 for j=1:num %橫坐標代表極角,為3600 22 %oy,ox作為極坐標變換中心坐標,需要作為偏移量相加 23 ind = j/10; 24 h=round(oy+i*sin(ind*pi/180)); 25 w=round(ox+i*cos(ind*pi/180)); 26
27 if h>0 && w> 0&& h<=m && w<=n %超出原圖像的像素忽略 28 re(j)= re(j) +double(img(h,w)); 29 end 30 end 31 end 32 re = re/sum(re); 33 end