Fix page orientation and skew with leptonica

 First part of processing scanned images si fix page orientation and possible image skew.

Lets consider following image example:


With leptonica you can fast and easily fix such case.

Code


/*
   fix_page.cpp
*/

#include <leptonica/allheaders.h>
#include <math.h>

int main(int    argc, char **argv) {
    char       *tail;
    char       buf[256];
    PIX        *pix1, *pix2, *pix_bin;
    l_float32  upconf, leftconf, angle, conf;
    l_int32    rotation, pixformat;

    if (argc != 2) {
        fprintf(stderr,"Syntax: %s filein\n", argv[0]);
        return 1;
    }

    if ((pix1 = pixRead(argv[1])) == NULL) {
        printf("pix not made - can not read input file %s", argv[1]);
        return 2;
    }

    /* Find and fix page orientation */
    pix_bin = pixConvertTo1(pix1, 140);
    pixOrientDetect(pix_bin, &upconf, &leftconf, 0, 0);
    printf("upconf: %7.2f; leftconf: %6.2f\n", upconf, leftconf);

    if ((upconf > 1) && fabsf(upconf) > fabsf(leftconf))
        rotation = 0;
    if ((leftconf > 1) && fabsf(leftconf) > fabsf(upconf))
        rotation = 90;
    if ((upconf < -1) && fabsf(upconf) > fabsf(leftconf))
        rotation = 180;
    if ((leftconf < -1) && fabsf(leftconf) > fabsf(upconf))
        rotation = 270;
    pixDestroy(&pix_bin);
    pix1 = pixRotateOrth(pix1, rotation/90);

    /* Find and fix page deskew*/
    pix2 = pixFindSkewAndDeskew(pix1, 2, &angle, &conf);
    printf("Skew angle: %7.2f degrees; %6.2f conf\n", angle, conf);

    /* Save output */
    splitPathAtDirectory(argv[1], NULL, &tail);
    snprintf(buf, sizeof(buf), "fixed_%s", tail);
    printf("Fileout: %s\n", buf);
    pixformat = pixChooseOutputFormat(pix2);
    pixWrite(buf, pix2, pixformat);

    lept_free(tail);
    pixDestroy(&pix1);
    pixDestroy(&pix2);

    return 0;
}
   

Build And Run


  cl fix_page.cpp /If:\win64_llvm\include /link /LIBPATH:f:/win64_llvm/lib leptonica-1.81.0.lib
  fix_page.exe rot_skewed_image.jpg
  
For environment setup, leptonica compilation etc. have a look at Building tesserocr on MS Windows 64bit.

Result

Comments

Popular posts from this blog

Tesseract LSTM training (aka Makefile training)