简体   繁体   English

OpenCV inRange更改了Mat类型

[英]OpenCV inRange changes Mat type

I can't get rid of this error in OpenCV: 我无法摆脱OpenCV中的这个错误:

OpenCV Error: Sizes of input arguments do not match (The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array') OpenCV错误:输入参数的大小不匹配(操作既不是'数组操作数组'(数组具有相同的大小和类型),也不是'数组操作标量',也不是'标量操作数组')

I found out with Mat.type(); 我发现了Mat.type(); that all of my Mat(img) has type 16 but after function inRange my img3 changed type to 0. Then I can't use function bitwise_and because it has not the same type. 所有我的Mat(img)都有16型但是在函数inRange我的img3将类型改为0.然后我不能使用函数bitwise_and因为它的类型不同。

How can I convert it to same type? 如何将其转换为相同类型?

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

This is normal, as inRange returns a 1-channel mask (a value for each pixel), so to perform the bitwise operation simply transform the mask back to 3-channel image: 这是正常的,因为inRange返回1通道掩码(每个像素的值),因此要执行按位操作,只需将掩码转换回3通道图像:

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

EDIT: as Berak says, to change the number of channels you must use cvtColor , not Mat::convertTo . 编辑:正如Berak所说,要改变必须使用cvtColor的通道数,而不是Mat::convertTo Sorry about that. 对于那个很抱歉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM