[C++] 纯文本查看 复制代码
/**************************************************
* Sobel算子边缘检测
* parameter: srcData - 原始图像数据指针
* dstData - 存储处理后的图像
* lWidth,lHeight - 图像的宽和高
* dLineBites - 单行图像的字节数(4的倍数)
备注:务必注意这个算子只允许单色图形,彩色图形请使用色觉公式转换
**************************************************/
void WINAPI SobelEdgeDetect(LPBYTE srcData,LPBYTE dstData,LONG lWidth,LONG lHeight,DWORD dLineBites)
{
int KERNEL[4][9] = {{-1,0,1,-2,0,2,-1,0,1},
{-1,-2,-1,0,0,0,1,2,1},
{-2,-1,0,-1,0,1,0,1,2},
{0,-1,-2,1,0,-1,2,1,0}};
int i,j,k,kernel_sum,total_sum = 0,nMax = 0;
unsigned char* pTmpSrcData = NULL;
unsigned char* pTmpDstData = NULL;
for (i = 1;i < lHeight - 1;i++)
{
pTmpSrcData = srcData + dLineBites * i;
pTmpDstData = dstData + dLineBites * i;
for (j = 1;j < lWidth - 1; ++j)
{
total_sum = 0;
nMax = 0;
for (k = 0;k < 4;k++)
{
kernel_sum = *(pTmpSrcData + j - dLineBites - 1) * KERNEL[k][0]+
*(pTmpSrcData + j - dLineBites ) * KERNEL[k][1]+
*(pTmpSrcData + j - dLineBites + 1) * KERNEL[k][2]+
*(pTmpSrcData + j - 1) * KERNEL[k][3]+
*(pTmpSrcData + j ) * KERNEL[k][4]+
*(pTmpSrcData + j + 1) * KERNEL[k][5]+
*(pTmpSrcData + j + dLineBites - 1) * KERNEL[k][6]+
*(pTmpSrcData + j + dLineBites ) * KERNEL[k][7]+
*(pTmpSrcData + j + dLineBites + 1) * KERNEL[k][8];
kernel_sum = abs(kernel_sum);
//total_sum += abs(kernel_sum);
if(nMax < kernel_sum)
nMax = kernel_sum;
}
if(nMax > 255)
nMax = 255;
*(pTmpDstData + j) = (unsigned char)nMax;
}
}
}