ViniLL
ViniLL

Reputation: 147

sliding window in verilog when doing convolution

I am working on my CNN project in Verilog , but I am having some problems of implementing convolution procedure of Image with 3x3 Filter. I wrote a code for convolutional module, but now when it comes to convolution, I have to read the values from memory, which contains the pixels of the image. The thing is that I have to read these values in particular order, since convolution takes the dot product of 2 matrices and then strides it by 1 to the right. So let's say if the image is 5x5 matrix which stored in a memory array

[ a1 a2 a3 a4 a5

a6 a7 a8 a9 a10

a11 a12 a13 a14 a15 ] - memory Ram

how can I read the values of the memory in the following order: a1 then a2 then a3 , then a6 then a7 then a8, and last row a11 a12 a13, and then stride and start over starting with a2 , a3, etc. til I reach the end of my array. Please suggest any solution how I should address the memory in this situation, the code snippet would be highly appreciated. Thank you.

p.s. my memory array will contain a lot of data, approximately will be a matrix of [400x300] , where the filter is [3x3].

Upvotes: 0

Views: 3821

Answers (1)

Oldfart
Oldfart

Reputation: 6269

Looks like a simple case of nested for-loops. This walk through the 16-entry memory as you wanted:

for (start=0; start<3; start=start+1)
   for(i=1; i<16; i=i+5)
      for (j=0; j<3; j=j+1)
         data = mem[start+i+j]; // C: printf("%d\n",start+i+j);

Note that the code is both C and Verilog compatible so you can test your sequence in a C-compiler if you want (I did).

If you don't like the for loops you can make them into counters. In HDL you always reverse the order and start with the inner loop:

if (j<3)
   j <= j + 1;
else
begin
   j <=0; 
   if (i<16) // should be 15 if you start from 0 
      i <= i + 5;
   else
   begin
      i <= 1; // You sure it should not be zero?
      if (start<3)
         start <= start + 1;
      else
      begin
         start <= 0;
         all_done <= 1'b1
      end // nd of start
   end // end of j
end // end of i 

In a different part pf the design you can now use start+i+j as address.
Last : I would start with indices 0,1,2 as your picture is likely to start from memory address 0. You need to change the 'i' loop for that.

(HDL code is not compiled or tested)

Upvotes: 1

Related Questions