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(第一个数组)大小和通道号相同的第二个输入数组
意味着两个图像应该具有相同的大小和模式。在您的图像(在评论中提供)中,这两个图像的尺寸(大小)不同,颜色模式也不同。因此,为了解决这个问题,您必须使两个图像的 mode 和 size 相等。
因此,您必须转换任一图像的图像颜色模式,以匹配另一图像的颜色模式。并为它们的尺寸做同样的事情。
您可以通过使用PIL 和cv2 的混合来实现此目的,或者您也可以仅使用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)