Certainly! Below is a complete Python script that creates a seamless pattern image from multiple PNG images of variable sizes. It uses the rectpack library for an irregular bin packing algorithm and allows you to specify whether the images can be rotated or must remain in their original orientation. The script includes a command-line interface (CLI) that takes all the images you want to process and various options.
#!/usr/bin/env python3
import argparse
import sys
from PIL import Image
from rectpack import newPacker, MaxRectsBssf, PackingMode
def wrap_around(image, canvas_size, position):
"""
Wraps the image around the canvas edges to create a seamless tile.
"""
canvas_width, canvas_height = canvas_size
x, y = position
wrapped_images = []
# Calculate overlaps in x and y directions
overlaps = {
'left': max(-x, 0),
'right': max(x + image.width - canvas_width, 0),
'top': max(-y, 0),
'bottom': max(y + image.height - canvas_height, 0),
}
# Original position
wrapped_images.append((image, x % canvas_width, y % canvas_height))
# Horizontal wrap
if overlaps['left'] > 0 or overlaps['right'] > 0:
new_x = (x + canvas_width) % canvas_width - canvas_width
wrapped_images.append((image, new_x, y % canvas_height))
# Vertical wrap
if overlaps['top'] > 0 or overlaps['bottom'] > 0:
new_y = (y + canvas_height) % canvas_height - canvas_height
wrapped_images.append((image, x % canvas_width, new_y))
# Diagonal wrap
if (overlaps['left'] > 0 or overlaps['right'] > 0) and (overlaps['top'] > 0 or overlaps['bottom'] > 0):
new_x = (x + canvas_width) % canvas_width - canvas_width
new_y = (y + canvas_height) % canvas_height - canvas_height
wrapped_images.append((image, new_x, new_y))
return wrapped_images
def create_seamless_pattern(images, canvas_size, allow_rotation):
"""
Creates a seamless pattern from the given images.
"""
canvas_width, canvas_height = canvas_size
# Prepare rectangles for packing
rects = []
img_dict = {}
for idx, img in enumerate(images):
w, h = img.size
rects.append((w, h, idx))
img_dict[idx] = img
# Initialize packer
packer = newPacker(mode=PackingMode.Offline, rotation=allow_rotation, pack_algo=MaxRectsBssf)
packer.add_bin(canvas_width, canvas_height)
# Add rectangles to packer
for r in rects:
packer.add_rect(*r)
# Pack the rectangles
packer.pack()
# Create canvas
canvas = Image.new('RGBA', (canvas_width, canvas_height), (0, 0, 0, 0))
# Place images on canvas and handle wrapping
for abin in packer:
for rect in abin:
x, y, w, h, rid = rect.x, rect.y, rect.width, rect.height, rect.rid
img = img_dict[rid]
# Rotate image if it was rotated in packing
if allow_rotation and ((img.width != w) or (img.height != h)):
img = img.rotate(90, expand=True)
# Paste the image onto the canvas
wrapped_positions = wrap_around(img, (canvas_width, canvas_height), (x, y))
for img_part, pos_x, pos_y in wrapped_positions:
canvas.alpha_composite(img_part, dest=(int(pos_x), int(pos_y)))
return canvas
def main():
parser = argparse.ArgumentParser(description='Create a seamless pattern image from multiple PNG images.')
parser.add_argument('images', nargs='+', help='Input PNG image files.')
parser.add_argument('-o', '--output', default='seamless_pattern.png', help='Output image file.')
parser.add_argument('-s', '--size', type=int, nargs=2, metavar=('WIDTH', 'HEIGHT'), default=None,
help='Size of the output image (width height).')
parser.add_argument('-r', '--allow-rotation', action='store_true', help='Allow images to be rotated.')
args = parser.parse_args()
# Load images
images = []
for img_file in args.images:
try:
img = Image.open(img_file).convert('RGBA')
images.append(img)
except Exception as e:
print(f"Error loading image {img_file}: {e}", file=sys.stderr)
if not images:
print("No images loaded. Exiting.", file=sys.stderr)
sys.exit(1)
# Determine canvas size
if args.size:
canvas_size = tuple(args.size)
else:
# Calculate canvas size based on total area of images
total_area = sum(img.width * img.height for img in images)
canvas_side = int(total_area ** 0.5)
canvas_size = (canvas_side, canvas_side)
# Create seamless pattern
pattern = create_seamless_pattern(images, canvas_size, args.allow_rotation)
# Save the output image
pattern.save(args.output)
print(f"Seamless pattern saved to {args.output}")
if __name__ == "__main__":
main()
How to Use the Script
-
Install Dependencies
Ensure you have the required Python packages installed:
pip install Pillow rectpack
-
Save the Script
Save the script above to a file, for example, seamless_pattern.py.
-
Make the Script Executable (Optional for Unix/Linux/Mac)
chmod +x seamless_pattern.py
-
Run the Script
Use the CLI to create a seamless pattern. Here's the basic usage:
python seamless_pattern.py image1.png image2.png image3.png -o output.png
Options:
-o OUTPUT, --output OUTPUT: Specify the output image file. Defaults to seamless_pattern.png.
-s WIDTH HEIGHT, --size WIDTH HEIGHT: Specify the size of the output image.
-r, --allow-rotation: Allow the images to be rotated during packing.
Example with All Options:
python seamless_pattern.py images/*.png -o pattern.png -s 1024 1024 -r
This command takes all PNG images in the images directory, allows them to be rotated, packs them into a 1024x1024 image, and saves the result as pattern.png.
Explanation of the Script
Notes
-
The script assumes all input images are in PNG format with transparency (alpha channel). If your images are in a different format or do not have transparency, you may need to adjust the image loading and conversion parts.
-
The canvas size defaults to a square where the side length is the square root of the total area of all images if not specified.
-
Allowing rotation (-r flag) can lead to a more efficient packing and varied pattern but may not be suitable for all images (e.g., text or directional graphics).
-
The wrapping logic ensures that any part of an image that goes over the canvas edge is wrapped around to the opposite side, making the final pattern seamless when tiled.
-
The script uses the alpha_composite method to handle images with transparency properly.
Feel free to adjust and extend the script to suit your specific needs!