调用cv2.merge()触发(-215)断言失败错误,求解决办法
调用cv2.merge()触发Assertion failed错误的排查与解决
错误信息
调用cv2.merge()时触发如下断言失败错误:
error: (-215:Assertion failed) mv[i].size == mv[0].size && mv[i].depth() == depth in function 'merge'
代码与运行输出
代码
# 将RGB转换为CIELAB色彩空间 image_lab = cv2.cvtColor(input_image, cv2.COLOR_BGR2LAB) # 将输入图像拆分为独立的颜色通道(BGR顺序) b, g, r = cv2.split(input_image) # 计算每个颜色通道的均值 mean_r = np.mean(r) mean_g = np.mean(g) mean_b = np.mean(b) # 计算灰度图像的均值 mean_gray = np.mean(input_image) # 计算每个通道的修正值 r_corrected = r - 0.3 * (mean_gray - mean_r) * g * (1 - r) b_corrected = b + 0.3 * (mean_gray - mean_b) * g * (1 - b) # 确保所有通道均值相同 mean_r_corrected = np.mean(r_corrected) mean_b_corrected = np.mean(b_corrected) mean_correction = (mean_r_corrected + mean_b_corrected) / 2 # 应用颜色修正使所有通道均值一致 r_corrected = r_corrected + mean_correction - mean_r_corrected b_corrected = b_corrected + mean_correction - mean_b_corrected # 检查通道形状与数据类型 print("b_corrected的形状:", b_corrected.shape) print("g的形状:", g.shape) print("r_corrected的形状:", r_corrected.shape) print("b_corrected的数据类型:", b_corrected.dtype) print("g的数据类型:", g.dtype) print("r_corrected的数据类型:", r_corrected.dtype) # 将修正后的通道与原始绿色通道合并 corrected_image = cv2.merge([b_corrected, g, r_corrected]) # 显示修正后的图像 cv2.imshow('Corrected Image', corrected_image) cv2.waitKey(0) cv2.destroyAllWindows()
运行输出
驱动器已挂载在/content/drive;若要强制重新挂载,请调用drive.mount("/content/drive", force_remount=True)。 b_corrected的形状: (313, 373) g的形状: (313, 373) r_corrected的形状: (313, 373) b_corrected的数据类型: float64 g的数据类型: uint8 r_corrected的数据类型: float64 --------------------------------------------------------------------------- error Traceback (most recent call last) <ipython-input-27-9def3a429c8c> in <cell line: 13>() 51 52 # 将修正后的通道与原始绿色通道合并 ---> 53 corrected_image = cv2.merge([b_corrected, g, r_corrected]) 54 55 # 显示修正后的图像 error: OpenCV(4.8.0) /io/opencv/modules/core/src/merge.dispatch.cpp:129: error: (-215:Assertion failed) mv[i].size == mv[0].size && mv[i].depth() == depth in function 'merge'
错误原因
从输出的通道信息可直接定位问题:
所有通道的尺寸(shape)完全一致,但数据类型不统一——b_corrected和r_corrected为float64类型,而原始g通道是uint8类型。cv2.merge()要求所有输入通道的尺寸、数据类型必须完全匹配,类型不一致会触发断言失败。
解决方法
方法1:将修正后的浮点通道转换为uint8类型
图像显示/存储通常使用uint8(取值范围0-255),先将修正后的浮点值钳制在合法范围,再转换类型:
# 合并前添加以下代码,修正通道类型与范围 r_corrected = np.clip(r_corrected, 0, 255).astype(np.uint8) b_corrected = np.clip(b_corrected, 0, 255).astype(np.uint8) # 执行合并 corrected_image = cv2.merge([b_corrected, g, r_corrected])
方法2:将原始g通道转换为浮点类型
若需保留浮点精度进行后续计算,可先将g通道转为float64,合并后再按需转回uint8:
# 将g通道转换为float64类型 g_float = g.astype(np.float64) # 合并浮点通道 corrected_image_float = cv2.merge([b_corrected, g_float, r_corrected]) # 若要显示图像,再转换为uint8并钳制范围 corrected_image = np.clip(corrected_image_float, 0, 255).astype(np.uint8)
通用排查思路
遇到cv2.merge()的断言错误时,优先检查:
- 所有待合并通道的**尺寸(shape)**是否完全一致(包括高度、宽度)
- 所有通道的**数据类型(dtype)**是否相同
- 浮点运算后的通道值是否超出目标类型的取值范围(比如uint8的0-255),需用
np.clip截断
内容的提问来源于stack exchange,提问作者REKA
相关产品推荐
相关产品推荐

