我正在实时处理视频帧。我一次遍历每个像素,进行一些数学运算,然后将像素设置为特定的颜色(如有必要)。

简而言之,我的算法如下所示:

     //videoFrame is IplImage, 8 bit, 4 channel
     for(int i=0;i<videoFrame.width;i++){
        for(int j=0;j<videoFrame.height;j++){

            CvScalar pixel = cvGet2D(&videoFrame, i, j);

            double red = pixel.val[0];
            double green = pixel.val[1];
            double blue = pixel.val[2];

            //do some math


            if (someCondition) {
                cvSet2D(&videoFrame, i, j, white);
            }
        }
    }

但是我发现调用cvGet2D(&videoFrame, i, j);cvSet2D(&videoFrame, i, j, white);确实很昂贵(慢)。有没有其他更快的方法可以访问每个像素的红色/绿色/蓝色值?

谢谢!

最佳答案

尝试使用指针直接访问数据,如下所示。

for(int i=0;i<videoFrame.width;i++){
  for(int j=0;j<videoFrame.height;j++){
    uchar B =((uchar *)(videoFrame.imageData + j*videoFrame.widthStep))[i*videoFrame.nChannels + 0];
    uchar G =((uchar *)(videoFrame.imageData + j*videoFrame.widthStep))[i*videoFrame.nChannels + 1];
    uchar R =((uchar *)(videoFrame.imageData + j*videoFrame.widthStep))[i*videoFrame.nChannels + 2];


    //do some math

    ((uchar *)(videoFrame.imageData + j*videoFrame.widthStep))[i*videoFrame.nChannels + 0] = B;
    ((uchar *)(videoFrame.imageData + j*videoFrame.widthStep))[i*videoFrame.nChannels + 1] = G;
    ((uchar *)(videoFrame.imageData + j*videoFrame.widthStep))[i*videoFrame.nChannels + 2] = R;

  }
}

10-08 04:36