旋轉一般是指將圖像圍繞某一指定點旋轉一定的角度。 旋轉通常也會改變圖像的大小,和圖像平移的處理一樣,可以把轉出顯示區域的圖像截去,也可以改變輸出圖像的大小以擴展顯示范圍。
本篇博客實現的旋轉算法改編自上一篇博客的鏡像,因此不說那么多理論,直接記錄重點。
一、MATLAB實現
1、函數法
%-------------------------------------------------------------------------- % 函數法旋轉 %-------------------------------------------------------------------------- clc; clear all; RGB = imread('monkey.jpg'); %讀取圖像 L_rotate = imrotate(RGB,90,'crop'); R_rotate = imrotate(RGB,-90,'crop'); rotate = imrotate(RGB,180,'crop'); subplot(2,2,1),imshow(RGB); title('原圖'); subplot(2,2,2),imshow(L_rotate); title('水平鏡像'); subplot(2,2,3),imshow(R_rotate); title('垂直鏡像'); subplot(2,2,4),imshow(rotate);title('水平垂直鏡像');
運行結果:
2、公式法
%-------------------------------------------------------------------------- % 公式法旋轉 %-------------------------------------------------------------------------- clc; clear all; RGB = imread('monkey.jpg'); %讀取圖像 [ROW,COL,N] = size(RGB); L_rotate = uint8(zeros(ROW, COL,N)); %Left rotate R_rotate = uint8(zeros(ROW, COL,N)); %Right rotate rotate = uint8(zeros(ROW, COL,N)); %180° rotate %左轉90度 for i =1:ROW for j=1:COL for k=1:N x = COL-j+1; y = i; z = k; L_rotate(x,y,z) =RGB(i,j,k); end end end %右轉90度 for i =1:ROW for j=1:COL for k=1:N x = j; y = ROW-i+1; z = k; R_rotate(x,y,z) =RGB(i,j,k); end end end %旋轉180度 for i =1:ROW for j=1:COL for k=1:N x = ROW-i+1; y = COL-j+1; z = k; rotate(x,y,z) =RGB(i,j,k); end end end subplot(2,2,1),imshow(RGB); title('原圖'); subplot(2,2,2),imshow(L_rotate); title('左轉90度'); subplot(2,2,3),imshow(R_rotate); title('右轉90度'); subplot(2,2,4),imshow(rotate); title('旋轉180度');
運行結果:
兩種方法得到的結果一致,表明公式正確。
二、FPGA實現
本次實驗基於鏡像改編而來,其他模塊一致,僅旋轉算法部分不同。
always @(*) begin case(mode) 2'b00 : begin //原圖 rotate_x = cnt_col; rotate_y = cnt_row; end 2'b01 : begin //右轉90度 rotate_x = cnt_row; rotate_y = (COL-1) - cnt_col; end 2'b10 : begin //旋轉180度 rotate_x = (COL-1) - cnt_col; rotate_y = (ROW-1) - cnt_row; end 2'b11 : begin //左轉90度(右轉270度) rotate_x = (ROW-1) - cnt_row; rotate_y = cnt_col; end default : begin rotate_x = cnt_col; rotate_y = cnt_row; end endcase end
三、上板驗證
總共4種模式,模式0、1、2、3 分別得到如下結果:
把這4副圖也按MATLAB的樣子拼到一塊看看吧:
和上面的 MATLAB 實驗結果對比,可以看到此次圖像旋轉實驗成功。
視頻演示如下所示:
后記
本博客整理的旋轉算法僅支持90度周期的旋轉,任意角度的旋轉算法還待進一步研究。此外本次所選圖片為正方形,如果是長方形圖片,則必須在設計旋轉算法的模塊好好思考如何設計坐標和數值的對應關系。
參考資料:[1] OpenS Lee:FPGA開源工作室(公眾號)