Home > Blockchain >  Different array dimensions causing failure to merge two images into one
Different array dimensions causing failure to merge two images into one

Time:04-03

enter image description here enter image description here

When trying to join two images to create one:

img3 = imread('image_home.png')
img4 = imread('image_away.png')

result = np.hstack((img3,img4))
imwrite('Home_vs_Away.png', result)

This error sometimes appears:

all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 192 and the array at index 1 has size 191

How should I proceed to generate the image when there is this difference in array size when np.hstack does not work?

Note:
I use several images, so not always the largest image is the first and not always the largest is the second, it can be quite random which is the smallest or largest between the two.

CodePudding user response:

You can manually add a row/column with a color of your choice to match the shapes. Or you can simply let cv2.resize handle the resizing for you. In this code I show how to use both methods.

import numpy as np
import cv2

img1 = cv2.imread("image_home.png")
img2 = cv2.imread("image_away.png")

# Method 1 (add a column and a row to the smallest image)
padded_img = np.ones(img1.shape, dtype="uint8")
color = np.array(img2[-1, -1])  # take the border color
padded_img[:-1, :-1, :] = img2
padded_img[-1, :, :] = color
padded_img[:, -1, :] = color

# Method 2 (let OpenCV handle the resizing)
padded_img = cv2.resize(img2, img1.shape[:2][::-1])

result = np.hstack((img1, padded_img))
cv2.imwrite("Home_vs_Away.png", result)
  • Related