public static Mat GetRectangle(Point[] point) { VectorOfPoint vt = new VectorOfPoint(point); Mat face = vt.GetInputArray().GetMat(); return(face); }
private void btStep4_Click(object sender, EventArgs e) { Mat thresh = new Mat(); CvInvoke.Threshold(cropped, thresh, 0, 255, ThresholdType.BinaryInv | ThresholdType.Otsu); VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint(); Mat hierarchy = new Mat(); CvInvoke.FindContours(thresh.Clone(), contours, hierarchy, RetrType.External, ChainApproxMethod.ChainApproxSimple); CvInvoke.DrawContours(cropped, contours, -1, new MCvScalar(0), 2); imageResult.Image = cropped; List <Point[]> questionContours = new List <Point[]>(); for (int i = 0; i < contours.Size; i++) { VectorOfPoint contour = contours[i]; Rectangle bounding = CvInvoke.BoundingRectangle(contour.GetInputArray().GetMat()); double ratio = bounding.Width / bounding.Height; if (bounding.Width >= 20 && bounding.Height >= 20 && ratio >= 0.95 && ratio <= 1.05) { questionContours.Add(contour.ToArray()); CvInvoke.Rectangle(thresh, bounding, new MCvScalar(255, 0, 0), 1); } } questionContours.Sort(new Comparison <Point[]>((a, b) => { if (a[0].X > b[0].X) { return(1); } else if (a[0].X < b[0].X) { return(-1); } return(0); })); answerSheet = new List <List <AnswerCell> >(); int xError = 5; int currentX = questionContours[0][0].X; int currentGroup = 0; answerSheet.Add(new List <AnswerCell>()); for (int i = 1; i < questionContours.Count; i++) { if (Math.Abs(questionContours[i][0].X - currentX) < xError) { VectorOfPoint contour = new VectorOfPoint(questionContours[i]); Rectangle bounding = CvInvoke.BoundingRectangle(contour.GetInputArray().GetMat()); Mat croppedBubble = new Mat(thresh, bounding); //Add to current column answerSheet[currentGroup].Add(new AnswerCell() { Contour = questionContours[i], Marked = CvInvoke.CountNonZero(croppedBubble) }); } else { //Sort current column answerSheet[currentGroup].Sort(new Comparison <AnswerCell>((a, b) => { if (a.Contour[0].Y > b.Contour[0].Y) { return(1); } else if (a.Contour[0].Y < b.Contour[0].Y) { return(-1); } return(0); })); currentX = questionContours[i][0].X; currentGroup++; //Create new column answerSheet.Add(new List <AnswerCell>()); } } imageResult.Image = thresh; }