在 CV2 中合并两个图像

Merging two images in CV2

我正在尝试使用 CV2 在 python 中合并 2 个图像,而不使用库来完成。

所以我不能使用 opencv 和 numpy 的任何内置函数(例如:np.mean)。 一般来说,我可以使用数学库中的函数。 此部分仅允许的函数是:np.array()、np.matrix()、np.zeros()、np.ones()、cv2.imread()、cv2.namedWindow(), cv2.waitKey().

有了库,我想将两个图像裁剪在一起并合并它们,这将是一个简单的解决方案,但是如果没有库,我就会卡住。这应该是最终的结果,两张图片在中间分开并正确合并。

我试过了:

image_left = cv2.imread("grace_1.png")[:155]
image_left = cv2.imread("grace_1.png")[155:340]
merged_image=np.array(image_left)
mer_img=np.array(image_right)
merged=np.array(left+right)

无用

查看代码评论以获得分步说明。

# import the necessary libraries
import numpy as np
from skimage import io, transform, img_as_float, img_as_ubyte # here I am using skimage, you can use opencv


# read the images
img1 = io.imread('img1.JPG')
img2 = io.imread('img2.JPG')

# convert both the images to same datatype
img1 = img_as_float(img1)
img2 = img_as_float(img2)

# determine the width and heigh of the images
height_of_first_image = img1.shape[0]
width_of_first_image = img1.shape[1]

height_of_the_second_image = img2.shape[0]
width_of_the_second_image = img2.shape[1]

# the img1 and img2 might have different channels for: img1 van be (RGB) but img2 can be (RGBA) in this case you need to drop a channel
if(len(img1.shape) != len(img2.shape)):
    print(f'Images provided not same shape {img1.shape} and {img2.shape}')
else:
    # we need to rezise the height of the second image so that we can join
    # the idea is take 1/2 of img1 + 1/2 of img2
    # for that both should have same height
    img2 = transform.resize(img2, (height_of_first_image, width_of_the_second_image), anti_aliasing=True)
    
    # now we have same height
    img1_half = img1[:, : width_of_first_image//2, :] # take first half of first image
    img2_half = img2[:, width_of_the_second_image//2 :,:] # take second half of second image
    
    # now horizontally stack the,
    final_image = np.hstack((img1_half, img2_half))
    # finally convert the image to unsigned byte format, with values in [0, 255]
    final_image = img_as_ubyte(final_image)
    
# now finally save the image
io.imsave('final.JPG', final_image)

图片礼貌:Google