OpenCV imencode因通道数不合法报错,求问题原因及解决方法
图像裁剪与透视变换中imencode报错问题排查
问题描述
在实现图像裁剪与透视变换时,调用imencode将Mat转为字节数组时触发断言错误:
(Assertion failed) channels == 1 || channels == 3 || channels == 4 in function 'imencode'
输入图像为3通道,但处理后的outputImg仅有2通道,以下是相关代码和运行日志:
代码片段
int process_image_bytes(uchar* bytes, int size, uchar **encodedOutput) { vector <uchar> v(bytes, bytes + size); Mat img = imdecode(Mat(v), IMREAD_COLOR); int width = 200; int height = 200; vector<Point2f> src_p = { Point(200, 200), Point(500, 200), Point(300, 200), Point(500, 300) }; InputArray src_p_arr = src_p; vector<Point2f> dst_p = { Point(0, 0), Point(width, 0), Point(0, height), Point(width, height) }; OutputArray dst_p_arr = dst_p; Mat warpMatrix = getPerspectiveTransform(src_p_arr, dst_p_arr); Mat outputImg; warpPerspective(src_p_arr, outputImg, warpMatrix, dst_p_arr.size()); vector<uchar> buf; imencode(".jpg", outputImg, buf); // <-- 错误发生位置 *encodedOutput = (unsigned char *) malloc(buf.size()); for (int i=0; i < buf.size(); i++) (*encodedOutput)[i] = buf[i]; return (int) buf.size(); }
运行日志
------ INPUT IMAGE img -------- width::: 720 height::: 405 channels::: 3 type::: 16 depth::: 0 ------ WARP MATRIX warpMatrix ------ width::: 3 height::: 3 channels::: 1 type::: 6 depth::: 6 ------ DESTINATION dst_p_arr ------ width::: 4 height::: 1 channels::: 2 type::: 13 depth::: 5 ------ OUTPUT IMAGE outputImg ------ width::: 4 height::: 1 channels::: 2 type::: 13 depth::: 5
问题原因与修复方案
核心原因
调用warpPerspective时传错了输入参数:你把**透视变换的源点集合src_p_arr**当成了输入图像传入,而非真正的输入图像img。
src_p_arr是由Point2f组成的向量,每个Point2f对应2通道(x、y坐标),因此处理后得到的outputImg是2通道矩阵,不符合imencode对JPG格式要求的1/3/4通道条件,触发断言错误。从日志也能看出,outputImg的尺寸是4x1,完全是点集合的特征,并非正常图像尺寸。
修复步骤
- 修正
warpPerspective调用参数:将第一个参数替换为输入图像img,同时指定输出图像的尺寸为目标宽高Size(width, height),而非dst_p_arr.size():Mat outputImg; warpPerspective(img, outputImg, warpMatrix, Size(width, height)); - 检查源点坐标有效性:当前
src_p中前三个点的y坐标均为200,属于共线点,会导致透视变换矩阵计算异常,请调整为有效的四边形顶点。 - 保证点顺序一致性:
dst_p的点顺序建议和src_p一一对应(如左上、右上、左下、右下),确保透视变换的正确性。
内容的提问来源于stack exchange,提问作者poimsm2
相关产品推荐
相关产品推荐

