0

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
Awais Chishti
  • 395
  • 2
  • 19
  • 1
    It's `.at<>(row, col)`. Maybe you need `gray_image.at(0, 1201)`. – DimChtz Aug 13 '16 at 12:05
  • 1
    see http://stackoverflow.com/questions/25642532/opencv-pointx-y-represent-column-row-or-row-column/25644503#25644503 for my interpretation of openCV mat access "confusion" – Micka Aug 14 '16 at 06:14

2 Answers2

2

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<>().

EDIT : However, creating a new cv::Point is not a recommended way of accessing pixels as suggested by @Micka, So consider it as a workaround and don't rely completely on cv::Point() to access a pixel. The best possible way to iterate the pixels is defined in Opencv documentation.

ZdaR
  • 22,343
  • 7
  • 66
  • 87
  • 2
    always creating a cv::Point might be a big overhead. – Micka Aug 14 '16 at 06:08
  • Yeah but I personally find it more convenient as you would never get confused in row and col. He can use the row, col to access the pixel as suggested in the comments, But i guess he needs it for debugging purposes only, as there is no loop structure in the question to access all the pixels. @Micka your suggestion is welcomed and I updated the answer accordingly – ZdaR Aug 14 '16 at 06:11
0

It should be .at(row,col) not (col,row) and you dont have a 1201th row thats why its a seg fault

Suvam
  • 11