Ask Your Question

Exception thrown when converting OpenCV Mat to array for 1024x1024 but not 512x512?

asked 2019-06-25 14:25:32 -0500

e1513377 gravatar image

I have the following code and images (first one is 1024x1024 and the second is 512x512)

int main() {
    cv::Mat mat0 = cv::imread("lenna1024.bmp");
    double* mat_ptr0 = new double[mat0.cols*mat0.rows];
    for (int i = 0; i < mat0.rows; i++) {
        for (int j = 0; j < mat0.cols; j++) {
            mat_ptr0[j*mat0.rows + i] =<double>(i, j);

I get an exception thrown error for this. However, when I use lenna512.bmp instead of lenna1024.bmp, I don't get that error. Why is this?

edit retag flag offensive close merge delete


Why is this?

new double -- wrong type, you also miss, that it's multi-channel.. don't blindly guess. and please do NOT use Mat::at for anything.

really, do not write code like this. opencv is a highly optimized vector library, don't try to defeat it with your own per-pixel code.

berak gravatar imageberak ( 2019-06-25 15:04:39 -0500 )edit

double means you got 8 bytes per pixel. I think bmp is 3 or 4 bytes per pixel. You can check channel and depth

LBerger gravatar imageLBerger ( 2019-06-25 15:05:32 -0500 )edit

when I use lenna512.bmp instead of lenna1024.bmp, I don't get that error.

run it in debug mode, please. you may not get an error on smaller images, but it's all still wrong.

berak gravatar imageberak ( 2019-06-25 15:12:34 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2019-06-26 11:40:44 -0500

crackwitz gravatar image<double>(i, j);

that is the problem you have. check the type of mat0. it is probably 8-bit unsigned integer, probably 1-channel or 3-channel. Mat::at<> doesn't respect that, instead it just reinterprets the underlying bytes in memory and when you do ask it to give you a double from that, it's gibberish.

mat_ptr0[j*mat0.rows + i]

that is a bug as well. it hasn't bitten you because both your inputs are square. it should be mat0.cols because that's how many elements there are in one row.

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower


Asked: 2019-06-25 14:25:32 -0500

Seen: 57 times

Last updated: Jun 26 '19