0

The following is my C-OpenCV code.I can reach img.at(2,3)=5;//its ok but why program don't give me a segmentation fault error when I try to reach a number bigger than WIDTH (10 in here) like img.at(2,10)=5;

    const int HEIGHT    = 5;
    const int WIDTH     = 4;
    const int CHANNEL   = 4;

    int main( int argc, char** argv )
    {

    Mat img(HEIGHT,WIDTH, CV_8U);

    int choosingWidth=3;
    int choosingHeight=2;


    cout << "img = \n"<< " "  << img << "\n\n";

    img.at<char>(choosingHeight,choosingWidth)=5;
    cout << "img = \n"<< " "  << img << "\n\n";

    choosingWidth=10;
    img.at<char>(choosingHeight,choosingWidth)=5;
    cout << "img = \n"<< " "  << img << "\n\n";

    return 0;
    }
 
  • it depends on the compiler and mode used (debug vs release) so please provide this information too. – Ahmed AEK Dec 09 '21 at 08:21
  • nvcc chossingElement.cu -o o1 `pkg-config --libs --cflags opencv4` I compile program like this. – Elif Kantar Dec 09 '21 at 08:24
  • 2
    in debug mode you will get an opencv error because in debug mode the size of the matrix is checked before accessing a value. In release mode there is no check (optimized) and so accessing a value outside of the matrix is undefined behaviour. You will observe a segmentation fault only if the memory you are accessing was not allocated by your application. So if you dont observe a segmentation fault, you are accidentally accessing a memory location that was allocated by your application. – Micka Dec 09 '21 at 08:27
  • 3
    currently you are trying to access linear matrix element with index 18 (row-index*width + col-index = 2*4+10) which is equal to matrix element with index row-index=4 and col-index=2, so you are accesing img.at(4,2) which is part of your application. – Micka Dec 09 '21 at 08:37
  • First of all using `img.at(cv::Point(choosingHeight,choosingWidth))` is better than `img.at(choosingHeight,choosingWidth)` . @Micka is right, if you assign a real image from a directory and try to assign a non-exist pixel to an integer, then you will get your error – Yunus Temurlenk Dec 09 '21 at 08:48
  • How can I control this, If I want to get segmentation fault error how do I implement this program ? Because I don't want to reach like this. Do I have another choice? – Elif Kantar Dec 09 '21 at 08:57
  • 2
    `img.at(cv::Point(choosingHeight,choosingWidth))` would be wrong, it would have to be `img.at(cv::Point(choosingWidth,choosingHeight))`, see https://stackoverflow.com/questions/25642532/opencv-pointx-y-represent-column-row-or-row-column/25644503#25644503 – Micka Dec 09 '21 at 08:57
  • test `if( choosingWidth < img.cols && choosingHeight < img.rows)` before accessing the value – Micka Dec 09 '21 at 08:58
  • 1
    you never specify the number of channel for your mat (which will be 1 in your example). Use `Mat img(HEIGHT,WIDTH, CV_8UC4);` for a 4 channel matrix – Miki Dec 09 '21 at 09:31

0 Answers0