原始图
轮廓图
相关代码如下
Image imageSource = new Image((Bitmap)loadPictureBox.Image);
Image imageGrayscale = imageSource.Convert();
Image dest = new Image(imageGrayscale.Width, imageGrayscale.Height);
CvInvoke.cvThreshold(imageGrayscale, dest, 30, 255, Emgu.CV.CvEnum.THRESH.CV_THRESH_BINARY);
loadPictureBox.Image = dest.ToBitmap();
IntPtr Dyncontour = new IntPtr();
IntPtr Dynstorage = CvInvoke.cvCreateMemStorage(0);
MCvContour con = new MCvContour();
int n = CvInvoke.cvFindContours(dest, Dynstorage, ref Dyncontour, Marshal.SizeOf(con), Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_TREE, Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_LINK_RUNS, new Point(0, 0));
Seq DyncontourTemp = new Seq(Dyncontour, null);
IntPtr dst = CvInvoke.cvCreateImage(CvInvoke.cvGetSize(dest), Emgu.CV.CvEnum.IPL_DEPTH.IPL_DEPTH_8U, 3);
CvInvoke.cvZero(dst);
int areaTotal = 0;//求轮廓面积
double max = 0;//求轮廓最大矩阵对角线
for (; DyncontourTemp != null && DyncontourTemp.Ptr.ToInt32() != 0; DyncontourTemp = DyncontourTemp.HNext)
{
Rectangle r = DyncontourTemp.BoundingRectangle;
double tmp = Math.Sqrt(r.Height * r.Height + r.Width * r.Width);
if (tmp > max)
{
max = tmp;
}
areaTotal += r.Width * r.Height;
//画出轮廓
CvInvoke.cvRectangle(dst, new Point(r.X, r.Y), new Point(r.X + r.Width, r.Y + r.Height), new MCvScalar(255, 0, 0), 1, Emgu.CV.CvEnum.LINE_TYPE.EIGHT_CONNECTED, 0);
}
MessageBox.Show("Area Total :" + areaTotal.ToString());
MessageBox.Show("Max Dist : " + max.ToString());
CvInvoke.cvNamedWindow("dst");
CvInvoke.cvShowImage("dst", dst);
IntPtr2Image(dst).Save("001-1.jpg");//保存轮廓图形