关于OpenCV的图像矩阵拼接(Python版本)及numpy.concatenate函数介绍

功能:给定任意大小的两个图片(矩阵),水平连接成一个图片(矩阵)。高度不同时,使用黑色作为高度较小者的边缘填充,图片垂直居中。

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)

顺便介绍一下numpyconcatenate()函数:

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]
"""

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值