Home >Backend Development >C++ >How to Efficiently Access Pixel Values in an OpenCV Matrix?

How to Efficiently Access Pixel Values in an OpenCV Matrix?

Barbara Streisand
Barbara StreisandOriginal
2024-12-07 13:46:12939browse

How to Efficiently Access Pixel Values in an OpenCV Matrix?

Accessing Pixel Values in an OpenCV Matrix

Getting pixel values from an OpenCV Mat image can be done through various methods based on the data structure used to represent the pixels.

Assuming an image of type CV_8UC3, where each pixel is represented by three 8-bit unsigned channels (BGR), retrieving a particular pixel's value can be achieved as follows:

for (int i = 0; i < foo.rows; i++) {
    for (int j = 0; j < foo.cols; j++) {
        Vec3b bgrPixel = foo.at<Vec3b>(i, j);

        // Access and manipulate BGR values...
    }
}

Vec3b is a container for 3-element vectors, where each element corresponds to a B, G, and R channel value.

Optimizing Performance

To improve performance, direct access to the data buffer can be used:

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 BGR values...
    }
}

Alternatively, the row() method can be used to access individual rows:

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 BGR values...
    }
}

The above is the detailed content of How to Efficiently Access Pixel Values in an OpenCV Matrix?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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