http://blog.csdn.net/u013162930/article/details/51941531
轮廓是图像中表示边界的一系列点的集合。
OpenCV3.0中的函数原型如下:
void findContours(InputOutArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset = Point())
Mat srcImage = imread("M:/图像处理实验/轮廓提取/test-1.bmp",1);
cvtColor(srcImage, srcImage, COLOR_BGR2GRAY);
adaptiveThreshold(srcImage,srcImage,255,ADAPTIVE_THRESH_GAUSSIAN_C,THRESH_BINARY, 35, 10);
Mat result = Mat::zeros(srcImage.size(), CV_8UC3);
srcImage.copyTo(result);
Canny(srcImage,srcImage,3,6,3);
vector > contours;
vector hierarchy;
findContours(srcImage, contours, hierarchy, CV_RETR_TREE, CHAIN_APPROX_SIMPLE);
int areaMin = srcImage.cols * srcImage.rows;
for (int i = 0; i < contours.size(); i++ ){
double area = contourArea(((contours)._Myfirst)[i]);
if (area > srcImage.rows * srcImage.cols/3){
//选取满足条件的最小的面积。认为改轮廓为答题卡的边框。
if (areaMin > area){
areaMin = area;
}else{
continue;
}
double area = contourArea(((contours)._Myfirst)[i]);
Scalar color(rand() & 255, rand() & 255, rand() & 255);
drawContours(result, contours, i, color, CV_FILLED, 8, hierarchy, 0, Point());
}
}
imwrite("M:/图像处理实验/轮廓提取/test-1-result.bmp", result);
EmguCV3.0中的函数原型如下:
Public Shared Sub FindContours(image As Emgu.CV.IInputOutputArray, contours As Emgu.CV.IOutputArray, hierarchy As Emgu.CV.IOutputArray, mode As Emgu.CV.CvEnum.RetrType, method As Emgu.CV.CvEnum.ChainApproxMethod, Optional offset As System.Drawing.Point = Nothing)
Dim bkGrayWhite As New Gray(255)
Dim img As Image(Of Gray, Byte) = New Image(Of Gray, Byte)("M:\图像处理实验\轮廓提取\test-2.bmp")
Dim img_threshold As Image(Of Gray, Byte) = New Image(Of Gray, Byte)(img.Width, img.Height, bkGrayWhite)
Dim imgresult As Image(Of Rgb, Byte) = New Image(Of Rgb, Byte)(img.Width, img.Height, New Rgb(255, 255, 255))
img.CopyTo(img_threshold)
CvInvoke.AdaptiveThreshold(img_threshold, img, 255, CvEnum.AdaptiveThresholdType.MeanC, CvEnum.ThresholdType.Binary, 35, 10)
Dim imgCanny As Image(Of Gray, Byte) = New Image(Of Gray, Byte)(img.Width, img.Height, bkGrayWhite)
CvInvoke.Canny(img, imgCanny, 25, 25 * 2, 3)
Dim contours As Emgu.CV.Util.VectorOfVectorOfPoint = New Emgu.CV.Util.VectorOfVectorOfPoint()
Dim hierarchy As Emgu.CV.IOutputArray = New Image(Of Gray, Byte)(img.Width, img.Height, bkGrayWhite)
CvInvoke.FindContours(imgCanny,
contours,
hierarchy,
Emgu.CV.CvEnum.RetrType.External,
Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple
)
Dim areaMax As Integer = img.Width * img.Height
For i = 0 To contours.Size - 1
Dim area As Integer = CvInvoke.ContourArea(contours(i))
'筛选轮廓面积大于三分之一整体图片面积的轮廓
If area < areaMax / 3 Then
Continue For
End If
CvInvoke.DrawContours(imgresult, contours, i, New MCvScalar(0, 0, 0), 2, CvEnum.LineType.EightConnected, hierarchy, 2147483647)
Next
imgresult.Save("M:\图像处理实验\轮廓提取\test-2-result.bmp")