Shashank Yadav Shashank Yadav - 3 months ago 12
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(! gray_image.data ) // 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)gray_image.at<uchar>(1201,0)<<endl; //SEGFAULT

Answer

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 mat.at<>(). I would recommend you to use mat.at<>(cv::Point(p_x, p_y)) in this way you would never get confused with rows and cols to be passed in the mat.at<>().