Skip to content

Commit

Permalink
Merge pull request #159 from cisocrgroup/xywh-unordered
Browse files Browse the repository at this point in the history
Handle any number of unordered points
  • Loading branch information
kba authored Aug 15, 2018
2 parents 0e875c6 + fe93077 commit a97aca6
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
24 changes: 19 additions & 5 deletions ocrd/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,26 @@ def xywh_from_points(points):
"""
Constructs an dict representing a rectangle with keys x, y, w, h
"""
[tl, tr, br] = [[int(p) for p in pair.split(',')] for pair in points.split(' ')[:3]]
xys = [[int(p) for p in pair.split(',')] for pair in points.split(' ')]
minx = sys.maxsize
miny = sys.maxsize
maxx = 0
maxy = 0
for xy in xys:
if xy[0] < minx:
minx = xy[0]
if xy[0] > maxx:
maxx = xy[0]
if xy[1] < miny:
miny = xy[1]
if xy[1] > maxy:
maxy = xy[1]

return {
'x': tl[0],
'y': tl[1],
'w': tr[0] - tl[0],
'h': br[1] - tr[1],
'x': minx,
'y': miny,
'w': maxx - minx,
'h': maxy - miny,
}

def polygon_from_points(points):
Expand Down
5 changes: 5 additions & 0 deletions test/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ def test_xywh_from_points(self):
xywh_from_points('100,100 200,100 200,200 100,200'),
{'x': 100, 'y': 100, 'w': 100, 'h': 100})

def test_xywh_from_points_unordered(self):
self.assertEqual(
xywh_from_points('500,500 100,100 200,100 200,200 100,200'),
{'x': 100, 'y': 100, 'w': 400, 'h': 400})

def test_polygon_from_points(self):
self.assertEqual(
polygon_from_points('100,100 200,100 200,200 100,200'),
Expand Down

0 comments on commit a97aca6

Please sign in to comment.