Ask Your Question
2

bgr image grayscale

asked 2013-11-14 05:46:56 -0600

updated 2013-11-14 05:54:03 -0600

I want to develop some color to grayscale algorithms in order to get an idea about how important a grayscale algorithm could be for feature extraction methods (lbp, hog, ...) and object recognition methods.

So, to start, I implemented a simple test algorithm in order to implement opencv grayscale conversion cvtcolor opencv. My implementation is as follows:

/// void cvtColor2(cv::InputArray _src, cv::OutputArray _dst, int code, int dstCn=0);
/// code and dstCn are not used by the moment but i included them as the original cvtColor method
void cvtColor2(cv::InputArray _src, cv::OutputArray _dst, int code, int dstCn){
//CV_BGR2GRAY: Y <-- 0.299*R + 0.587*G + 0.114*B
static const float coeffs0[] = { 0.299f, 0.587f, 0.114f };

Mat src = _src.getMat();
_dst.create(src.size(), CV_8UC1);
Mat dst = _dst.getMat();

for( int i = 0; i < src.rows; i++ )
{
    for( int j = 0; j < src.cols; j++ )
    {
        Vec3b scalarColor = src.at<Vec3b>(i,j);
        dst.at<uchar>(i,j) = scalarColor.val[0]*coeffs0[2] + scalarColor.val[1]*coeffs0[1] + scalarColor.val[2]*coeffs0[0];
    }
}   
}

Then, i test this algorithm:

Mat image = imread("....");
Mat grayImage, grayImage2;
cvtColor(image,grayImage,CV_BGR2GRAY);
cvtColor2(image,grayImage2,CV_BGR2GRAY);

I don't get the same result. For some pixels, there is one intensity pixel difference between cvtColor2 and cvtColor. I saw this other question HERE but I didn't find a solution. I don't know where the error is. Any help will be appreciated. Thanks in advance

edit retag flag offensive close merge delete

Comments

1 answer

Sort by ยป oldest newest most voted
2

answered 2013-11-14 08:10:27 -0600

updated 2013-11-14 08:22:49 -0600

saturate_cast is needed:

dst.at<uchar>(i,j) = saturate_cast<uchar>(scalarColor.val[0]*coeffs0[2] + scalarColor.val[1]*coeffs0[1] + scalarColor.val[2]*coeffs0[0]);

see saturation-arithmetics

edit flag offensive delete link more

Question Tools

Stats

Asked: 2013-11-14 05:46:56 -0600

Seen: 781 times

Last updated: Nov 14 '13