C++ – Accessing elements of OpenCV CV_8UC1 cv::Mat

copencv

I have a cv::Mat of type CV_8UC1 (8-bit single channel image) and I would like to access elements using the at<> operator as follows: image.at<char>(row, column). However, when casting to int: (int) image.at<char>(row, column), some values become negative, e.g., 255 becomes -1.

This might be a stupid question, but I can't tell why this happens and what would be a better way to convert the entries to int.

Thanks in advance!

Best Answer

You have to specify that the elements are unsigned char, between 0 and 255 , otherwise they will be char (signed), from -128 to 127. The casting will be this way:

(int) image.at<uchar>(row,column);
Related Topic