为什么在 opencv 中使用 uchar 矩阵会给我错误结果?



我想使用 opencv(4.2 c++) 通过指针获取矩阵的每个值,因为我需要通过 8UC1 处理灰度图像。

当我使用浮点矩阵时,这很好,但使用 uchar 不起作用。

cv::Mat src_f = Mat::eye(4, 4, CV_32FC1);
float* test_f = src_f.ptr<float>(0);
cout << "test_f ptr address:" << test_f <<endl; 
for (size_t i = 0; i < 16; i++)
{
cout << "test_f ptr value:" << *(test_f+i) <<endl; 
}
cv::Mat src_u = Mat::eye(4, 4, CV_8UC1);
uchar* test_u = src_u.ptr<uchar>(0);
cout << "test_u ptr address:" << test_u <<endl; 
for (size_t i = 0; i < 16; i++)
{
cout << "test_u ptr value:" << *(test_u+i) <<endl; 
}

我得到了这样的输出

test_f ptr address:0x562c91769280
test_f ptr value:1
test_f ptr value:0
test_f ptr value:0
test_f ptr value:0
test_f ptr value:0
test_f ptr value:1
test_f ptr value:0
test_f ptr value:0
test_f ptr value:0
test_f ptr value:0
test_f ptr value:1
test_f ptr value:0
test_f ptr value:0
test_f ptr value:0
test_f ptr value:0
test_f ptr value:1
test_u ptr address:
test_u ptr value:
test_u ptr value:
test_u ptr value:
test_u ptr value:
test_u ptr value:
test_u ptr value:
test_u ptr value:
test_u ptr value:
test_u ptr value:
test_u ptr value:
test_u ptr value:
test_u ptr value:
test_u ptr value:
test_u ptr value:
test_u ptr value:
test_u ptr value:

我无法获取地址或值。谁能帮忙?谢谢。

当您想在控制台上打印字符的数字序列时,您必须将其提升为更广泛的类型,例如unsigned short.否则,您将看到仅由存储在char类型的数值赋予的字符。

cout << "test_u ptr value:" << (unsigned short)*(test_u+i) <<endl; 

operator<<对需要以null 结尾的字符数组的char*具有重载。因为您创建了眼图矩阵,所以第一个字节是 1,下一个字节是 0。1表示空格字符,这就是为什么您在控制台上看不到任何内容的原因(尝试分配test_u[0] = 65,然后您将看到打印的A字符)。 要打印地址,您必须使用强制转换来void

cout << "test_u ptr address:" << (void*)test_u <<endl; 

最新更新