【问题标题】:Blending two images, error: Images do not match混合两个图像,错误:图像不匹配
【发布时间】:2019-07-31 14:33:43
【问题描述】:

尝试将两个图像混合在一起。 我遇到了图像不匹配的异常,不确定要更改什么或如何操作图像以使其匹配

两张照片:photo 1photo 2

fg = Image.open("test.png").convert("RGBA") ## ive done it with and without RGBA
bg = Image.open("newfig.png").convert("RGBA")
# set alpha to .7
Image.blend(bg, fg, .5).save("out.png")

然后我尝试使用cv2 转换两个图像

fg = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
fg = Image.open("test.png")
fg = cv2.cvtColor(fg, cv2.COLOR_BGR2GRAY)

bg = Image.open("newfig.png")
bg = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY)

# set alpha to .7
Image.blend(bg, fg, .5).save("out.png")

然后我得到的错误是

参数“src”的预期 cv::UMat

【问题讨论】:

    标签: python image python-imaging-library cv2 blending


    【解决方案1】:

    cv2.cvtColor() 期望(通常)通过cv2.imread()(或更具体地说是 numpy 数组)创建的源图像对象作为它的第一个参数。但是在您的代码中,您使用Image.open() 创建PIL.Image 对象并将其作为参数传递给cv2.cvtColor(),这会导致错误。

    只需将所有Image.open() 替换为cv2.imread(),程序就可以正常工作了。

    fg = Image.open("test.png")
    bg = Image.open("newfig.png")
    

    fg = cv2.imread("test.png", -1)
    bg = cv2.imread("newfig.png", -1)
    

    程序应该可以正常运行。

    编辑:-

    help(cv2.addWeighted) 说明一切:-

    与 src1(第一个数组)大小和通道号相同的第二个输入数组

    意味着两个图像应该具有相同的大小和模式。在您的图像(在评论中提供)中,这两个图像的尺寸(大小)不同,颜色模式也不同。因此,为了解决这个问题,您必须使两个图像的 modesize 相等。

    因此,您必须转换任一图像的图像颜色模式,以匹配另一图像的颜色模式。并为它们的尺寸做同样的事情。

    您可以通过使用PILcv2 的混合来实现此目的,或者您也可以仅使用cv2 来实现此目的。

    混合法:-

    from PIL import Image
    import cv2
    import numpy as np
    
    fg = Image.open("test.png")
    
    # converting the color mode of the second image to match the first image, while opening the second image
    bg = Image.open("newfig.png").convert(fg.mode)
    
    # resizing the second image to the same dimensions as the first one
    bg = bg.resize(fg.size)
    
    # creating an numpy array off both the image objects, for using in addWeighted()
    bg = np.array(bg)
    fg = np.array(fg)
    
    img = cv2.addWeighted(fg, 0.3, bg, 0.7, 0)
    

    Purecv2 方法:-

    import cv2
    
    fg = cv2.imread("test.png", -1)
    bg = cv2.imread("newfig.png", -1)
    
    # converting color modes of both the images to Greyscale    
    fg = cv2.cvtColor(fg, cv2.COLOR_BGR2GRAY)
    bg = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY)
    
    # resizing both the images to 400x400 size
    fg = cv2.resize(fg, (400, 400))
    bg = cv2.resize(bg, (400, 400))
    
    img = cv2.addWeighted(fg, 0.3, bg, 0.7, 0)
    

    【讨论】:

    • 所以我做到了 fg = cv2.imread("test.png", -1) bg = cv2.imread("newfig.png", -1) fg = cv2.cvtColor(fg, cv2.COLOR_BGR2GRAY) bg = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY) img = cv2.addWeighted(fg, 0.3, bg, 0.7, 0)
    • 现在它给了我 209:输入参数的大小不匹配
    • @AricaChristensen 那么可能 numpy 数组的大小(或两个图像的尺寸/颜色空间)可能不同。我看不到这些图片,因为您对它们进行了安全保护,所以请让这些图片公开可见,以便我分析它们
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 2020-04-22
    • 2015-01-01
    • 1970-01-01
    • 2014-05-18
    相关资源
    最近更新 更多