Исправление искажения перспективы изображения документа в .NET

Категория: Imaging.NET

8 декабря 2023

Сейчас очень часто изображение документа фотографируют с помощью камеры смартфона. Достаточно сложно идеально разместить камеру смартфона над фотографируемым документом, поэтому практически все получаемые изображения повернуты и имеют пространственное искажение.

Вот примеры повернутых изображений документов, которые получены с помощью камеры смартфона:
Изобрежние документа полученное с камеры смартфона
Изобрежние документа полученное с камеры смартфона


Практически все системы работы с документами требуют не повернутое и не искаженное изображение документа, поэтому возникает задача преобразовать повернутое и искаженное изображение в не повернутое и не искаженное изображение.
В VintaSoft Document Cleanup .NET Plug-in 7.3 (VintaSoft Imaging .NET SDK 12.3) была добавлена команда для исправления искажения перспективы изображения документа.

Команда Vintasoft.Imaging.ImageProcessing.Document.DocumentPerspectiveCorrectionCommand может быть использована для решения следующих задач:

Замечание: Команда Vintasoft.Imaging.ImageProcessing.Document.DocumentPerspectiveCorrectionCommand возвращает хороший результат, если граница изображения документа имеет приемлемую контрастность, т.е. граница документа легко различима человеческим глазом.

Вот пример выровненного изображения документа после применения команды Vintasoft.Imaging.ImageProcessing.Document.DocumentPerspectiveCorrectionCommand:
Исправленное изображение документа обработанное используя DocumentPerspectiveCorrectionCommand
Исправленное изображение документа обработанное используя DocumentPerspectiveCorrectionCommand



Вот C# код, который демонстрирует как можно исправить искажение перспективы для изображения документа:
/// <summary>
/// Corrects perspective distortion of document image.
/// </summary>
/// <param name="sourceFile">Source image file.</param>
/// <param name="resultFile">Result image file.</param>
public void ApplyPerspectiveCorrection(string sourceFile, string resultFile)
{
    using (Vintasoft.Imaging.VintasoftImage image =
        new Vintasoft.Imaging.VintasoftImage(sourceFile))
    {
        // create the perspective correction command
        Vintasoft.Imaging.ImageProcessing.Document.DocumentPerspectiveCorrectionCommand command =
            new Vintasoft.Imaging.ImageProcessing.Document.DocumentPerspectiveCorrectionCommand();

        // apply the perspective correction to a document image
        command.ExecuteInPlace(image);

        // save the result image to a file
        image.Save(resultFile);
    }
}


Если изначально известно соотношение сторон изображения документа, то соотношение сторон нужно указать с помощью свойства Vintasoft.Imaging.ImageProcessing.Document.DocumentPerspectiveCorrectionCommand.DocumentAspectRatio.
Вот C# код, который демонстрирует как можно исправить искажение перспективы для изображения документа листа формата A4:
/// <summary>
/// Corrects perspective distortion of A4 document image.
/// </summary>
/// <param name="sourceFile">Source file.</param>
/// <param name="resultFile">Result file.</param>
public void ApplyPerspectiveCorrectionA4Paper(string sourceFile, string resultFile)
{
    using (Vintasoft.Imaging.VintasoftImage image =
        new Vintasoft.Imaging.VintasoftImage(sourceFile))
    {
        // create the perspective correction command
        Vintasoft.Imaging.ImageProcessing.Document.DocumentPerspectiveCorrectionCommand command =
            new Vintasoft.Imaging.ImageProcessing.Document.DocumentPerspectiveCorrectionCommand();

        // set the document aspect ratio to the aspect ratio of the A4 paper
        Vintasoft.Imaging.ImageSize paperSizeA4 = Vintasoft.Imaging.ImageSize.FromPaperKind(Vintasoft.Imaging.PaperSizeKind.A4);
        command.DocumentAspectRatio = paperSizeA4.WidthInDip / paperSizeA4.HeightInDip;

        // apply the perspective correction to a document image
        command.ExecuteInPlace(image);

        // save the result image to a file
        image.Save(resultFile);
    }
}


Команда Vintasoft.Imaging.ImageProcessing.Document.DocumentPerspectiveCorrectionCommand использует команду Vintasoft.Imaging.ImageProcessing.Transforms.QuadrilateralWarpCommand для выполнения преобразования исправления перспективы. Если вам известны угловые точки искаженного изображения, то вы можете воспользоваться командой Vintasoft.Imaging.ImageProcessing.Transforms.QuadrilateralWarpCommand для выполнения обратного преобразования перспективы.
Вот C# код, который демонстрирует как можно исправить искажение перспективы для изображения документа, если известны угловые точки искаженного изображения:
/// <summary>
/// Corrects perspective distortion of document image.
/// </summary>
/// <param name="sourceFile">Source image file.</param>
/// <param name="resultFile">Result image file.</param>
/// <param name="documentImagePoints">An array of four points, which define the corner points of document image.
/// Points should be set in the following order: 0 - top-left, 1 - top-right,
/// 2 - bottom-left, 3 - bottom-right.</param>
public void ApplyQuadrilateralUnwarp(string sourceFile, string resultFile, System.Drawing.PointF[] documentImagePoints)
{
    using (Vintasoft.Imaging.VintasoftImage image =
        new Vintasoft.Imaging.VintasoftImage(sourceFile))
    {
        // create the perspective correction command
        Vintasoft.Imaging.ImageProcessing.Transforms.QuadrilateralWarpCommand command =
            new Vintasoft.Imaging.ImageProcessing.Transforms.QuadrilateralWarpCommand();

        // specify that command must use invert transform (command must work as unwarp command)
        command.IsInverseTransform = true;

        // set the corner points of document image
        command.DestinationPoints = documentImagePoints;

        // apply perspective correction to a document image
        command.ExecuteInPlace(image);

        // save the result image to a file
        image.Save(resultFile);
    }
}