Write a C++ program Convolution is an incredibly important concept in many areas
ID: 3582862 • Letter: W
Question
Write a C++ program
Convolution is an incredibly important concept in many areas of math and engineering Convolution takes two 2-dimensional arrays: an input array and a kernel array. It produces a third 2-D array as output. Here is an example on how convolution is computed using a 3x3 kernel (4x0) (0 x 0) Center element of the kernel is placed over the (0 x 0) source pixel. The source pixel is then replaced with a weighted sum itself and nearby pixels. (0x0) (0 x 1) (0 x 1) (0x0) Source pixel (0 x 1) (-4 x 2) Convolution kernel (emboss) New pixel value (destination pixel) Figure 1 Let us consider the following second example using two 2-Darrays 1 2 3 1 1 0 0 0 7 8 9 Kernel npu Here, the input 2-D arrayis "convolved" with the kernel 2-D array and the corresponding output is produced (below). The steps of convolution are as follows: 1) First, add extra columns and rows of zeros tothe input matrix as follows, so that we be able to have the center of the kernel be positioned at the corner point of the original input (follow the figure 2 below). The figure shows that, to compute the convolution value for the cell (as highlighted red color in the input 2-D array), the kernel's centerExplanation / Answer
#include <stdio.h>
int** addpadding(int **a, int row, int col)
{
//initializing entire matrix with zero
int **temp = 0;
temp = new int *[row+2];
for(int i=0;i<row+2;i++)
temp[i] = new int[col+2];
//copying centre of zero_padded matrix with input matrix
for(int i=1;i<=row;i++)
for(int j=1;j<=col;j++)
temp[i][j] = a[i-1][j-1];
return temp;
}
int** convolve(int **input, int kernel[3][3], int row, int col)
{
int **output = 0;
output = new int *[row+1];
for(int i=1;i<=row;i++)
output[i] = new int[col+1];
for(int i=1;i<=row;i++) //loop from 1 to row for output matrix rows
for(int j=1;j<=col;j++) //loop from 1 to col for output matrix columns
for(int n=0,r=i-1;n<3;n++,r++) //loop for kernel rows
for(int m=0,s=j-1;m<3;m++,s++) //loop for kernel columns
output[i][j] += input[r][s] * kernel[n][m];
return output;
}
int main()
{
int **input, **input_zero_padded,**output, row, col;
int kernel[3][3] = {{1,2,1},{0,0,0},{-1,-2,-1}};
printf("Enter how many rows and columns : ");
scanf("%d %d",&row,&col);
printf("Enter your input values seperated by space : ");
input = new int *[row];
for(int i=0;i<row;i++)
{
input[i] = new int[col];
for(int j=0;j<col;j++)
scanf("%d",&input[i][j]);
}
input_zero_padded = addpadding(input, row, col);
output = new int *[row];
output = convolve(input_zero_padded, kernel, row, col);
printf("Convolve output matrix : ");
for(int i=1;i<=row;i++)
{
for(int j=1;j<=col;j++)
printf("%2d ",output[i][j]);
printf(" ");
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.