【问题标题】:Why is my tiled image shifted with pasting into Pillow?为什么我的平铺图像在粘贴到 Pillow 时会发生偏移?
【发布时间】:2021-11-19 03:45:42
【问题描述】:

我正在编写一个程序,将图像分割成许多子图块,处理图块,然后将它们缝合在一起。我卡在缝合部分。当我运行我的代码时,在第一行之后,每个瓷砖都会移动一个空格。我正在使用 1000x1000 的图块,图像大小可以是可变的。我也得到了这个丑陋的水平填充,我不知道如何摆脱它。 这是图片的谷歌驱动器链接: https://drive.google.com/drive/folders/1HqRl29YlWUrsYoZP88TAztJe9uwgP5PS?usp=sharing

基于 cmets 的说明

我将原始的黑白图像裁剪成 1000 像素 x 1000 像素的黑白图块。然后对这些图块重新着色,用与密度热图对应的颜色替换白色。然后将重新着色的图块保存到该文件夹​​中。我包含的图片是我试图拼凑起来的彩色瓷砖之一。当拼凑在一起时,它应该是黑白图像的相同形状但多色版本

from PIL import Image
import os


stitched_image = Image.new('RGB', (large_image.width, large_image.height))
image_list = os.listdir('recolored_tiles')
current_tile = 0

for i in range(0, large_image.height, 1000):
    for j in range(0, large_image.width, 1000):
        p = Image.open(f'recolored_tiles/{image_list[current_tile]}')
        stitched_image.paste(p, (j, i), 0)
        current_tile += 1

stitched_image.save('test.png')

我附上了我在图块中处理的原始图像和输出图像的当前状态:

文件夹 recolored_tiles 中的图块示例:

【问题讨论】:

    标签: python image python-imaging-library


    【解决方案1】:

    首先,下面的代码将创建正确的图像:

    from PIL import Image
    import os
    
    stitched_image = Image.new('RGB', (original_image_width, original_image_height))
    image_list = os.listdir('recolored_tiles')
    current_tile = 0
    
    for y in range(0, original_image_height - 1, 894):
        for x in range(0, original_image_width - 1, 1008):
            tile_image = Image.open(f'recolored_tiles/{image_list[current_tile]}')
            print("x: {0}     y: {1}".format(x, y))
            stitched_image.paste(tile_image, (x, y), 0)
            current_tile += 1
    
    stitched_image.save('test.png')
    

    说明

    首先,您应该注意到,您的图块不是 1000x1000。它们都是 1008x984,因为 18145x16074 不能分成 19 个 1000x1000 的瓦片。

    因此,您必须在 for 循环中放置正确的 tile 宽度和高度:

    for y in range(0, 16074, INSERT CURRECT RECOLORED_TILE HEIGHT HERE):
        for x in range(0, 18145, INSERT CURRECT RECOLORED_TILE WIDTH HERE):
    

    其次,python 范围是如何工作的,它不会在最后一位上运行。表示:

    for i in range(0,5):
        print(i)
    

    输出将是:

    0
    1
    2
    3
    4
    

    因此原始图像的宽度和高度必须减去 1,因为它认为您有 19 个图块,但实际上没有。

    希望这行得通,你正在从事的项目多么酷:)

    【讨论】:

    • 非常感谢!我应该检查瓷砖尺寸 - 我使用另一个库生成它并且有一个错误!
    猜你喜欢
    • 2020-12-12
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多