Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cv::Exception at memory location while looping over cv::Mat object

Tags:

c++

opencv

I create an empty matrix hide_image with zero values. Dimentions are right - 672x896. Each element should be filled with value, I do it in loop. But on (0, 299) element code throw an exception:

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

I debugged the function and found out that exceptions depend of j value in loop. I can set j<299 and program will work without problems, but I need all matrix. In command line I see this message:

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

May be it happens because of wrong matrix initialisation, but why there's shown right dimentions? Rows are right number and if I set j<298, loop ends on i=671. But columns are less and it seems that number 299 does not depend on anything.

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;
}

Why this exception occurs?

like image 322
la Gorda Avatar asked Dec 06 '25 07:12

la Gorda


1 Answers

You are using different types to initialize and loop through the matrix...

During initialization you use CV_8U which is an 8 bit pixel representation (one 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);

Then you use Vec3b which is a 24 bit per pixel (equivalent to CV_8UC3). So it will condume the data 3 times faster, and then you are out of data and a segmentation error is bound to happen.

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;
  }

What can you do:

Initialize with CV_8UC3 instead of CV_8U or use uchar instead of Vec3b.

BTW, this line

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

is unnecessary if you do the next line

hide_image = cv::Mat::zeros(hide_image_rows, hide_image_cols, CV_8U);
like image 196
api55 Avatar answered Dec 07 '25 21:12

api55



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!