Skip to content

Commit

Permalink
feat(visualize): add option to not trust the box
Browse files Browse the repository at this point in the history
  • Loading branch information
AmitMY committed Jan 31, 2024
1 parent 086a631 commit 0fdc36f
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
16 changes: 16 additions & 0 deletions signwriting/visualizer/test_visualize.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,22 @@ def test_image_invalid_fsw(self):

assert_array_equal(np.array(image), np.array(reference_image))

def test_image_small_box(self):
fsw = "M500x500S2ff00407x501S1ce20436x535S2e300413x552S22b04418x565S36520420x523"

with self.assertRaises(ValueError):
signwriting_to_image(fsw)

def test_image_small_box_is_corrected(self):
fsw = "M500x500S2ff00407x501S1ce20436x535S2e300413x552S22b04418x565S36520420x523"

image = signwriting_to_image(fsw, trust_box=False)

assets_path = Path(__file__).parent / "test_assets" / f"{fsw}.png"
reference_image = Image.open(assets_path)

assert_array_equal(np.array(image), np.array(reference_image))


if __name__ == '__main__':
unittest.main()
21 changes: 19 additions & 2 deletions signwriting/visualizer/visualize.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,38 @@


@lru_cache(maxsize=None)
def get_font(font_name: str):
def get_font(font_name: str) -> ImageFont.FreeTypeFont:
font_path = Path(__file__).parent / f'{font_name}.ttf'
return ImageFont.truetype(str(font_path), 30)


def get_symbol_size(symbol: str):
font = get_font('SuttonSignWritingLine')
line_id = symbol_line(key2id(symbol))
left, top, right, bottom = font.getbbox(line_id)
return right - left, bottom - top


# pylint: disable=too-many-locals
def signwriting_to_image(fsw: str, antialiasing=True) -> Image:
def signwriting_to_image(fsw: str, antialiasing=True, trust_box=True) -> Image:
sign = fsw_to_sign(fsw)
if len(sign['symbols']) == 0:
return Image.new('RGBA', (1, 1), (0, 0, 0, 0))

positions = [s["position"] for s in sign['symbols']]
min_x = min(positions, key=lambda p: p[0])[0]
min_y = min(positions, key=lambda p: p[1])[1]

max_x, max_y, = sign["box"]["position"]

if not trust_box:
max_x, max_y = 0, 0
for symbol in sign['symbols']:
symbol_x, symbol_y = symbol["position"]
symbol_width, symbol_height = get_symbol_size(symbol["symbol"])
max_x = max(max_x, symbol_x + symbol_width)
max_y = max(max_y, symbol_y + symbol_height)

img = Image.new('RGBA', (max_x - min_x, max_y - min_y), (255, 255, 255, 0))
draw = ImageDraw.Draw(img)
if not antialiasing:
Expand Down

0 comments on commit 0fdc36f

Please sign in to comment.