Skip to content

Character bounding boxes and negative offsetx #4789

@indigoviolet

Description

@indigoviolet

What did you do?

I'm trying to get character level bounding boxes for some text I'm generating, following #3921, and @nulano 's comment, this stackoverflow answer etc. Also tagging #4724 in the hope that this issue will be addressed by it.

def test_bbox(font, txt):
    img = Image.new(mode='RGB', size=(300,100), color='white')
    draw = ImageDraw.Draw(img)
    xref, yref = 50, 5
    draw.text((xref, yref), txt, font=font, fill='black')
    for i, c in enumerate(txt):
        wd0, ht0 = font.getsize(txt[:i+1])
        (wd, ht), (offsetx, offsety) = font.font.getsize(txt[:i+1])
        cmask_wd, cmask_ht = font.getmask(c).size
        char_wd, char_ht = font.getsize(c)
        
        x2, y2 = wd0, char_ht
        x1, y1 = x2 - cmask_wd, y2 - cmask_ht
        draw.rectangle((x1 + xref, y1 + yref, x2 + xref, y2 + yref), fill=None, outline='red', width=1)
        draw.rectangle((x1 + offsetx + xref, y1 + yref, x2 + offsetx + xref, y2 + yref), fill=None, outline='green', width=1)
    return img
italic_font = ImageFont.truetype('fonts/google/fonts-master/ofl/baskervville/Baskervville-Italic.ttf', 60, layout_engine=ImageFont.LAYOUT_BASIC) 

# show_grid just uses matplotlib ax.imshow to display the image
show_grid(test_bbox(italic_font, 'fa'))
show_grid(test_bbox(italic_font, 'af'))

image

What did you expect to happen?

I expected the red bounding box to encompass the a in the first image (fa).

What actually happened?

  1. It was shifted to the right.

  2. Also, while flailing around, I realized that the green bounding box, which is created by an additional offsetx shift, does appear to encompass the a. I don't understand why this would be, but it might just be coincidence.

  3. Neither of these completely bound the a on the top edge. Why would that be?

What are your OS, Python and Pillow versions?

  • OS: Ubuntu 18.04
  • Python: 3.8.1
  • Pillow: 7.1.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions