opencv Pixel Access Access individual pixel values with cv::Mat::at()


To access pixel values in an OpenCV cv::Mat object, you first have to know the type of your matrix.

The most common types are:

  • CV_8UC1 for 8-bit 1-channel grayscale images;
  • CV_32FC1 for 32-bit floating point 1-channel grayscale images;
  • CV_8UC3 for 8-bit 3-channel color images; and
  • CV_32FC3 for 32-bit floating point 3-channel color images.

The default setting with cv::imread will create a CV_8UC3 matrix.

To access individual pixels, the safest way, though not the most efficient, is to use cv::Mat::at<T>(r,c) method where r is the row of the matrix and c is the column. The template argument depends on the type of the matrix.

Let us say you have a cv::Mat image. According to its type, the access method and the pixel color type will be different.

  • For CV_8UC1: uchar pixelGrayValue =<uchar>(r,c).
  • For CV_8UC3: cv::Vec3b pixelColor =<cv::Vec3b>(r,c). The cv::Vec3b object represents a triplet of uchar values (integers between 0 and 255).
  • For CV_32FC1: float pixelGrayValue =<float>(r,c).
  • For CV_32FC3: cv::Vec3f pixelColor =<cv::Vec3f>(r,c). The cv::Vec3f object represents a triplet of float values.

Note that OpenCV represents images in row-major order, like, e.g. Matlab or as the convention in Algebra. Thus, if your pixel coordinates are (x,y), then you will access the pixel using<..>(y,x).

Alternatively, at<> also support access via a single cv::Point argument.
In this case, the access is done in column-major:<..>(cv::Point(x,y));

Take a look at OpenCV documentation for more details on this method.