gpt4 book ai didi

c++ - 循环 cv::Mat 对象时 cv::Exception 在内存位置

转载 作者:太空狗 更新时间:2023-10-29 20:34:39 27 4
gpt4 key购买 nike

我创建了一个具有零值的空矩阵 ​​hide_image。尺寸正确 - 672x896。每个元素都应该填充值,我在循环中进行。但是在 (0, 299) 元素代码上抛出异常:

Unhandled exception at 0x00007FFD3C063C58 in stego.exe: Microsoft C++ exception: cv::Exception at memory location 0x000000D2B033E5F0. occurred

我调试了函数,发现异常取决于循环中的 j 值。我可以设置 j<299 并且程序可以正常运行,但我需要所有矩阵。在命令行中,我看到这条消息:

OpenCV Error: Assertion failed ((unsigned)(i1 * DataType<_Tp>::channels) < 
(unsigned)(size.p[1] * channels())) in cv::Mat::at, file c:\opencv-
3.3.1\opencv\build\include\opencv2\core\mat.inl.hpp, line 1095

可能是因为错误的矩阵初始化而发生的,但为什么显示了正确的维度?行数正确,如果我设置 j<298,则循环在 i=671 时结束。但是列较少,而且数字 299 似乎不依赖于任何东西。

cv::Mat hide_image;
int hide_image_cols = 0, hide_image_rows = 0;
int i_current = 0, j_current = 15;
int curr_bit = 0;

get_img_dim(image, hide_image_cols, hide_image_rows);

hide_image = cv::Mat(hide_image_rows, hide_image_cols, CV_8U);
hide_image = cv::Mat::zeros(hide_image_rows, hide_image_cols, CV_8U);
std::cout << (hide_image.at<cv::Vec3b>(671, 299)) << std::endl; // exception

for (int i = 0; i < hide_image.rows; i++)
for (int j = 0; j < hide_image.cols; j++) {
//exception when j>298
std::cout << (hide_image.at<cv::Vec3b>(i, j)) << std::endl;
}

为什么会出现这个异常?

最佳答案

您正在使用不同的类型来初始化和遍历矩阵...

在初始化期间,您使用 CV_8U,这是一个 8 位像素表示(一个 channel )。

hide_image = cv::Mat(hide_image_rows, hide_image_cols, CV_8U);
hide_image = cv::Mat::zeros(hide_image_rows, hide_image_cols, CV_8U);

然后您使用 Vec3b,它是每像素 24 位(相当于 CV_8UC3)。所以它会以快 3 倍的速度消耗数据,然后你就没有数据了,并且必然会发生段错误。

for (int i = 0; i < hide_image.rows; i++)
for (int j = 0; j < hide_image.cols; j++) {
//exception when j>298
std::cout << (hide_image.at<cv::Vec3b>(i, j)) << std::endl;
}

你能做什么:

使用 CV_8UC3 而不是 CV_8U 进行初始化,或者使用 uchar 而不是 Vec3b

顺便说一句,这一行

hide_image = cv::Mat(hide_image_rows, hide_image_cols, CV_8U);

如果你做下一行是不必要的

hide_image = cv::Mat::zeros(hide_image_rows, hide_image_cols, CV_8U);

关于c++ - 循环 cv::Mat 对象时 cv::Exception 在内存位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47197834/

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