接下來按照論文裏面的思想逐步實現:
1.讀取需要的圖片,爲灰色圖像,Sobel算子設置指針
IplImage* srcImg = cvLoadImage(".\\srcImg\\renlian1.jpg");
IplImage* gradImg[corNum];
IplImage* sobelImg[corNum];
IplImage* graySrcImg = cvCreateImage(cvGetSize(srcImg), srcImg->depth, 1);
2.對原圖像進行高斯濾波器平滑處理,之後轉換成灰度值圖像。
cvCvtColor(srcImg, graySrcImg, CV_BGR2GRAY);
for(int i=0; i<1; i++)
cvSmooth(graySrcImg, graySrcImg, CV_GAUSSIAN, 3, 0, 0);
3.利用Sobel算子對灰度值圖像進行卷積,計算出來Gx和Gy:
int sobel[2][9]={{-1, 0, 1,-2, 0, 2,-1, 0, 1}, {-1, -2, -1, 0, 0, 0, 1, 2, 1}};
float tempMag, tempAng;
float magX, magY;
for(int i=0; i<height; i++)
{
for(int j=0; j<width; j++)
{
unitArr[i][j].floMag = (int)( (unitArr[i][j].floMag / maxGrad) * 255 + 0.5);
}
}
for(int i=0; i<2; i++)
{
int tempA, tempB;
for(int m=0; m< height; m++)
{
for(int n=0; n< width; n++)
{
for(int l=0; l< winSize*winSize; l++)
{
tempA = abs(m + l/3 - 1) % hth;
tempB = abs(n + l%3 - 1) % wth;
tempSum = unitArr[tempA][tempB].floMag;
finalSum += tempSum * sobel[i][l];
}
finalSum = finalSum / MAX_VAL;
if(i ==0)
{
finalSum = (finalSum > 255)? 255 : finalSum;
finalSum = (finalSum < -255)? -255: finalSum;
unitArr[m][n].floX = finalSum;
}
else
{
finalSum = (finalSum > 255)? 255 : finalSum;
finalSum = (finalSum < -255)? -255: finalSum;
unitArr[m][n].floY = finalSum;
}
finalSum = 0;
tempSum = 0;
}
}
4.求出梯度的方向,方便梯度∠的計算:
unitArr[i][j].floX = -magY;
unitArr[i][j].floY = magX;
5.利用Gx和Gy 求出一階導數:
for(int i=0; i<corNum; i++)
{
gradImg[i] = cvCreateImage(cvGetSize(srcImg), graySrcImg->depth, 1);
cvCopy(graySrcImg, gradImg[i], NULL);
}
6.之後就可以得到輸出的圖像了。
ps:最開始在配置opencv的環境的時候發生 了很多問題,總是缺少各種各樣的文件。
其中的一些問題可以參考以下這篇博客:https://www.cnblogs.com/linshuhe/p/5764394.html。感覺寫得很詳細。