简体   繁体   中英

OpenCV segmentation fault after successfully printing each element

This code when executed displays the expected output but prints segmentation fault (core dumped) at the end :

int main(){

    Mat src(100,100,CV_32F,0);

    for(int i=0 ; i < src.rows ; i++ ){
        for(int j=0 ; j < src.cols ; j++ ){
            src.at<float>(i,j)=0;
        }
    }

    for(int i=0 ; i < src.rows ; i++ ){
        for(int j=0 ; j < src.cols ; j++ ){
            cout<<src.at<float>(i,j)<<" ";
        }
        cout<<endl;
    }

    return 0;
} 

Please write the minimal working example so that we can simply copy and paste the code and test it.

#include <iostream>
#include <opencv2/core.hpp>

using namespace std;
using namespace cv;

int main() {

  /* Mat src(100, 100, CV_32F, 0); */
  Mat src(100, 100, CV_32F, Scalar(0));

  for (int i = 0; i < src.rows; i++) {
    for (int j = 0; j < src.cols; j++) {
      src.at<float>(i, j) = 0;
    }
  }

  for (int i = 0; i < src.rows; i++) {
    for (int j = 0; j < src.cols; j++) {
      cout << src.at<float>(i, j) << " ";
    }
    cout << endl;
  }

  return 0;
}

The problem seems to be that opencv compares, at CV_Assert on line 500 of opencv2/core/mat.inl.hpp , data with respect to NULL . Basically, when you give a non-zero value such as 1 in the constructor, or use their Scalar data-type to provide the value, your code just works fine.

By the way, I did not receive a segfault, but simply a CV::Exception when trying to run your code after linking against opencv_core .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM