Skip to content

Instantly share code, notes, and snippets.

@kastnerp
Created July 31, 2022 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kastnerp/3c9c96028490fce661723138d33c9509 to your computer and use it in GitHub Desktop.
Save kastnerp/3c9c96028490fce661723138d33c9509 to your computer and use it in GitHub Desktop.
Stack images with black and white fill color
# inspired by this post https://stackoverflow.com/a/65677170/4876516 by https://stackoverflow.com/users/334346/oleg
import numpy as np
import cv2 as cv
def stack_images(img_list, how, fill_color):
max_height, max_width = 0, 0
padding = 200 # 200
total_height, total_width = padding, padding # padding
mult_by = 0 if fill_color == 'black' else 255
for image in img_list:
img_height, img_width = image.shape[0], image.shape[1]
if img_height > max_height:
max_height = img_height
total_width += img_width
if img_width > max_width:
max_width = img_width
total_height += img_height
final_image = None
if how == 'ver':
# create a new array with a size large enough to contain all the images with white pixels
final_image = np.ones((total_height, max_width, 3), dtype=np.uint8)*mult_by
curr_y = 0 # keep track of where your current image was last placed in the y coordinate
for curr_image in img_list:
img_height, img_width = curr_image.shape[0], curr_image.shape[1]
curr_height = curr_y + img_height
calc_width = max_width - img_width
# add an image to the final array and increment the y coordinate
curr_image = np.hstack((curr_image, np.ones((img_height, calc_width , 3))*mult_by)) # with white pixels
# place current image
final_image[curr_y: curr_height, :, :] = curr_image
curr_y += img_height
elif how == 'hor':
# create a new array with a size large enough to contain all the images with white pixels
final_image = np.ones((max_height,total_width, 3), dtype=np.uint8)*mult_by
curr_x = 0 # keep track of where your current image was last placed in the x coordinate
for curr_image in img_list:
img_height, img_width = curr_image.shape[0], curr_image.shape[1]
curr_width = curr_x + img_width
calc_height = max_height - img_height
# add an image to the final array and increment the y coordinate
curr_image = np.vstack((curr_image, np.ones((calc_height, img_width, 3))*mult_by)) # with white pixels
# place current image
final_image[:, curr_x: curr_width,:] = curr_image
curr_x += img_width
return final_image
# cv.imwrite("test.png",stack_images([cv.imread("2ScreenTop.png"),cv.imread("2ScreenParallel.png")], 'hor', 'white'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment