功能:给定任意大小的两个图片(矩阵),水平连接成一个图片(矩阵)。高度不同时,使用黑色作为高度较小者的边缘填充,图片垂直居中。
import cv2
import numpy as np
def image_join(image1, image2):
"""
水平合并两个opencv图像矩阵为一个图像矩阵
:param image1:
:param image2:
:return:
"""
h1, w1 = image1.shape[0:2]
h2, w2 = image2.shape[0:2]
if h1 > h2:
margin_height = h1 - h2
if margin_height % 2 == 1:
margin_top = int(margin_height / 2)
margin_bottom = margin_top + 1
else:
margin_top = margin_bottom = int((h1 - h2)/2)
image2 = cv2.copyMakeBorder(image2, margin_top, margin_bottom, 0, 0, cv2.BORDER_CONSTANT, value=[0, 0, 0])
elif h2 > h1:
margin_height = h2 - h1
if margin_height % 2 == 1:
margin_top = int(margin_height / 2)
margin_bottom = margin_top + 1
else:
margin_top = margin_bottom = int(margin_height / 2)
image1 = cv2.copyMakeBorder(image1, margin_top, margin_bottom, 0, 0, cv2.BORDER_CONSTANT, value=[0, 0, 0])
return np.concatenate((image1, image2), axis=1)
顺便介绍一下numpy的concatenate()函数:
def concatenate(arrays, axis=None, out=None):
"""
concatenate((a1, a2, ...), axis=0, out=None)
Join a sequence of arrays along an existing axis.
Parameters
----------
a1, a2, ... : sequence of array_like
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int, optional
The axis along which the arrays will be joined. If axis is None,
arrays are flattened before use. Default is 0.
out : ndarray, optional
If provided, the destination to place the result. The shape must be
correct, matching that of what concatenate would have returned if no
out argument were specified.
Returns
-------
res : ndarray
The concatenated array.
"""
参数arrays:可接收一个矩阵列表,函数会把说有矩阵依次连接。
参数axis:连接方向(轴向),axis=0时,垂直连接;axis=1时,水平连接;axis=None时,扁平输出,即把二维矩阵中的每个元素横向顺序依次放到一个一维矩阵(列表)中。
参数out:指定时,会把结果放到这个参数中;out=None时,直接把结果返回出去。
最好的说明是官方举例:
"""
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
[3, 4],
[5, 6]])
>>> np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],
[3, 4, 6]])
>>> np.concatenate((a, b), axis=None)
array([1, 2, 3, 4, 5, 6]
"""