在opencv(c++)中,在所有像素上运行方法的最快方法是什么

what is the fastest way to run a method on all pixels in opencv (c++)

本文关键字:方法 运行 是什么 像素 opencv c++      更新时间:2023-10-16

我在opencv中的每个像素上都有几个任务要做。我正在使用这样一个结构:

for(int row = 0; row < inputImage.rows; ++row)
    {
        uchar* p = inputImage.ptr(row);
        for(int col = 0; col < inputImage.cols*3; col+=3)
        {
            int blue=*(p+col);  //points to each pixel B,G,R value in turn assuming a CV_8UC3 colour image
            int green=*(p+col+1);
            int red=*(p+col+2);
            // process pixel            }
    }

这是有效的,但我想知道是否有更快的方法可以做到这一点?该解决方案不使用任何SIMD或OpenCV的任何并行处理。

在opencv中对图像的所有像素运行方法的最佳方式是什么?

如果Mat是连续的,即矩阵元素连续存储,每行末尾没有间隙,可以使用Mat::isContinuous()引用,则可以将它们视为长行。因此,你可以这样做:

const uchar *ptr = inputImage.ptr<uchar>(0);
for (size_t i=0; i<inputImage.rows*inputImage.cols; ++i){
    int blue  = ptr[3*i];
    int green = ptr[3*i+1];
    int red   = ptr[3*i+2];
    // process pixel 
}

正如文档中所说,这种方法虽然非常简单,但可以将简单元素操作的性能提高10-20%,尤其是在图像很小且操作非常简单的情况下。

PS:为了更快的需求,你需要充分利用GPU来并行处理每个像素。