爲了實現硬件加速而把C code轉化爲Verilog。
參考的是: http://beiciliang.weebly.com/uploads/2/4/3/1/24316476/verilog.pdf
因爲FPGA上的VGA或者ARM-M3上的攝像頭模塊都需要一些設置和添加模塊(frame buffer,等)。所以爲了pre-simulation,將圖像作爲txt 文件讀入verilog裏面。
1. 所以第一步是MATLAB code: 把圖像轉化爲binary txt 文件。
注意:不通的圖像文件的格式不同:如BMP是有(row X col X 3)而PGM則只有1層。因爲SIFT裏面是用的PGM,所以這個例子裏面我就用PGM格式的。
%% transform image into text file
%% read the image in pgm format
tu = imread('file2.pgm');
%% get the size parameter to set in Verilog file
[row, col] = size(tu);
%% transform into 8bit binary number
tutu = dec2bin(tu);
%% get the string length of binary data
len = size(tutu);
%% then simply open tutu and CtrlC+CtrlV to 'img.txt'
2. 當第一步完成後得到binary文檔後,就可以在Verilog裏面用$readmemh或者$readmemb。 eg:$readmemh("mem3.txt",mem4); 讀入。
`timescale 1ns / 1ps
module rotate;
parameter row = 115,
col = 153,
len = row*col;// = 17595;
reg clk;
reg[0:7] mem1[0:len-1];
reg[0:7] mem3[0:len-1];
reg[0:7] mem4[0:len-1];
integer r,c,p,newp,n,x,i,file1,file2;
initial clk=0;
always #5 clk=~clk;
initial
$readmemb("img.txt",mem1); //讀入 img.txt 中的數據寄存在 mem1 中
initial
for(c=0;c<col;c=c+1)
begin
for(r=0;r<row;r=r+1)
begin
p=c*row + r; //c*col+r;
newp=col*(row-1-r)+c; //將 153*115 的數據轉置並上下顛倒,實現圖像翻轉
@(posedge clk)
mem3[newp]=mem1[p]; //每週期將 mem2 中的數據寄存 mem3 的新位置中
end
end
initial begin
file1=$fopen("mem3.txt"); //新建 mem3.txt
wait (c==col)
for(x=0;x<len;x=x+1)
$fwrite(file1,"%h ",mem3[x]); //當所有數據寄存在 mem3 中後,寫入 mem3.txt(16 進制)
$fclose(file1);
$readmemh("mem3.txt",mem4); //讀入 mem3.txt 的數據寄存在 mem4 中
file2=$fopen("result.txt"); //新建 result.txt
for(i=0;i<len;i=i+1)
begin @(posedge clk)
$fwrite(file2,"%d ",mem4[i]); //每週期將寄存在 mem4 中的數據寫入 result.txt(十進制)
end
$fclose(file2);
end
endmodule
當Verilog用Iverilog編譯之後就可以並用VVP執行後就可以得到輸出。注意:Verilog只可以處理2維數組。
3. 現在就可以將結果用MATLAB轉換成圖像文件來驗證了:
%% load dec output from Verilog
qq = load('lena2.txt');
%% transform into binary
qqq = uint8(qq);
%% reshape to size of 'img.pgm'
Q = reshape(qqq, 153, 115);
%% plot
imshow(Q);
這裏分別是輸入:
和輸出圖像: