提取单个像素数据的最快方法

Fastest way to extract individual pixel data?

本文关键字:方法 数据 单个 像素 像素数 提取      更新时间:2023-10-16

我必须使用OpenCV获得关于灰度图像上许多像素的标量值的信息。它将遍历数十万像素,所以我需要最快的方法。我在网上找到的所有其他来源都很神秘,很难理解。有没有一行简单的代码应该只提供一个简单的整数值,表示图像的第一个通道(亮度)的标量值?

for (int row=0;row<image.height;row++) {
    unsigned char *data = image.ptr(row);
    for (int col=0;col<image.width;col++) {
       // then use *data for the pixel value, assuming you know the order, RGB etc           
       // Note 'rgb' is actually stored B,G,R
       blue= *data++;
       green = *data++;
       red = *data++;
    }
}

您需要在每一个新行上获得数据指针,因为opencv将在每一行的开头将数据填充到32位边界

关于Martin的帖子,您实际上可以使用OpenCV的Mat对象中的isContinuous()方法来检查内存是否连续分配。以下是一个常见的习惯用法,用于确保外部循环在可能的情况下只循环一次:

#include <opencv2/core/core.hpp>
using namespace cv;
int main(void)
{
    Mat img = imread("test.jpg");
    int rows = img.rows;
    int cols = img.cols;
    if (img.isContinuous())
    {
        cols = rows * cols; // Loop over all pixels as 1D array.
        rows = 1;
    }
    for (int i = 0; i < rows; i++)
    {
        Vec3b *ptr = img.ptr<Vec3b>(i);
        for (int j = 0; j < cols; j++)
        {
            Vec3b pixel = ptr[j];
        }
    }
    return 0;
}