【问题标题】:Merging two images in CV2在 CV2 中合并两个图像
【发布时间】:2021-02-08 05:16:20
【问题描述】:

我正在尝试使用 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)

没用

【问题讨论】:

  • 假设我理解正确,是什么阻止您从一个图像中切出前半列而从另一个图像中切出另一半列?
  • 我不知道该怎么做,我刚开始上这门影像课,正在努力掌握这个概念。

标签: python numpy opencv3.0


【解决方案1】:

查看代码cmets了解分步说明。

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

图片提供:谷歌

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-02
    • 2018-01-19
    • 2012-10-10
    • 2012-02-10
    • 2011-01-20
    • 2010-10-02
    相关资源
    最近更新 更多