python通过cv2.merge结合新矩阵时报错-215:Assertion failed解决方法

在用cv2对不同矩阵合成一张图像过程中,利用cv2.merge进行结合即可,代码如下:

import numpy as np
import cv2

image = cv2.imread("0037.png")

# R、G、B分量的提取
(B, G, R) = cv2.split(image)  # 提取R、G、B分量
fill_R = np.zeros((768, 1366))
fill_G = np.zeros((768, 1366))
fill_B = np.zeros((768, 1366))
B_s = cv2.merge([B, fill_G, fill_R])
G_s = cv2.merge([fill_B, G, fill_R])
R_s = cv2.merge([fill_B, fill_G, R])

但在运行代码过程中发生如下错误:

cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-nxx381if\opencv\modules\core\src\merge.dispatch.cpp:129:error: (-215:Assertion failed) mv[i].size == mv[0].size &&mv[i].depth() == depth in function ‘cv::merge’

最开始解读错误信息,以为是0矩阵的shape和B分量的shape不一致,通过代码发现:shape一致。

print(fill_R.shape, B.shape)

(768, 1366) (768, 1366)

再尝试解决问题,打印出B分量和0矩阵,发现B分量为整数类型,而0矩阵为float型,因此,将0矩阵在建立时加上dtype=np.int再merge:

fill_B = np.zeros((768, 1366), dtype=np.int)
fill_G = np.zeros((768, 1366), dtype=np.int)
fill_R = np.zeros((768, 1366), dtype=np.int)

B_s = cv2.merge([B, fill_G, fill_R])

仍报相同错误:

cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-nxx381if\opencv\modules\core\src\merge.dispatch.cpp:129: error: (-215:Assertion failed) mv[i].size == mv[0].size && mv[i].depth() == depth in function 'cv::merge'

尝试不用merge,直接将三个二维向量变成一个三维向量,再进行保存展示,在print时,发现B分量的数据类型为uint8,所以,将0矩阵的dtype设为uint8,解决问题。全部代码如下:

import numpy as np
import cv2

image = cv2.imread("0037.png")

# R、G、B分量的提取
(B, G, R) = cv2.split(image)  # 提取R、G、B分量
fill_B = np.zeros((768, 1366), dtype=np.uint8)
fill_G = np.zeros((768, 1366), dtype=np.uint8)
fill_R = np.zeros((768, 1366), dtype=np.uint8)
B_s = cv2.merge([B, fill_G, fill_R])
G_s = cv2.merge([fill_B, G, fill_R])
R_s = cv2.merge([fill_B, fill_G, R])

效果图如下图所示:

你可能感兴趣的:(python,opencv,python,opencv)