Skip to content

Commit

Permalink
Merge remote-tracking branch 'bertsky/ocrd-utils-scale'
Browse files Browse the repository at this point in the history
  • Loading branch information
kba committed Sep 20, 2021
2 parents 42446b7 + c9d32aa commit 58ff068
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
19 changes: 19 additions & 0 deletions ocrd/ocrd/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -1051,3 +1051,22 @@ def _rotate(log, name, skew, segment, segment_image, segment_coords, segment_xyw
log, name, segment, segment_image, segment_coords,
op='recropped', **kwargs)
return segment_image, segment_coords, segment_xywh

def _scale(log, name, factor, segment_image, segment_coords, segment_xywh, **kwargs):
# Resize linearly
segment_coords['transform'] = scale_coordinates(
segment_coords['transform'], [factor, factor])
segment_coords['scale'] = segment_coords.setdefault('scale', 1.0) * factor
segment_xywh['w'] *= factor
segment_xywh['h'] *= factor
# resize, if (still) necessary
if not 'scaled' in segment_coords['features']:
log.info("Scaling %s by %.2f", name, factor)
segment_coords['features'] += ',scaled'
# FIXME: validate factor against PAGE-XML attributes
# FIXME: factor should become less precise due to rounding
segment_image = segment_image.resize((int(segment_image.width * factor),
int(segment_image.height * factor)),
# slowest, but highest quality:
Image.BICUBIC)
return segment_image, segment_coords, segment_xywh
18 changes: 18 additions & 0 deletions ocrd_utils/ocrd_utils/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
'polygon_mask',
'rotate_coordinates',
'shift_coordinates',
'scale_coordinates',
'transform_coordinates',
'transpose_coordinates',
'xywh_from_bbox',
Expand Down Expand Up @@ -300,6 +301,23 @@ def shift_coordinates(transform, offset):
shift[1, 2] = offset[1]
return np.dot(shift, transform)

def scale_coordinates(transform, factors):
"""Compose an affine coordinate transformation with a proportional scaling.
Given a numpy array ``transform`` of an existing transformation
matrix in homogeneous (3d) coordinates, and a numpy array
``factors`` of the scaling factors, calculate the affine
coordinate transform corresponding to the composition of both
transformations.
Return a numpy array of the resulting affine transformation matrix.
"""
LOG = getLogger('ocrd_utils.coords.scale_coordinates')
LOG.debug('scaling coordinates by %s', str(factors))
scale = np.eye(3)
scale[0, 0] = factors[0]
scale[1, 1] = factors[1]
return np.dot(scale, transform)

def transform_coordinates(polygon, transform=None):
"""Apply an affine transformation to a set of points.
Augment the 2d numpy array of points ``polygon`` with a an extra
Expand Down

0 comments on commit 58ff068

Please sign in to comment.