在图像上卷积高斯掩模,而不使用内置函数

convolving a gaussian mask on an image, without using built-in functions

本文关键字:内置 函数 图像 卷积 高斯掩      更新时间:2023-10-16

我想在不使用cvcanny函数的情况下将canny边缘检测应用于图像,因此所需步骤的一部分是应用高斯掩模,我在x和y方向上有两个掩模。现在的问题是,每当我尝试将掩码卷积到我的图像上时,由于"访问违规",执行就会中断。为什么会发生这种情况?我该如何克服这种情况?

//DECLARATIONS..
double maskx[3][3];
double masky[3][3];
double convx[1000][1000]={0};
double convy[1000][1000]={0};
double M[1000][1000]={0};  //magnitude
double slope[1000][1000];

int gaussian_mask()
{
int MaskRadius=SIGMA*3;
double eq1;
double exp=2.71828183;
for(int p=-MaskRadius; p<=MaskRadius; p++)
{
for(int q=-MaskRadius; q<=MaskRadius; q++)
{
    eq1=-1*(p*p + q*q)/(2*SIGMA);
    maskx[p+MaskRadius][q+MaskRadius]=-1*q*(pow(exp,eq1));
    masky[p+MaskRadius][q+MaskRadius]=-1*p*(pow(exp,eq1));
}
}
return MaskRadius;
}
IplImage* convolve(IplImage *im)
{
int MaskRadius=gaussian_mask();
int row=im->width;
int col=im->height;
printf("row: %d, col= %d",row,col);
//-----------------------------------------------------------------------------------//
IplImage *pix=cvCreateImage(cvGetSize(im), im->depth, 1);      //converting 3 channel   to 1 channel
cvSetImageCOI(im,1);
cvCopy(im,pix);
cout<<endl<<"No. of channels = "<<pix->nChannels;
//-----------------------------------------------------------------------------------------------//
for(int i=MaskRadius; i<=row-MaskRadius; i++)             //convolving the image
{
uchar* ptr1 = (uchar*) (pix->imageData + i * pix->widthStep);
uchar* ptr0 = (uchar*) (pix->imageData + (i-1) * pix->widthStep);
uchar* ptr2 = (uchar*) (pix->imageData + (i+1) * pix->widthStep);
for(int j=MaskRadius; j<=col-MaskRadius; j++)
 {
     cout<<endl<<i<<" , "<<j;
     convx[i][j]=(double)ptr1[j-1]*maskx[1][0]+ptr1[j]*maskx[1][1]+ptr1[j+1]*maskx[1][2] + (ptr2[j-1]*maskx[0][0]+ptr2[j]*maskx[0][1]+ptr2[j+1]*maskx[0] + ptr0[j-1]*maskx[2][0]+ptr0[j]*maskx[2][1]+ptr0[j+1]*maskx[2][2]);
     convy[i][j]=(double)ptr1[j-1]*masky[1][0]+ptr1[j]*masky[1][1]+ptr1[j+1]*masky[1][2] + (ptr2[j-1]*masky[0][0]+ptr2[j]*masky[0][1]+ptr2[j+1]*masky[0] + ptr0[j-1]*masky[2][0]+ptr0[j]*masky[2][1]+ptr0[j+1]*masky[2][2]);
    double eq2=pow(convx[i][j],2)+pow(convy[i][j],2);
    M[i][j]=(double)sqrt(eq2);
}
}

在创建掩码、转换图像或进行卷积时,可能会发生访问冲突。您可以先注释掉所有代码,然后从顶部取消注释,同时观察哪一行/块会给您带来错误。还可以使用IDE的调试器来查看索引的值,并检查那些超出范围的值。