我正在尝试制作扫描应用程序。该应用程序将扫描文档并在图片框中显示图像。我面临的问题是图像(保存在扫描仪中的文档图像或说“真实”图像)显示在另一个具有某些背景的图像中(该背景颜色也在变化)它看起来像这个图像。
我尝试了很多东西,但没有给我一个完美的结果,我用 forge.net 尝试了它。这是我尝试过的代码。
public static System.Drawing.Image AforgeAutoCrop(Bitmap selectedImage)
{
Bitmap autoCropImage = null;
try
{
autoCropImage = selectedImage;
// create grayscale filter (BT709)
Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
Bitmap grayImage = filter.Apply(autoCropImage);
// create instance of skew checker
DocumentSkewChecker skewChecker = new DocumentSkewChecker();
// get documents skew angle
double angle = skewChecker.GetSkewAngle(grayImage);
// create rotation filter
RotateBilinear rotationFilter = new RotateBilinear(-angle);
rotationFilter.FillColor = Color.White;
// rotate image applying the filter
Bitmap rotatedImage = rotationFilter.Apply(grayImage);
new ContrastStretch().ApplyInPlace(grayImage);
new Threshold(100).ApplyInPlace(grayImage);
BlobCounter bc = new BlobCounter();
bc.FilterBlobs = true;
// bc.MinWidth = 500;
//bc.MinHeight = 500;
bc.ProcessImage(grayImage);
Rectangle[] rects = bc.GetObjectsRectangles();
MemoryStream writeName = new MemoryStream();
if (rects.Length == 0)
{
System.Windows.Forms.MessageBox.Show("No rectangle found in image ");
}
else if (rects.Length == 1)
{
Bitmap cropped = new Crop(rects[0]).Apply(autoCropImage);
autoCropImage = cropped;
// pictureBox1.Image = cropped;
}
else if (rects.Length > 1)
{
// get largets rect
Console.WriteLine("Using largest rectangle found in image ");
var r2 = rects.OrderByDescending(r => r.Height * r.Width).ToList();
//var r2 = rects.OrderByDescending(r => r.Height < 1500 && r.Width < 1000).ToList();
Bitmap cropped = new Crop(r2[0]).Apply(autoCropImage);
Graphics gr = Graphics.FromImage(cropped);
gr.DrawRectangles(new Pen(Color.Red), rects);
autoCropImage = cropped;
// pictureBox1.Image = cropped;
}
else
{
Console.WriteLine("Huh? on image ");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
return autoCropImage;
}