I'm learning how to use PIL and I want to concatenate 4 separate images into a grid (all 256x256
PNG). Using PIL (and optionally NumPy). With several examples I've found, I am already able to concatenate images by stacking them all horizontally/vertically or as a grid when I have exactly 4 images.
What I want to be able to do now is to combine up to 4 images into a grid, i.e. passing in anywhere between 1 and 4 images into a function.
Use cases:
My first thought was to split the image list into pairs, concatenate each horizontally, then concatenate the two results vertically, but that feels inefficient.
EDIT: I've gotten this working as I described above using OpenCV because it was easier to work with than PIL. Here's my code:
images = ["images/img1.png", "images/img2.png", "images/img3.png", "images/img4.png"]
def combine(images):
if len(images) == 1:
img1 = cv2.imread(images[0])
return cv2.imwrite("Combined.png", img1)
elif len(images) == 2:
img1 = cv2.imread(images[0])
img2 = cv2.imread(images[1])
combined_image = cv2.hconcat([img1, img2])
return cv2.imwrite("Combined.png", combined_image)
elif len(images) == 3:
img1 = cv2.imread(images[0])
img2 = cv2.imread(images[1])
img3 = cv2.imread(images[2])
img4 = cv2.imread("images/Blank.png") # Just a transparent PNG
image_row_1 = cv2.hconcat([img1, img2])
image_row_2 = cv2.hconcat([img3, img4])
combined_image = cv2.vconcat([image_row_1, image_row_2])
return cv2.imwrite("Combined.png", combined_image)
elif len(images) == 4:
img1 = cv2.imread(images[0])
img2 = cv2.imread(images[1])
img3 = cv2.imread(images[2])
img4 = cv2.imread(images[3])
image_row_1 = cv2.hconcat([img1, img2])
image_row_2 = cv2.hconcat([img3, img4])
combined_image = cv2.vconcat([image_row_1, image_row_2])
return cv2.imwrite("Combined.png", combined_image)
combine(images)
Is there a better way?