opencv中的手动灰度太慢 [英] manual grayscale in opencv is too slow

查看:141
本文介绍了opencv中的手动灰度太慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我必须手动执行此操作,因此不建议我使用库函数cvtColor().

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

我是opencv的新手,我正在尝试使用公式对彩色图像进行灰度处理

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)

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

这是我的转换为灰度的方法(C ++):

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 ;
    }
}

因为我想对视频进行灰度处理,所以我使用此方法对视频的每个帧进行灰度处理. 与使用cvtColor(src,dst,CV_RGB2GRAY)相比,它确实很慢. (我只是waitkey(1),所以这不是waitkey的问题)

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)

我有2个问题

  1. 我只是想知道是否有任何方法可以手动灰度与cvtColor一样快的图像.如果不是,你们知道如何优化上面的代码,以使灰度视频看起来更平滑.
  2. 以上只是灰度的一种方法. (r,g,b)=(r,g,b)/(((r + g + b)/3) 你们能告诉我有关彩色图像灰度的所有其他方法吗?
  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.

推荐答案

我可以告诉您:: at函数很慢.

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

我总是使用结构和指针,这是一个rgb示例:

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

像这样更改像素值(对于RGB图像):

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;

您可以轻松地将其转换为灰度问题.这样做的好处是,它的速度非常快,因为cv :: Mat图像的一条扫描线在内存中没有被分割,一条扫描线的像素在内存中彼此相邻.

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.

这篇关于opencv中的手动灰度太慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆