manual grayscale in opencv is too slow

守給你的承諾、 提交于 2020-01-14 18:50:33

问题


Note: I have to do this manually so don't suggest me to use the library function cvtColor().

I'm new to opencv and I am trying to grayscale an color image with the formula

(r,g,b) = (r,g,b)/((r+g+b)/3)

Here is my method(C++) for converting to grayscale:

    Mat dst = src.clone();
for (int i= 0; i<src.rows; ++i)
{
    for (int j = 0 ; j < src.cols; ++j)
    {
        Vec3b myVec = dst.at<Vec3b>(i,j);

        uchar temp = (myVec[0]+myVec[1]+myVec[2])/3;
        Vec3b newPoint(temp,temp,temp);
        dst.at<Vec3b>(i,j) = newPoint ;
    }
}

Because I want to grayscale a video so I use this method to grayscale each of its frame. It is really slow in comparison with using the cvtColor(src,dst,CV_RGB2GRAY). (I only waitkey(1) so it is not the problem of waitkey)

I have 2 questions

  1. I just wonder if there are any way to manually grayscale an image that is as fast as cvtColor. If not do you guy know how to optimize the above code so that the grayscale video appears to be smoother.
  2. The above is just one approach to grayscale. (r,g,b) = (r,g,b)/((r+g+b)/3) Can you guy tell me about all other approaches for grayscale a color image?

Any answer would be appreciated. Thanks in advance.


回答1:


I can tell you that the ::at function is slow.

I always use a struct and a pointer here is an rgb example:

#pragma pack(push, 2)
 struct RGB {        //members are in "bgr" order!
   uchar blue;
   uchar green;
   uchar red;  
 };

And then acces the pixels of you image like this:

RGB& rgb = image.ptr<RGB>(y)[x]; //y = row, x = col

Change pixel values (for an RGB image) like this:

image.ptr<RGB>(y)[x].value[0] = 142;
image.ptr<RGB>(y)[x].value[1] = 255;
image.ptr<RGB>(y)[x].value[2] = 90;

You can translate that into your grayscale problem pretty easy. The good thing about this is, that its really fast because a scanline of an cv::Mat image are not split in the memory the pixels of one scanline are next to each other in the memory.



来源:https://stackoverflow.com/questions/24319406/manual-grayscale-in-opencv-is-too-slow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!