使用OpenCV2的hconcat和vconcat函数时出现断言失败错误求助
OpenCV hconcat/vconcat 断言失败错误排查与解决
问题详情
执行hconcat或vconcat时触发断言错误:
cv2.error: OpenCV(4.6.0) /io/opencv/modules/core/src/matrix_operations.cpp:65: error: (-215:Assertion failed) src[i].dims <= 2 && src[i].rows == src[0].rows && src[i].type() == src[0].type() in function 'hconcat'
使用代码:
import cv2 img1 = cv2.imread('test1.jpeg') img2 = cv2.imread('book.jpg') h_concat_img = cv2.hconcat([img1, img2]) v_concat_img = cv2.vconcat([img1, img2]) cv2.imshow('horizontal', h_concat_img) cv2.imshow('vertical', v_concat_img) cv2.waitKey(0) cv2.destroyAllWindows()
环境:Python 3.10.8、OpenCV 4.6.0,照搬教程代码仍无法解决。
解决步骤
错误提示的三个断言条件是核心排查点,逐一处理:
- 校验图片加载状态
cv2.imread找不到文件会返回None,直接拼接会触发错误,先添加校验:
img1 = cv2.imread('test1.jpeg') img2 = cv2.imread('book.jpg') if img1 is None or img2 is None: print("图片加载失败,检查文件路径是否正确") exit()
确保图片维度为2D
确认两张图都是普通的2D矩阵(彩色图为(高,宽,3),灰度图为(高,宽)),不能是3D以上的张量。用print(img1.shape)查看维度,若存在异常维度,需预处理调整。水平拼接要求高度一致
hconcat强制要求所有输入图的行数(高度)相同,高度不同时先resize:
# 将img2的高度统一为img1的高度,保持宽高比 target_height = img1.shape[0] scale = target_height / img2.shape[0] target_width = int(img2.shape[1] * scale) img2_resized = cv2.resize(img2, (target_width, target_height)) h_concat_img = cv2.hconcat([img1, img2_resized])
- 垂直拼接要求宽度一致
vconcat强制要求所有输入图的列数(宽度)相同,宽度不同时resize:
# 将img2的宽度统一为img1的宽度,保持宽高比 target_width = img1.shape[1] scale = target_width / img2.shape[1] target_height = int(img2.shape[0] * scale) img2_resized = cv2.resize(img2, (target_width, target_height)) v_concat_img = cv2.vconcat([img1, img2_resized])
- 统一图片类型
确保两张图的通道数一致(比如都是3通道彩色图或单通道灰度图),若一张是灰度图,转为彩色图:
# 灰度图转彩色图 if len(img1.shape) == 2: img1 = cv2.cvtColor(img1, cv2.COLOR_GRAY2BGR) if len(img2.shape) == 2: img2 = cv2.cvtColor(img2, cv2.COLOR_GRAY2BGR)
内容的提问来源于stack exchange,提问作者BodyCreator0909
相关产品推荐
相关产品推荐

