不同的数组维度导致合并两张图片失败。

3
尝试合并两张图片以创建一张图片时:

输入图像描述 输入图像描述

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

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

有时会出现以下错误:

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

np.hstack 无法使用时,如何处理数组大小之间的差异以生成图像?

注意:
我使用多张图片,因此最大的图像不一定总是第一张,也不一定总是第二张,最小和最大的顺序可能会相当随机。

1个回答

2

您可以手动添加一个具有您选择的颜色的行/列,以匹配形状。或者,您可以让cv2.resize为您处理调整大小。在此代码中,我展示了如何使用这两种方法。

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)

而且,@GuilhermeCorrea使用shape来分析哪个图像最大,并创建IF ELIF是否是最快和最聪明的方法? - Digital Farmer
例如:if (img1.shape[0] > img2.shape[0]): cv2.resize(img2, img1.shape[:2][::-1]) elif (img2.shape[0] > img1.shape[0]): cv2.resize(img1, img2.shape[:2][::-1]): - Digital Farmer
1
如果大小差异不大,我会选择一个常见的形状将每个人都调整到这个形状。然而,如果形状差异很大,您需要考虑保持图像的纵横比,在这种情况下,我会考虑填充它,您可以尝试通过在每个方向上“平均”填充来保持图像对称。 - Guilherme Correa
我建议使用np.maximum来解决这个问题,因为Python的原生max函数无法按预期工作。 - Guilherme Correa
让我们在聊天中继续这个讨论 - Guilherme Correa
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接