Friday, July 29, 2022

[FIXED] How to stack all images in a directory vertically into one long image

Issue

I've been trying to merge images together into one long image. The images are all in one folder and have the same file name format group1.X.jpg with X being a number, starting at 0. I've tried using img.paste to merge the images together. This is basically what I've been trying:

    img1 = Image.open(directory + filePrefix + str(fileFirst) + fileExtension)
    w, h = img1.size
    h = h * fileCount
    img = Image.new("RGB", (w, h))
    tmpImg = img.load()
    console.log("Setup Complete")
    number = 0
    for number in track(range(fileCount - 1)):
        imgPaste = Image.open(dir + prefix + str(number) + extension)
        if not number >= fileCount:
            Image.Image.paste(tmpImg, imgPaste, (0, h * (number + 1)))
        number += 1
    img.save(file)

stitch(directory, filePrefix, fileExtension)

The above code, when ran, outputs the following:

Working... ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━   0% -:--:--
Traceback (most recent call last):
  File "c:\Users\marcus\Desktop\Stuff\Files\code\webtoonstitcher.py", line 36, in <module>
    stitch(directory, filePrefix, fileExtension)
  File "c:\Users\marcus\Desktop\Stuff\Files\code\webtoonstitcher.py", line 32, in stitch
    Image.Image.paste(tmpImg, imgPaste, (0, h * (number + 1)))
  File "C:\Users\marcus\AppData\Roaming\Python\Python310\site-packages\PIL\Image.py", line 1619, in paste
    if self.mode != im.mode:
AttributeError: 'PixelAccess' object has no attribute 'mode'```

Solution

You can get list of all images using glob and then just iterate through that list:

import glob
from PIL import Image


def stitch(directory, file_prefix, file_extension):
    files = glob.glob(directory + f'{file_prefix}*.{file_extension}')
    images = [Image.open(file) for file in files]
    background_width = max([image.width for image in images])
    background_height = sum([image.height for image in images])
    background = Image.new('RGBA', (background_width, background_height), (255, 255, 255, 255))
    y = 0
    for image in images:
        background.paste(image, (0, y))
        y += image.height
    background.save('image.png')


stitch('', 'group1', 'png')

Sample output:

Fruits



Answered By - Alderven
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.