/// <summary> /// 獲取區域 /// </summary> /// <param name="bitmap"></param> /// <param name="graybtm"></param> /// <returns></returns> public static Bitmap FindBundingBox(Bitmap bitmap, out Bitmap graybtm,out List<Rectangle> rects) { Image<Bgr, byte> img = new Image<Bgr, byte>(bitmap); Image<Gray, byte> gray = new Image<Gray, byte>(img.Width, img.Height); Image<Bgr, byte> resuImage = new Image<Bgr, byte>(img.Width, img.Height); Image<Gray, byte> dnc = new Image<Gray, byte>(img.Width, img.Height); CvInvoke.CvtColor(img, gray, ColorConversion.Bgra2Gray);//灰度化 //做一下膨脹,x與y方向都做,但系數不同 var kernal = CvInvoke.GetStructuringElement(ElementShape.Rectangle, new Size(4, 4), new Point(1, 1)); CvInvoke.Erode(gray, gray, kernal, new Point(0, 2), 1, BorderType.Default, new MCvScalar()); //CvInvoke.Canny(gray, gray, 100, 60); CvInvoke.Threshold(gray, gray, 100, 255, ThresholdType.BinaryInv | ThresholdType.Otsu);//二值化 //檢測連通域,每一個連通域以一系列的點表示,FindContours方法只能得到第一個域 graybtm = gray.ToBitmap(); VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint(); CvInvoke.FindContours(gray, contours, dnc, RetrType.Ccomp, ChainApproxMethod.ChainApproxSimple); var color = new MCvScalar(0, 0, 255); Console.WriteLine(contours.Size); rects = new List<Rectangle>(); //開始遍歷 for (int i = 0; i < contours.Size; i++) { //得到這個連通區域的外接矩形 var rect = CvInvoke.BoundingRectangle(contours[i]); //如果高度不足,或者長寬比太小,認為是無效數據,否則把矩形畫到原圖上 if (rect.Height > 2 && rect.Width > 2) { rects.Add(rect); CvInvoke.DrawContours(resuImage, contours, i, color); } } return img.ConcateVertical(resuImage).ToBitmap(); }
private void StandardRects() { List<Rectangle> removeList=new List<Rectangle>(); foreach (var item in glbRect) { if (glbRect.Exists(o => o.Contains(item) && o!=item)) { removeList.Add(item); } } glbRect.RemoveAll(o => removeList.Contains(o)); glbRect=glbRect.OrderBy(o => o.X).ToList(); lb_count.Text = "輪廓總數:" + glbRect.Count; }