Home > OS >  How to calculate offsets to show images in a grid evenly?
How to calculate offsets to show images in a grid evenly?

Time:01-09

I have a set of images (frame0.jpg to frame15.jpg) that I want to display in a grid with a yellow background:

from PIL import Image

# yellow background
img = Image.new("RGBA", (1920, 1080), (255, 216, 0, 255))
img_w, img_h = img.size
offset = 20

rows = 4
columns = 4

frame_w = img_w // rows - offset
frame_h = img_h // columns - offset
total_frames = rows * columns

x, y = 15, 15
for i in range(0, total_frames):
    frame_on_the_row = Image.open("frame"   str(i)   ".jpg", "r")
    img.paste(frame_on_the_row, (x, y))
    x  = frame_w   15  # its offset I choose empirically
    if x > img_w - frame_w:
        x = 15
        y  = frame_h   15

img.save("out.png")

Output example:

output

As you can see, yellow border at the bottom and right is slightly wider than the other yellow lines. How can I make them all equally wide?

CodePudding user response:

You calculated the offset with 20. I presume you determined x, y = 15, 15 by subtracting 5 px, to account for the right and bottom lines to be 20 px. However you now set the others to be 15 px.

setting x, y = 16, 16 will result in even lines, all 16 px wide

For a generic calculation you simply have to account for the fact that there is an extra line for the number of image rows / columns.

x_offset = ( offset * rows ) // ( rows 1 )

y_offset = ( offset * columns ) // ( columns 1 )

In words: the total offset, divided by the total numer of lines

  •  Tags:  
  • Related