c# 如何去歪斜图像

c# how to deskew an image

我目前正在使用 OCR 程序。我正在使用 tesseract,我需要对图像进行校正以提高检测到的字符的质量。问题是 tesseract 给出的 deskew 属性 没有产生足够吸引人的结果。所以我尝试用 AForge 和 Atalasoft 对图像进行校正,但无论如何,每次图像都不是他们要求的格式。我究竟做错了什么?或者有更好的解决办法?

这是 AForge 实现

        System.Drawing.Bitmap imageToBitmap = AForge.Imaging.Image.FromFile(imagePath);
        Console.WriteLine("before  " + imageToBitmap.PixelFormat);
        System.Drawing.Bitmap NewPicture = imageToBitmap.Clone(new System.Drawing.Rectangle(0, 0, imageToBitmap.Width, imageToBitmap.Height), System.Drawing.Imaging.PixelFormat.Format24bppRgb);
        var dop = AForge.Imaging.Image.Clone(imageToBitmap, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
        Console.WriteLine("after  " + dop.PixelFormat);

        AForge.Imaging.DocumentSkewChecker skewChecker = new AForge.Imaging.DocumentSkewChecker();
        // get documents skew angle
        double angle = skewChecker.GetSkewAngle(dop);
        // create rotation filter
        AForge.Imaging.Filters.RotateBilinear rotationFilter = new AForge.Imaging.Filters.RotateBilinear(-angle);
        rotationFilter.FillColor = System.Drawing.Color.White;
        // rotate image applying the filter
        System.Drawing.Bitmap rotatedImage = rotationFilter.Apply(imageToBitmap);

        rotatedImage.Save("deskewedImage");

这是 Atalasoft 实现

        AtalaImage img = new AtalaImage(imagePath);
        AutoDeskewCommand cmd = new AutoDeskewCommand();
        AtalaImage resultImage = cmd.Apply(img).Image;
        resultImage.Save("result.tif", new TiffEncoder(), null);

我终于明白了为什么它不起作用:图像应该转换为 Format8bppIndexed 否则方法 skewChecker.GetSkewAngle(image) 将抛出异常

        Bitmap tempImage = AForge.Imaging.Image.FromFile(imagePath);
        Bitmap image;
        if (tempImage.PixelFormat.ToString().Equals("Format8bppIndexed"))
        {
            image = tempImage;
        }
        else
        {
            image = AForge.Imaging.Filters.Grayscale.CommonAlgorithms.BT709.Apply(tempImage);
        }

        tempImage.Dispose();

        AForge.Imaging.DocumentSkewChecker skewChecker = new AForge.Imaging.DocumentSkewChecker();
        // get documents skew angle
        double angle = skewChecker.GetSkewAngle(image);
        // create rotation filter
        AForge.Imaging.Filters.RotateBilinear rotationFilter = new AForge.Imaging.Filters.RotateBilinear(-angle);
        rotationFilter.FillColor = Color.Black;
        // rotate image applying the filter
        Bitmap rotatedImage = rotationFilter.Apply(image);

        var deskewedImagePath = folderSavePath + filename + "_deskewed.tiff";
        rotatedImage.Save(deskewedImagePath, System.Drawing.Imaging.ImageFormat.Tiff);

        image.Dispose();
        rotatedImage.Dispose();