利用sobel遮罩來做測邊:
測y方向的灰階變化的Mask為 int y[3][3] = { { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 } };
測x方向的灰階變化的Mask為 int x[3][3] = { { -1, 0, 1 }, { -2, 0, 2 }, {-1, 0, 1 } };
#include<iostream>
#include <cv.h>
#include <highgui.h>
void sobel(uchar *data2, const int x[3][3], const int y[3][3], int height,int width, int step2)
{
for (int i = 1; i < height; i++)
{
for (int j = 1; j < width; j++)
{
for (int m = 0; m < 3; m++)
{
for (int n = 0; n < 3; n++)
{
int sum = 0;
sum += (x[m][n] + y[m][n])*data2[(i + (m - 1))*step2 + j + (n - 1)];
data2[i*step2 + j] = sum;
}
}
}
}
}
void sobel_edge(uchar *data2, int width, int height, int step2)
{
for (int i = 0; i < height + 2; i++)
{
for (int j = 0; j < width + 2; j++)
{
int pixel = data2[i*step2 + j];
if (pixel>95)
{
data2[i*step2 + j] = 255;
}
else
data2[i*step2 + j] = 0;
}
}
}
void main()
{
int y[3][3] = { { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 } };
int x[3][3] = { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } };
IplImage *img1;
IplImage *img2 = cvCreateImage(cvSize(722,1282), IPL_DEPTH_8U, 1);
//根據圖像的大小自己調整
img1 = cvLoadImage("NiKi.jpg", 0);
int height = img1->height;
int width = img1->width;
int step = img1->widthStep;
uchar* data1 = (uchar*)img1->imageData;
int step2 = img2->widthStep;
uchar* data2 = (uchar *)img2->imageData;
//複製img1到img2
for (int i = 1; i < height + 1; i++)
{
for (int j = 1; j < width + 1; j++)
{
data2[i*step2 + j] = data1[(i - 1)*step + (j - 1)];
}
}
//複製邊緣的值到圖外面一個像素
for (int i = 0; i<height + 2; i++)
{
for (int j = 0; j<width + 2; j++)
{
if (i == 0 && j == 0)
data2[i*step2 + j] = data2[(i + 1)*step2 + (j + 1)];
else if (i == width + 1 && j == height + 1)
data2[i*step2 + j] = data2[(i - 1)*step2 + (j - 1)];
else if (i == 0 && j == width + 1)
data2[i*step2 + j] = data2[(i - 1)*step2 + (j + 1)];
else if (i == height + 1 && j == 0)
data2[i*step2 + j] = data2[(i + 1)*step2 + (j - 1)];
else if (i == 0)
data2[i*step2 + j] = data2[(i + 1)*step2 + j];
else if (j == 0)
data2[i*step2 + j] = data2[i*step2 + (j + 1)];
else if (i == height + 1)
data2[i*step2 + j] = data2[(i - 1)*step2 + j];
else if (j == width + 1)
data2[i*step2 + j] = data2[i*step2 + (j - 1)];
}
}
sobel(data2, x, y, width, height, step2);
sobel_edge(data2, width, height, step2);
cvNamedWindow("NiKi", 0);
cvShowImage("NiKi", img1);
cvNamedWindow("sobelNiKi", 0);
cvShowImage("sobelNiKi", img2);
cvWaitKey(0);
cvDestroyWindow("NiKi");
cvDestroyWindow("sobelNiKi");
cvReleaseImage(&img1);
}
顯示結果如下