diff --git a/src/ocrmypdf/leptonica.py b/src/ocrmypdf/leptonica.py index 6d382795..ab26f750 100644 --- a/src/ocrmypdf/leptonica.py +++ b/src/ocrmypdf/leptonica.py @@ -139,6 +139,8 @@ class Pix: """ def __init__(self, pix): + if not pix: + raise ValueError('NULL box') self._pix = ffi.gc(pix, Pix._pix_destroy) def __repr__(self): @@ -403,8 +405,6 @@ class Pix: display, pdfdir)) - print(repr(cropbox)) - cropped_pix = lept.pixClipRectangle( self._pix, cropbox._box, @@ -549,8 +549,11 @@ class Box: """ def __init__(self, box): + if not box: + raise ValueError('NULL box') self._box = ffi.gc(box, Box._box_destroy) + def __repr__(self): if self._box: return ''.format( @@ -583,6 +586,8 @@ class BoxArray: """Wrapper around Leptonica's BOXA (Array of BOX) objects.""" def __init__(self, boxa): + if not boxa: + raise ValueError('NULL boxa') self._boxa = ffi.gc(boxa, BoxArray._boxa_destroy) def __repr__(self): diff --git a/tests/test_lept.py b/tests/test_lept.py index 9c03a6b8..38efebc2 100644 --- a/tests/test_lept.py +++ b/tests/test_lept.py @@ -18,8 +18,12 @@ import os import shutil -import pytest import sys +from pickle import dumps, loads + +import pytest +from PIL import Image, ImageChops + import ocrmypdf.leptonica as lept @@ -28,3 +32,49 @@ def test_colormap_backgroundnorm(resources): # can handle that case pix = lept.Pix.open(resources / 'baiona_colormapped.png') pix.background_norm() + + +@pytest.fixture +def crom_pix(resources): + pix = lept.Pix.open(resources / 'crom.png') + im = Image.open(resources / 'crom.png') + return pix, im + + +def test_pix_basic(crom_pix): + pix, im = crom_pix + + assert pix.width == im.width + assert pix.height == im.height + assert pix.mode == im.mode + + +def test_pil_conversion(crom_pix): + pix, im = crom_pix + + # Check for pixel perfect + assert ImageChops.difference(pix.topil(), im).getbbox() is None + + +def test_pix_otsu(crom_pix): + pix, _ = crom_pix + im1bpp = pix.otsu_adaptive_threshold() + assert im1bpp.mode == '1' + + +def test_crop(resources): + pix = lept.Pix.open(resources / 'linn.png') + foreground = pix.crop_to_foreground() + assert foreground.width < pix.width + + +def test_clean_bg(crom_pix): + pix, _ = crom_pix + imbg = pix.clean_background_to_white() + + +def test_pickle(crom_pix): + pix, _ = crom_pix + pickled = dumps(pix) + pix2 = loads(pickled) + assert pix.mode == pix2.mode