Home > Backend Development > C++ > How to Extract Pixel Channel Values from a Mat Image in OpenCV?

How to Extract Pixel Channel Values from a Mat Image in OpenCV?

DDD
Release: 2024-11-15 22:47:02
Original
769 people have browsed it

How to Extract Pixel Channel Values from a Mat Image in OpenCV?

OpenCV: Extracting Pixel Channel Values from Mat Images

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...
    }
}
Copy after login

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...
    }
}
Copy after login

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...
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template