From c7612152ef8096d32d0222abeb5a012bc13a3ac9 Mon Sep 17 00:00:00 2001 From: "James R. Barlow" Date: Sun, 13 Mar 2016 18:17:58 -0700 Subject: [PATCH] leptonica: pillow interop --- ocrmypdf/leptonica.py | 22 ++++++++++++++++++++++ ocrmypdf/lib/compile_leptonica.py | 4 ++++ 2 files changed, 26 insertions(+) diff --git a/ocrmypdf/leptonica.py b/ocrmypdf/leptonica.py index 2f81dc4a..f092e87a 100644 --- a/ocrmypdf/leptonica.py +++ b/ocrmypdf/leptonica.py @@ -197,6 +197,28 @@ class Pix: filename.encode(sys.getfilesystemencoding()), self._pix, jpeg_quality, jpeg_progressive) + def topil(self): + "Returns a PIL.Image version of this Pix" + from PIL import Image + + with LeptonicaErrorTrap(): + pix_swapped = Pix(lept.pixEndianByteSwapNew(self._pix)) + + size = (pix_swapped._pix.wpl * 4, pix_swapped._pix.h) + buf = ffi.buffer(pix_swapped._pix.data, size[0] * size[1]) + + im_raw = Image.frombytes(self.mode, size, buf, 'raw') + + # Leptonica stores images in 32-bit words + # Need to crop the any trailing amount + box = (0, 0, self.width, self.height) + im = im_raw.crop(box) + + return im + + def show(self): + return self.topil().show() + def deskew(self, reduction_factor=0): """Returns the deskewed pix object. diff --git a/ocrmypdf/lib/compile_leptonica.py b/ocrmypdf/lib/compile_leptonica.py index 6f9fde5e..dd8a836f 100644 --- a/ocrmypdf/lib/compile_leptonica.py +++ b/ocrmypdf/lib/compile_leptonica.py @@ -62,6 +62,10 @@ PIX * pixScale ( PIX *pixs, l_float32 scalex, l_float32 scaley ); l_int32 pixFindSkew ( PIX *pixs, l_float32 *pangle, l_float32 *pconf ); l_int32 pixWriteImpliedFormat ( const char *filename, PIX *pix, l_int32 quality, l_int32 progressive ); void pixDestroy ( PIX **ppix ); + +PIX * +pixEndianByteSwapNew(PIX *pixs); + PIX * pixDeskew ( PIX *pixs, l_int32 redsearch ); char * getLeptonicaVersion ( ); l_int32 pixCorrelationBinary(PIX *pix1, PIX *pix2, l_float32 *pval);