我正在尝试从矩形物体(纸张)中找到4个角。
Mat source = new Mat();
Org.Opencv.Core.Point center;
public GetCorners(Bitmap _sourceImg)
{
Utils.BitmapToMat(_sourceImg, source);
}
//find corners
public void FindCorners()
{
center = new Org.Opencv.Core.Point(0, 0);
//Mat source = new Mat();
if (source == null)
{
Console.WriteLine("No IMG");
return;
}
Mat BlackWhite = new Mat();
Imgproc.CvtColor(source, BlackWhite, Imgproc. ColorBgr2gray); //ColorBgra2gray, 4);
Imgproc.Blur(BlackWhite, BlackWhite, new Size(3, 3));
Imgproc.Canny(BlackWhite, BlackWhite, 100, 100, 3, true);
Mat Lines = new Mat();
int treshold = 70;
int minLinsize = 30;
int lineGap = 10;
Imgproc.HoughLinesP(BlackWhite, Lines, 1, Math.PI / 180, treshold, minLinsize, lineGap);
for (int i = 0; i < Lines.Cols(); i++)
{
double[] Vector = Lines.Get(0, i);
double[] Value = new double[4];
Value[0] = 0;
Value[1] = ((float) Vector[1] - Vector[3]) / (Vector[0] - Vector[2]) * -Vector[0] + Vector[1];
Value[2] = source.Cols();
Value[3] = ((float)Vector[1] - Vector[3]) / (Vector[0] - Vector[2]) * (source.Cols() - Vector[2]) + Vector[3];
Lines.Put(0, i, Value);
}
Console.WriteLine("##Quantity {0} Founded##",Lines.Cols());
List<Org.Opencv.Core.Point> Corners = new List<Org.Opencv.Core.Point>();
for (int i = 0; i < Lines.Cols(); i++)
{
for (int j = 0 ; i < Lines.Cols(); j++)
{
Mat m1 = new Mat(),
m2 = new Mat();
double[] d1 = Lines.Get(0, i);
double[] d2 = Lines.Get(0, j);
m1.Put(0, j, d1);
m2.Put(0, j, d2);
try
{
//i'm getting exception here
Org.Opencv.Core.Point pt = ComputeInteresect(Lines.Get(0, i), Lines.Get(0, j)); //(m1, m2);
if (pt.X >= 0 && pt.Y >= 0)
{
Corners.Add(pt);
Console.WriteLine ("dobavleno {0} koordinat",Corners.Count);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
我还有一个计算相交的方法:
static Org.Opencv.Core.Point ComputeInteresect(double[] a, double[] b) //(Mat es,Mat es2)//
{
double x1 = a[0], y1 = a[1], x2 = a[2], y2 = a[3], x3 = b[0], y3 = b[1], x4 = b[2], y4 = b[3];
double denom = ((x1 - x2) * (y3 - y4)) - ((y1 - y2) * (x3 - x4));
Org.Opencv.Core.Point pt = new Org.Opencv.Core.Point();
if (denom != 0)
{
pt.X = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2)
* (x3 * y4 - y3 * x4))
/ denom;
pt.Y = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2)
* (x3 * y4 - y3 * x4))
/ denom;
return pt;
}
else
return new Org.Opencv.Core.Point(-1, -1);
}
我不明白为什么,但我得到了这个例外:
java.lang.UnsupportedOperationException: 提供的数据元素编号(0) 应该是Mat频道的多个 count(1)
我发现,当图像处于RGB格式(并且有4个通道)时会出现此问题,但首先,我通过此方法转换为灰色(1通道) :
Imgproc.CvtColor(source, BlackWhite, Imgproc. ColorBgr2gray); //ColorBgra2gray, 4);
任何帮助将不胜感激,谢谢!
答案 0 :(得分:0)
最后,我更改了部分代码及其工作:
public class ExceptionLogFilterAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
System.Diagnostics.Trace
.TraceError(string.Format("{0}\r\n\r\n",
filterContext.Exception.ToString()));
base.OnException(filterContext);
}
}