【发布时间】:2016-05-17 00:21:17
【问题描述】:
我需要在测试表格中找到三个黑色方块的坐标。我从站点 emgu.com 获取示例代码并稍作更改,但他没有找到我需要的内容。图片尺寸为A4,试卷尺寸为A5。我希望你的帮助:) 我差点忘了,正方形的大小是 30 像素。
private void DetectRectangles(Image<Gray, byte> img)
{
var size = new Size(3, 3);
CvInvoke.GaussianBlur(img, img, size, 0);
CvInvoke.AdaptiveThreshold(img, img, 255, AdaptiveThresholdType.MeanC, ThresholdType.Binary, 75, 100);
UMat cannyEdges = new UMat();
CvInvoke.Canny(img, cannyEdges, 180, 120);
var boxList = new List<RotatedRect>();
using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint())
{
CvInvoke.FindContours(cannyEdges, contours, null, RetrType.Tree, ChainApproxMethod.ChainApproxSimple);
int count = contours.Size;
for (int i = 0; i < count; i++)
{
using (VectorOfPoint contour = contours[i])
using (VectorOfPoint approxContour = new VectorOfPoint())
{
CvInvoke.ApproxPolyDP(contour, approxContour, CvInvoke.ArcLength(contour, true) * 0.05, true);
var area = CvInvoke.ContourArea(approxContour);
if (area > 800 && area < 1000)
{
if (approxContour.Size == 4)
{
bool isRectangle = true;
Point[] pts = approxContour.ToArray();
LineSegment2D[] edges = PointCollection.PolyLine(pts, true);
for (int j = 0; j < edges.Length; j++)
{
double angle = Math.Abs(edges[(j + 1) % edges.Length].GetExteriorAngleDegree(edges[j]));
if (angle < 75 || angle > 94)
{
isRectangle = false;
break;
}
}
if (isRectangle)
boxList.Add(CvInvoke.MinAreaRect(approxContour));
}
}
}
}
}
var resultimg = new Image<Bgr,byte>(img.Width, img.Height);
CvInvoke.CvtColor(img, resultimg, ColorConversion.Gray2Bgr);
foreach (RotatedRect box in boxList)
{
CvInvoke.Polylines(resultimg, Array.ConvertAll(box.GetVertices(), Point.Round), true, new Bgr(Color.Red).MCvScalar, 2);
}
imageBox1.Image = resultimg;
resultimg.Save("result_img.jpg"); }
输入图片:
【问题讨论】: