Add Image.color and PageObject.color.

This commit is contained in:
Andrey Golovizin 2014-09-01 14:53:59 +02:00
parent 44c2cce96e
commit a44091b570
2 changed files with 15 additions and 0 deletions

View file

@ -18,6 +18,7 @@ import itertools
from io import BytesIO from io import BytesIO
import numpy as np import numpy as np
from scipy.stats.mstats import mode
from skimage.io import imread, imsave from skimage.io import imread, imsave
from .utils import cached_property, pairwise from .utils import cached_property, pairwise
@ -162,6 +163,16 @@ class Image(object):
def isspace(self): def isspace(self):
return not is_nonblank(self.bitmap) return not is_nonblank(self.bitmap)
@cached_property
def color(self):
"""Return the most frequent foreground color."""
if self.isspace:
return None
mask3 = np.dstack([~self.bitmap] * 3)
colors = np.ma.MaskedArray(self.data, mask3).reshape(-1, 3)
modes, counts = mode(colors)
return tuple(modes[0])
def serialize(self): def serialize(self):
"""Serialize the image as some hashable object.""" """Serialize the image as some hashable object."""
bitmap = self.data.astype(np.uint8).tostring() bitmap = self.data.astype(np.uint8).tostring()

View file

@ -80,6 +80,10 @@ class PageObject(object):
def ycenter(self): def ycenter(self):
return (self.bottom - self.top) / 2 return (self.bottom - self.top) / 2
@property
def color(self):
return self.image.color
def fits(self, left, top, right, bottom): def fits(self, left, top, right, bottom):
"""Return True if the glyph fits into the given bounding box.""" """Return True if the glyph fits into the given bounding box."""