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'```
CodePudding user response:
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:
CodePudding user response:
I think the issue is here:
h = h * fileCount
img = Image.new("RGB", (w, h))
You should delete the first line and change the second line to:
img = Image.new("RGB", (w, h * fileCount))
Otherwise your h
will be far too big when you use it later to calculate the offset for paste()
.