Home > Software engineering >  Why is my tiled image shifted with pasting into Pillow?
Why is my tiled image shifted with pasting into Pillow?

Time:09-27

I am writing a program where I chop up an image into many sub-tiles, process the tiles, then stitch them together. I am stuck at the stitching part. When I run my code, after the first row the tiles each shift one space over. I am working with 1000x1000 tiles and the image size can be variable. I also get this ugly horizontal padding that I can't figure out how to get rid of. Here is a google drive link to the images: Original Pre-Processed Image Processed Output

An example of the tiles found in the folder recolored_tiles: enter image description here

CodePudding user response:

First off, the code below will create the correct image:

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

Explanation

First off, you should notice, that your tiles aren't 1000x1000. They are all 1008x984 because 18145x16074 can't be divided up into 19 tiles each.

Therefore you will have to put the correct tile width and height in your for loops:

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

Secondly, how python range works, it doesn't run on the last digit. Representation:

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

The output for that would be:

0
1
2
3
4

Therefore the width and height of the original image will have to be minused by 1, because it thinks you have 19 tiles, but there isn't.

Hope this works and what a cool project you're working on :)

  • Related