您的位置:首页 > 编程语言 > C#

C# OpenCV学习笔记五之图像轮廓

2011-09-22 21:41 791 查看
原始图



轮廓图



相关代码如下

Image<Bgr, Byte> imageSource = new Image<Bgr, byte>((Bitmap)loadPictureBox.Image);

Image<Gray, Byte> imageGrayscale = imageSource.Convert<Gray, Byte>();

Image<Gray, Byte> dest = new Image<Gray, Byte>(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<Point> DyncontourTemp = new Seq<Point>(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");//保存轮廓图形
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: