mchd
mchd

Reputation: 3163

Pillow does not draw the correct bounding box given the dimensions

I am trying to draw bounding boxes around logos that I am pasting on images. However, PIL is not drawing them correctly despite that I am supplying the right coordinates. The logos are transparent so I want to get their topright xy and use their width, height to draw the box. This is my result:

enter image description here

Here is my code:

brand_logo = Image.open('/content/logos/' + logo, 'r').convert('RGBA')
logo_width, logo_height = brand_logo.size

gameplay = Image.open('/content/composite-testing/' + gp, 'r').convert('RGBA')
gameplay_width, gameplay_height = gameplay.size

logo_x = math.floor((gameplay_width/2) - (logo_width/2))
logo_y = math.floor((gameplay_height/2) - (logo_height/2))

text_img = Image.new('RGBA', (gameplay_width, gameplay_height), (0, 0, 0, 0))

text_img.paste(gameplay, (0, 0))
text_img.paste(brand_logo, (logo_x, logo_y), mask = brand_logo)
img_draw = ImageDraw.Draw(text_img)

# This is the code that draws the red bounding box
img_draw.rectangle(((logo_x, logo_y),(logo_width, logo_height)), outline='Red')
text_img.save('/content/result/' + epoch + '_' + str(counter) + '.png' , format="png")

Upvotes: 0

Views: 2856

Answers (1)

Glenn Gribble
Glenn Gribble

Reputation: 390

The second pair of numbers are coordinates, not width/height. Use:

img_draw.rectangle(((logo_x, logo_y),(logo_x+logo_width, logo_y+logo_height)), outline='Red')

Upvotes: 3

Related Questions