OpenCV stitching two images together (Python)

1. Introduction to use functions

The main use of numpy library array splicing np.concatenate
usage example is as follows

>>> a = np.array(([1,2,3],[4,5,6]))
>>> b = np.array(([4,5,6],[7,8,9]))
>>> c = np.array(([7,8,9],[10,11,12]))
>>> np.concatenate((a,b,c), axis = 0)

array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [ 7,  8,  9],
       [10, 11, 12]])
       
>>> np.concatenate((a,b,c), axis = 1)

array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9],
       [ 4,  5,  6,  7,  8,  9, 10, 11, 12]])

When axis is 0, splice several arrays vertically
When axis is 1, splice several arrays horizontally

2. Code implementation

The two images stitched here by default are of the same width or height

# 横向拼接
def concat_1(img_1, img_2):
    rows = np.size(img, 0)
    # 乘255是因为想要间隙是白的,白色像素值是255,如果想要黑色间隙
    interval_1 = np.ones((rows, 5)) * 255
    img_o = np.concatenate((img_1, interval_1, img_2), axis=1)
    return img_o

# 纵向拼接
def concat_0(img_1, img_2):
    columns = np.size(img, 1)
    interval_0 = np.ones((5, columns)) * 255 # 纵向拼接间隙
    img_o = np.concatenate((img_1, interval_0, img_2), axis=0)
    return img_o

Among them, interval refers to the gap between two pictures.

  • When stitching horizontally, the height of the interval should be the same as the height of the picture, and the width of the interval can be set by yourself
  • When stitching vertically, the width of the interval should be the same as the width of the picture, and the height of the interval can be set by yourself

The splicing here is a single-channel grayscale image. If you want to splice a color image, just change the interval. If you find it troublesome, just delete the interval.

Guess you like

Origin blog.csdn.net/weixin_50497501/article/details/128204510