编辑:正如 Miki 在评论中指出的那样,您可能正在搜索旋转框。您可能想要OpenCvSharp.Cv.MinAreaRect2()
,它需要 aCvArr
点,并返回 a CvBox2D
。
参考
只要您不担心边界框的倾斜,边界框计算相对简单,找到最小封闭矩形只是找到对应于黑色像素的最小和最大 x 和 y 的问题。最简单的方法是这样的:
// You would actually use your image
Bitmap b = new Bitmap(640,480);
// For the demonstration generate some randomized data
Random r = new Random();
for (int i = 0; i < 1000; i++)
{
b.SetPixel(r.Next(200) + 50, r.Next(200) + 50, Color.Black);
}
int minX, minY;
int maxX, maxY;
minX = minY = int.MaxValue;
maxX = maxY = int.MinValue;
// Find the minimum and maximum black coordinates
for (int x = 0; x < b.Width; x++)
{
for (int y = 0; y < b.Height; y++)
{
if (b.GetPixel(x,y).ToArgb() == Color.Black.ToArgb())
{
if (x > maxX) maxX = x;
if (x < minX) minX = x;
if (y > maxY) maxY = y;
if (y < minY) minY = y;
}
}
}
// Draw a bounding box for the demonstration
using (Graphics g = Graphics.FromImage(b))
{
Pen red = new Pen(Color.Red);
g.DrawRectangle(red, minX, minY, maxX - minX, maxY - minY);
}
b.Save("c:\\tmp\\test.png");
诚然,这不是最干净的实现,但任何搜索最小值和最大值的算法都可以。(你只需要在两个维度上都这样做。)