代码之家  ›  专栏  ›  技术社区  ›  Digital Farmer

不同的数组维度导致无法将两个图像合并为一个

  •  2
  • Digital Farmer  · 技术社区  · 4 年前

    enter image description here enter image description here

    尝试连接两个图像以创建一个图像时:

    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 回复  |  直到 4 年前
        1
  •  1
  •   Guilherme Correa    4 年前

    您可以手动添加一行/一列,并选择与形状匹配的颜色。或者你可以简单地让cv2。调整大小为您调整大小。在这段代码中,我将演示如何使用这两种方法。

    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)