OpenGL-----Spatial Convolution

来源:互联网 发布:华为4 a数据分区破坏 编辑:程序博客网 时间:2024/05/18 02:28

Problem Description:
write and experiment with a program that will filter an image using spatial convolution
Filter is like this:
box filter:
3
1 1 1
1 1 1
1 1 1
laplacian filter:(sharpen filter,edge detect)
3
0 -1 0
-1 4 -1
0 -1 0
KEY:
convolve(filter,image)function-convolve the image use filters,the image edge use zero to padding.(Other way like symmetry padding…)
Core codes is below.Careful when you do the convolution,you need to extend a new space for the temporal result, because all the convolve must use the original image data.

// convolve image use filtervoid convolve( float ** filter,rgba_pixel **image){temp_buffer = new rgba_pixel*[HEIGHT];   temp_buffer[0] = new rgba_pixel[WIDTH*HEIGHT];   for (int i=1; i<HEIGHT; i++) {      temp_buffer[i] = temp_buffer[i-1] + WIDTH;   } mat = new rgba_pixel*[N];   mat[0] = new rgba_pixel[N*N];   for (int i=1; i<N; i++) {      mat[i] = mat[i-1] + N;   }    cout<<"start convolve"<<endl;    for (int row=0; row<HEIGHT; row++) {      for (int col=0; col<WIDTH; col++) {        for(int i=0;i<N;i++)         for(int j=0;j<N;j++)       {      if((row-N/2+i)<0||(col-N/2+j)<0||(row-N/2+i)>=HEIGHT||(col-N/2+j)>=WIDTH)      {      mat[i][j].r=0;      mat[i][j].g=0;      mat[i][j].b=0;      }      else {      mat[i][j].r=image[row-N/2+i][col-N/2+j].r;      mat[i][j].g=image[row-N/2+i][col-N/2+j].g;      mat[i][j].b=image[row-N/2+i][col-N/2+j].b;      }      }        float r=0,g=0,b=0;        for (int m=0;m<N;m++)        for(int p=0;p<N;p++)        {        r=filter[m][p]*mat[m][p].r+r;        g=filter[m][p]*mat[m][p].g+g;        b=filter[m][p]*mat[m][p].b+b;        }        temp_buffer[row][col].r=(r/scale);        temp_buffer[row][col].g=(g/scale);        temp_buffer[row][col].b=(b/scale);      }      }      for (int row=0; row<HEIGHT; row++)         for (int col=0; col<WIDTH; col++)       {       image[row][col].r=temp_buffer[row][col].r;       image[row][col].g=temp_buffer[row][col].g;       image[row][col].b=temp_buffer[row][col].b;       }     cout<<"finish convolve"<<endl;}

some original image:
original squares
original brushes

After convolution:
3 emboss filter
-2 -1 0
-1 1 1
0 1 2
emboss

tent filter:
3
0.3 0.5 0.3
0.5 1.0 0.5
0.3 0.5 0.3
tent

box filter(size:9)
box9
sober-horiz
3
-1 0 1
-2 0 2
-1 0 1
sober-horizon
sober-vert
3
-1 -2 -1
0 0 0
1 2 1
sober-vert filter

ADVANCED REQUIREMENT
A Gabor filter is one in which the filter kernel weights are determined by xˆ 2 + yˆ 2 2 π xˆ
g(x,y;θ,σ,T) = exp(− 2σ2 )cos( T )
where
xˆ = x cos θ + y sin θ
and
yˆ = −x sin θ + y cos θ
Here (x,y) are distances measured from the kernel center, θ is an angular orientation, σ is the standard deviation of the Gaussian curve, and T is the period of the cosine.

Gabor θ =0, σ=4,T=4
gabor044

0 0
原创粉丝点击