我的图像尺寸为(352 x 240)
我想裁剪白色区域(选定区域如下所示)。
我使用此代码裁剪图像,
private static Image cropImage(Image img, Rectangle cropArea)
{
Bitmap bmpImage = new Bitmap(img);
Bitmap bmpCrop = bmpImage.Clone(cropArea,
bmpImage.PixelFormat);
return (Image)(bmpCrop);
}
但是我找不到我需要的确切矩形区域!
如何找到Rectangle
选定区域的价值?
我只想播种这个区域!谢谢 !
如果您想自己做,当然可以。但是,如何做到最好的细节在很大程度上取决于您对源图像的了解程度。
以下是一些要考虑的问题和决定:
查看您的示例,您可以例如尝试以下策略:
为此,您必须对预期的颜色变化有所了解:是否会涉及平滑处理?如果是这样,您需要比较什么变化水平的GetPixel
颜色?
同样,尺寸应该大约已知,否则您可能需要使用更细的网格重复整个过程。
编辑:使用评论中的信息,您可以做一些假设(*),然后使用这段代码来确定目标矩形。这些假设用于:
我使用了色差功能和4个点数列表,并在几次点击中求平均值。该变量blur
的图像值为2-6。
List<Point> xPoints1 = new List<Point>();
List<Point> xPoints2 = new List<Point>();
List<Point> yPoints1 = new List<Point>();
List<Point> yPoints2 = new List<Point>();
Rectangle findRectangle()
{
int xMax = pictureBox1.Image.Width;
int yMax = pictureBox1.Image.Height;
// * we can asume that these lines hit the body
int x0 = xMax * 3 / 4;
int y0 = yMax * 3 / 4;
using (Bitmap bmp = new Bitmap(pictureBox1.Image) )
{
// we can assume that these are the out- and inside colors
Color col0 = bmp.GetPixel(9, 9);
Color col1 = bmp.GetPixel(x0, y0);
int blur = 4;
int diff = colordistance(col0, col1) / blur;
bool outside = true;
// a few horizontal scans..
for (int y = y0 - 20; y < y0 + 20; y += 4)
{
outside = true;
for (int x = 0; x < xMax; x++)
{
Color c = bmp.GetPixel(x, y);
if ( outside && colordistance(c, col0) > diff)
{ outside = !outside; xPoints1.Add(new Point(x, y)); }
else if (!outside && colordistance(c, col1) > diff)
{ outside = !outside; xPoints2.Add(new Point(x, y)); }
}
}
// a few vertical scans..
for (int x = x0 - 20; x < x0 + 20; x += 4)
{
outside = true;
for (int y = 0; y < yMax; y++)
{
Color c = bmp.GetPixel(x, y);
if (outside && colordistance(c, col0) > diff)
{ outside = !outside; yPoints1.Add(new Point(x, y)); }
else if (!outside && colordistance(c, col1) > diff)
{ outside = !outside; yPoints2.Add(new Point(x, y)); }
}
}
int left = (int)xPoints1.Average(p => p.X);
int right = (int)xPoints2.Average(p => p.X);
int top = (int)yPoints1.Average(p => p.Y);
int bottom = (int)yPoints2.Average(p => p.Y);
// if the target sits at the bottom we didn't find the edge
if (bottom == 0) bottom = yMax;
return = new Rectangle(left, top, right - left, bottom - top);
}
}
int colordistance(Color c1, Color c2)
{
return (int) Math.Sqrt((c1.R - c2.R) * (c1.R - c2.R) +
(c1.G - c2.G) * (c1.G - c2.G) +
(c1.B - c2.B) * (c1.B - c2.B));
}
注意:顶部和左侧的值命中目标的内部。底部(可能还有底部)撞到外面。因此,应根据需要将前者或后者减少1个像素。
编辑第一个版本的outside
变量设置在错误的位置。已更正。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句