Shashank Yadav Shashank Yadav - 2 months ago 5x
C++ Question

Unable to access pixel values from greyscale image

I am reading an image of size 1600x1200 as greyscale and then trying to access pixel value at location (1201,0). I get segfault in the end as shown in comments:

Mat gray_image = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE); // Read the file

if(! ) // Check for invalid input
cout << "Could not open or find the image" << std::endl ;
return -1;

const int width = gray_image.cols;
const int height = gray_image.rows;

cout<<gray_image.cols<<endl; // 1600
cout<<gray_image.rows<<endl; // 1200
cout<<(int)<uchar>(1201,0)<<endl; //SEGFAULT


You already stated that you are reading an image of size 1600x1200, then how can you access 1201 element from a total of 1200 rows only, actually you have misunderstood the convention of<>(). I would recommend you to use<>(cv::Point(p_x, p_y)) in this way you would never get confused with rows and cols to be passed in the<>().