【问题标题】:How to calculate offsets to show images in a grid evenly?如何计算偏移量以在网格中均匀显示图像?
【发布时间】:2022-01-08 10:17:12
【问题描述】:

我有一组图像(frame0.jpgframe15.jpg),我想在黄色背景的网格中显示:

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")

输出示例:

如您所见,底部和右侧的黄色边框比其他黄线略宽。我怎样才能使它们都一样宽?

【问题讨论】:

    标签: python math


    【解决方案1】:

    您用 20 计算了偏移量。我假设您通过减去 5 px 来确定@​​987654321@,以说明右下线为 20 px。但是,您现在将其他设置为 15 像素。

    设置 x, y = 16, 16 将产生偶数行,所有 16 像素宽

    对于一般计算,您只需考虑图像行/列数有一个额外的行。

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

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

    换句话说:总偏移量除以总行数

    【讨论】:

    • 谢谢。但是有没有可能推导出一个通用的计算公式?
    • 我现在正在尝试这样做:offset_on_grid = int(offset * 4 / 5) 它给了我16。但是现在我不能让这个公式对任意数量的帧都通用。
    • 更新了答案,你已经知道答案了
    猜你喜欢
    • 1970-01-01
    • 2020-11-04
    • 2013-04-03
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多