混合两个图像,错误:图像不匹配

2024-07-01 08:34:44 发布

您现在位置:Python中文网/ 问答频道 /正文

试着把两个图像混合在一起。 我得到了一个例外的图像不匹配,不知道要改变什么或如何操作一个图像,使它匹配

两张照片: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对两个图像进行转换

^{pr2}$
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")

我得到的错误是

Expected cv::UMat for argument 'src'


Tags: totest图像imagealphaconvertpngopen
1条回答
网友
1楼 · 发布于 2024-07-01 08:34:44

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

通过

^{pr2}$

程序应该可以正常工作。在

编辑:-

help(cv2.addWeighted)说的没错全部:-在

second input array of the same size and channel number as src1 (first array)

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

因此,您必须转换其中一个图像的图像颜色模式,以匹配另一个图像的颜色模式。对他们的尺寸也一样。在

您可以通过使用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)

cv2方法:-

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)

相关问题 更多 >

    热门问题