You can use macros defined by opencv to extract pixel values.
Assume that the gray-scale image can be used to access the pixels in column J of its line I: cv_image_elem (image, uchar, Y, X)
For a color image
Cv_image_elem (image, uchar, Y, 3 * X)
Cv_image_elem (image, uchar, Y, 3 * x + 1)
Cv_image_elem (image, uchar, Y, 3 * x + 2)
Cv_image_elem is a macro,
# Define cv_image_elem (image, elemtype, row, col )\
(Elemtype *) (image)-> imagedata + (image)-> widthstep * (ROW) [(COL)])
# Define cv_mat_elem (MAT, elemtype, row, col )\
(* (Elemtype *) cv_mat_elem_ptr_fast (MAT, row, Col, sizeof (elemtype )))
Well, I have always used it as a function. Actually, there is no difference in nature.
However, to correctly obtain the pixel value of the image coordinate (x, y) point, we should write cv_image_elem (image, uchar, Y, x) in this way)
Note that the order of the coordinate XY of the pixel points and the value of the row and column is the opposite (you can think carefully about why)
I have been writing cv_image_elem (image, uchar, x, y) at the beginning, and sometimes it takes a long time to make an error when I access the image,
However, you can copy the image data to the mat as follows:
Cv_image_elem (pimage, uchar, I, j) = cv_mat_elem (* mat, uchar, I, j)
No need to change order
In short, if an error is reported when the macro is applied, try to change the order or check whether the accessed address is out of bounds.