How to access individual pixels in OpenCV 2.3 using C++?
For my U8C3 image I tried this:
Scalar col = I.at<Scalar>(i, j);
and
p = I.ptr<uchar>(i);
First is throwing an exception, the second one is returning some unrelated data. Also all examples I was able to find are for old IIPimage(?) for C version of OpenCV.
All I need is to get color of pixel at given coordinates.
The type you call
cv::Mat::atwith needs to match the type of the individual pixels. Sincecv::Scalaris basically acv::Vec<double,4>, this won’t work for aU8C3image (it would work for aF64C4image, of course).In your case you need a
cv::Vec3b, which is atypedefforcv::Vec<uchar,3>:You can then convert this into a
cv::Scalarif you really need to, but the type of thecv::Mat::atinstantiation must match the type of your image, since it just casts the image data without any conversions.Your second code snippet returns a pointer to the ith row of the image. It is no unrelated data, but just a pointer to single
ucharvalues. So in case of aU8C3image, every consecutive 3 elements in the data returned topshould represent one pixel. Again, to get every pixel as a single element usewhich again does nothing more than an appropriate cast of the row pointer before returning it.
EDIT: If you want to do many pixel accesses on the image, you can also use the
cv::Mat_convenience type. This is nothing more than a typed thin wrapper around the image data, so that all accesses to image pixels are appropriately typed:You can then freely use
U(i, j)and always get a 3-tuple of unsigned chars and therefore pixels, again without any copying, just type casts (and therefore at the same performance asI.at<Vec3b>(i, j)).