標籤:c++ sobel
這裡增加了對邊緣像素的補齊。sobel梯度分割抗噪性好,但是無法做到自動閾值,是其一大遺憾,matlab卻解決的很好。
//預設對8位位元影像進行處理void Sobel(unsigned char *pIn, int width, int height, unsigned char *pOut){//每行像素所佔位元組數,輸出映像與輸入映像相同int lineByte=(width+3)/4*4;//申請輸出映像緩衝區pOut=new unsigned char[lineByte*height];//迴圈變數,映像的座標int i,j;//中間變數int x, y, t;//Sobel運算元for(i=1;i<height-1;i++){for(j=1;j<width-1;j++){//x方向梯度x= *(pIn+(i-1)*lineByte+j+1) + 2 * *(pIn+i*lineByte+j+1) + *(pIn+(i+1)*lineByte+j+1) - *(pIn+(i-1)*lineByte+j-1) - 2 * *(pIn+i*lineByte+j-1) - *(pIn+(i+1)*lineByte+j-1);//y方向梯度y= *(pIn+(i-1)*lineByte+j-1)+ 2 * *(pIn+(i-1)*lineByte+j)+ *(pIn+(i-1)*lineByte+j+1)- *(pIn+(i+1)*lineByte+j-1)- 2 * *(pIn+(i+1)*lineByte+j)- *(pIn+(i+1)*lineByte+j+1);t=abs(x)+abs(y)+0.5;if (t>100){*(pOut+i*lineByte+j)=255;}else{*(pOut+i*lineByte+j)=0;}}}for(j=0;j<width;j++){*(pOut+(height-1)*lineByte+j)=0;//補齊最後一行*(pOut+j)=0;//補齊第一行} for(i=0;i<height;i++) {*(pOut+i*lineByte)=0;//補齊第一列*(pOut+i*lineByte+width-1)=0;//補齊最後一列} }}
image=imread('C:\\Users\\Liu\\\Desktop\\lenna.bmp');Info=imfinfo('C:\\Users\\Liu\\\Desktop\\lenna.bmp'); %讀映像資訊,並判斷是否是灰階圖if Info.BitDepth>8image=rgb2gray(image);endBW=edge(image,'sobel');imshow(BW)
甚至對比opencv,matlab的效果也略勝一籌,接下來希望深入matlab底層,用c++實現matlab的sobel運算元。
sobel運算元實現邊緣檢測及其c++實現及與matlab效果對比