OpenCV inRange 更改了垫子类型

OpenCV inRange changes Mat type

本文关键字:类型 inRange OpenCV      更新时间:2023-10-16

我无法摆脱OpenCV中的此错误:

OpenCV 错误:输入参数的大小不匹配(操作为 既不是"数组操作数组"(数组具有相同的大小和类型), 也不是"数组操作标量",也不是"标量操作数组")

Mat.type();发现我所有的Mat(img)都有类型 16,但在函数inRange之后,我的img3将类型更改为 0。然后我不能使用函数bitwise_and因为它的类型不同。

如何将其转换为相同类型?

Mat img1 = imread(argv[1], 1);
Mat img2, img3, img4;
cvtColor(img1, img2, CV_BGR2HSV);
GaussianBlur(img2, img2, Size(15,15), 0); 
inRange(img2, Scalar(h_min_min,s_min_min,v_min_min), Scalar(h_max_min,s_max_min,v_max_min), img3); // now img3 changed type to 0
bitwise_and(img1, img3, img4); // img1.type()=16, img3.type()=0 ERROR
这是

正常的,因为inRange返回一个 1 通道掩码(每个像素的值),因此要执行按位运算,只需将掩码转换回 3 通道图像:

cvtColor(img3,img3,CV_GRAY2BGR);
bitwise_and(img1, img3, img4);// now both images are CV_8UC3 (=16)

编辑:正如Berak所说,要更改频道数量,您必须使用cvtColor,而不是Mat::convertTo。对此感到抱歉。