上一篇自动对焦里文章里用的评价函数,有用到opencv里的sobel算子。
我这边用C++实现下opencv里的这个算子
sobel算子的两个内核分别是{-1,0,1;-2,0,2;-1,0,1} {-1,-2,-1;0,0,0;1,2,1}
先实现下opencv里图像彩色转灰色的算子
Mat BGR2GRAY(Mat img) { int width = img.cols; int height = img.rows; Mat grayImg(height, width, CV_8UC1); uchar *p = grayImg.ptr(0); Vec3b *pImg = img.ptr (0); for (int i = 0; i < width*height; ++i) { p[i] = 0.2126*pImg[i][2] + 0.7152*pImg[i][1] + 0.0722*pImg[i][0]; } return grayImg; }
然后实现下sobel算子
Mat sobel_filter(Mat img, bool horizontal) { int height = img.rows; int width = img.cols; Mat out=Mat::zeros(height, width, CV_16S); double kernel[3][3] = { {-1,-2,-1},{0,0,0},{1,2,1} }; if (horizontal) { kernel[0][1] = 0; kernel[0][2] = 1; kernel[1][0] = -2; kernel[1][2] = 2; kernel[2][0] = -1; kernel[2][1] = 0; } short* pOut = out.ptr(0); uchar *p1 = img.ptr (0); uchar *p2 = img.ptr (0); uchar *p3 = img.ptr (0); for (int j = 1; j < height-1; ++j) { pOut = pOut + width; p2 = p1 + width; p3 = p2 + width; for (int i = 1; i < width-1; ++i) { pOut[i] = p1[i - 1] * kernel[0][0] + p1[i] * kernel[0][1] + p1[i + 1] * kernel[0][2] + p2[i - 1] * kernel[1][0]+p2[i + 1] * kernel[1][2] + p3[i - 1] * kernel[2][0] + p3[i] * kernel[2][1] + p3[i + 1] * kernel[2][2]; } p1 = p1 + width; } return out; }
OK
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)