一般轮廓提取是通过对图像的梯度进行卷积计算,得到图像边缘(滤波),常用的边缘检测方法有candy、sobel、 Laplacian等,再对二值化后的边缘图像进行轮廓计算;
1、Candy算子;
cv::cvtColor(img, grayImg, cv::COLOR_RGB2GRAY); cv::blur(grayImg, tempImage, cv::Size(3,3));//先用均值滤波器进行平滑去噪 cv::Canny(tempImage, binaryImg, threshod,threshod * 3);
candy算子计算得到的是二值图像;
2、sobel算子;
cv::Mat tpImg,temp1,temp2,dstImg; cv::Sobel(img, tpImg, CV_16S, 1, 0,(2* kernelSize+1),1,1,cv::BORDER_DEFAULT);//求x方向梯度 cv::convertScaleAbs(tpImg, temp1);//计算绝对值,并将结果转换成8位 cv::Sobel(img, tempImage, CV_16S, 0, 1,(2*kernelSize+1),1,1,cv::BORDER_DEFAULT);//求y方向梯度 cv::convertScaleAbs(tempImage, temp2);//计算绝对值,并将结果转换成8位 addWeighted(temp1, 0.5, temp2, 0.5, 0, dstImg); //进行轮廓检测; cv::cvtColor(dstImg,grayImg,cv::COLOR_RGB2GRAY); cv::threshold(grayImg,binaryImg,0,255,cv::THRESH_BINARY | cv::THRESH_OTSU);
3、Laplacian算子;
cv::Mat temp1,temp2,dstImg; cv::GaussianBlur(img, temp1, cv::Size(3,3), 0,0,cv::BORDER_DEFAULT);//高斯滤波消除噪声 cv::cvtColor(temp1, grayImg, cv::COLOR_RGB2GRAY); cv::Laplacian(grayImg, temp2, CV_16S,(kernelSize*2+1),1,0,cv::BORDER_DEFAULT); convertScaleAbs(temp2, dstImg); cv::threshold(dstImg,binaryImg,0,255,cv::THRESH_BINARY | cv::THRESH_OTSU);
轮廓提取:
opencv提供了findContours函数来提取二值图的轮廓,利用drawContours能够标记提取得到的轮廓;
findContours:
C++: void findContours(InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset=Point()) C++: void findContours(InputOutputArray image, OutputArrayOfArrays contours, int mode, int method, Point offset=Point())¶
drawContours:
C++: void drawContours(InputOutputArray image, InputArrayOfArrays contours, int contourIdx, const Scalar& color, int thickness=1, int lineType=8, InputArray hierarchy=noArray(), int maxLevel=INT_MAX, Point offset=Point() )
注: 此博文为扩展型;