gpt4 book ai didi

c++ - 访问多 channel OpenCV Mat 中的元素

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:18:09 26 4
gpt4 key购买 nike

这是我在 stackoverflow 上的第一篇文章,所以我希望一切都做对,如果做错了,我深表歉意。

我正在为将单个 RGB 值转换为 CIE L*a*b* 颜色空间的函数编写代码。该函数应该采用 3 个 float 数组(RGB channel 的值在 [0-255] 中),并在输出中给出一个具有 L*a*b* 值的 3 个 float 数组。为此,我使用了 cvtColor OpenCV 可用的函数。

根据 the openCV website 上的建议我正在通过构造函数创建 Mat 结构(cvtColor 需要)。

我的问题是,虽然我认为代码可以正常运行并执行转换,但我无法取回 Mat 结构中包含的值。

这是我的代码:

float * rgb2lab(float rgb[3]) {
// bring input in range [0,1]
rgb[0] = rgb[0] / 255;
rgb[1] = rgb[1] / 255;
rgb[2] = rgb[2] / 255;

// copy rgb in Mat data structure and check values
cv::Mat rgb_m(1, 1, CV_32FC3, cv::Scalar(rgb[0], rgb[1], rgb[2]));
std::cout << "rgb_m = " << std::endl << " " << rgb_m << std::endl;
cv::Vec3f elem = rgb_m.at<cv::Vec3f>(1, 1);
float R = elem[0];
float G = elem[1];
float B = elem[2];
printf("RGB =\n [%f, %f, %f]\n", R, G, B);

// create lab data structure and check values
cv::Mat lab_m(1, 1, CV_32FC3, cv::Scalar(0, 0, 0));
std::cout << "lab_m = " << std::endl << " " << lab_m << std::endl;

// convert
cv::cvtColor(rgb_m, lab_m, CV_RGB2Lab);

// check lab value after conversion
std::cout << "lab_m2 = " << std::endl << " " << lab_m << std::endl;
cv::Vec3f elem2 = lab_m.at<cv::Vec3f>(1, 1);
float l = elem2[0];
float a = elem2[1];
float b = elem2[2];
printf("lab =\n [%f, %f, %f]\n", l, a, b);

// generate the output and return
static float lab[] = { l, a, b };
return lab;
}

如您所见,我通过 at 函数从 Mat 结构中提取所有 channel ,然后从 vector 中单独访问它们。这在许多地方被提议作为解决方案 ( one of them )。

但是如果我运行此代码(输入 vector 为 {123,10,200}),在 cout 上我正确地获得了 Mat 结构的输出(从中我得到算法正在正确转换),但如您所见,提取的值是错误的:

rgb_m = 
[0.48235294, 0.039215688, 0.78431374]
RGB =
[0.000000, 0.000000, -5758185472.000000]
lab_m =
[0, 0, 0]
lab_m2 =
[35.198029, 70.120964, -71.303688]
lab =
[0.000000, 0.000000, 4822177514157213323960797626368.000000]

有人知道我做错了什么吗?

非常感谢您的帮助!

最佳答案

cv::Mat 的第一个元素总是在 (0, 0) , 所以正确 cv::Vec3f elem = rgb_m.at<cv::Vec3f>(1, 1);通过 cv::Vec3f elem = rgb_m.at<cv::Vec3f>(0, 0);cv::Vec3f elem2 = lab_m.at<cv::Vec3f>(1, 1);通过 cv::Vec3f elem2 = lab_m.at<cv::Vec3f>(0, 0);

关于c++ - 访问多 channel OpenCV Mat 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30456113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com