Hi. I have implemented a little function to convert CV_8UC3 (bgr) to CV_8UC1 grayscale using formula provided with cv::cvtColor() docs : GRAY = 0.114 * B + 0.587f *G + 0.299f * R
Though output of my func is quite similar to one of cv::cvtColor(BGR2Gray), when checking each pixel's value in loop discovers lots of bad pixels. What is wrong ?
My function is below:
void bgr2gray(cv::Mat& src, cv::Mat& dst) { CV_Assert(!src.empty());
int width = src.cols;
int height = src.rows;
int channels = src.channels();
CV_Assert(src.channels() == 3 && dst.channels() == 1);
CV_Assert(width == dst.cols && height == dst.rows);
CV_Assert(src.isContinuous() && dst.isContinuous());
// src.isContinious() && dst.isContinious()
width *= height;
height = 1;
uchar* p_src;
uchar* p_dst;
for (int i = 0; i < height; i++) {
p_src = src.ptr<uchar>(i);
p_dst = dst.ptr<uchar>(i);
for (int j = 0; j < width * channels; j += 3) {
float d_gray(0.114F * p_src[j] + 0.587f * p_src[j + 1] + 0.299f * p_src[j + 2]);
uchar gray = (uchar)d_gray;
if (gray - d_gray >= 0.5f)
gray += 1;
p_dst[j / 3] = gray;
}
}
}