Question: How can you retrieve the channel value of a specific pixel in a Mat image?
Answer:
For a Mat object where the pixel type is CV_8UC3 (an 8-bit unsigned 3-channel image), the following method can be used:
for(int i = 0; i < foo.rows; i++) { for(int j = 0; j < foo.cols; j++) { Vec3b bgrPixel = foo.at<Vec3b>(i, j); // Process the BGR values... } }
In this code, Vec3b represents a 3-channel pixel with 8-bit unsigned integers for each channel. at is a member function that allows you to access the pixel value at the specified row and column.
Performance Optimization:
For improved performance, consider accessing the data buffer directly:
uint8_t* pixelPtr = (uint8_t*)foo.data; int cn = foo.channels(); Scalar_<uint8_t> bgrPixel; for(int i = 0; i < foo.rows; i++) { for(int j = 0; j < foo.cols; j++) { bgrPixel.val[0] = pixelPtr[i*foo.cols*cn + j*cn + 0]; // B bgrPixel.val[1] = pixelPtr[i*foo.cols*cn + j*cn + 1]; // G bgrPixel.val[2] = pixelPtr[i*foo.cols*cn + j*cn + 2]; // R // Process the BGR values... } }
Alternatively, you can use the row method:
int cn = foo.channels(); Scalar_<uint8_t> bgrPixel; for(int i = 0; i < foo.rows; i++) { uint8_t* rowPtr = foo.row(i); for(int j = 0; j < foo.cols; j++) { bgrPixel.val[0] = rowPtr[j*cn + 0]; // B bgrPixel.val[1] = rowPtr[j*cn + 1]; // G bgrPixel.val[2] = rowPtr[j*cn + 2]; // R // Process the BGR values... } }
Note: OpenCV internally stores images in BGR format, not RGB.
The above is the detailed content of How to Extract Pixel Channel Values from a Mat Image in OpenCV?. For more information, please follow other related articles on the PHP Chinese website!