简体   繁体   English

在 CV2 中合并两个图像

[英]Merging two images in CV2

I am trying to merge 2 images in python using CV2 without using libraries to do it.我正在尝试使用 CV2 合并 python 中的 2 个图像,而不使用库来完成它。

So I cannot use any in-built functions from opencv and numpy (Eg: np.mean).所以我不能使用 opencv 和 numpy 的任何内置函数(例如:np.mean)。 In general, I can use function from math library.一般来说,我可以使用数学库中的 function 。 Only Functions allowed for this part are: np.array(), np.matrix(), np.zeros(), np.ones(), cv2.imread(), cv2.namedWindow(), cv2.waitKey().此部分仅允许使用以下函数:np.array()、np.matrix()、np.zeros()、np.ones()、cv2.imread()、cv2.namedWindow()、cv2.waitKey()。

With library I figured to crop two images together and merge them, which would be an easy solve, however without the library I am stuck.使用库我想将两个图像裁剪在一起并将它们合并,这将是一个简单的解决方案,但是没有库我被卡住了。 This should be the final result where the two images are split in the middle and merged properly.这应该是两个图像在中间分割并正确合并的最终结果。

在此处输入图像描述

I tried:我试过了:

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)

No avail徒劳无功

Check the code comments for step by step explanation.检查代码注释以获取分步说明。

# 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)

Image Courtesy: Google图片提供:谷歌

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM