RGB到实验室的转换

时间:2019-04-29 12:13:06

标签: c++ opencv

我正在尝试将图像从RGB转换为Lab。

我使用的数学公式来自此处:https://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor

double fun(double t) {
    if (t > 0.008856) return pow(t, (1 / 3));
    else return ((7.787 * t) + (16 / 116));
}

void convertRGBtoLab() {
    char fname[MAX_PATH];
    openFileDlg(fname);

    Mat src = imread(fname, CV_LOAD_IMAGE_COLOR);
    Mat lab(src.rows, src.cols, src.type());
    double X, Y, Z, a, b, L;
    double B, G, R;

    for (int i = 0; i < src.rows; i++) {
        for (int j = 0; j < src.cols; j++) {
            B = src.at<Vec3b>(i, j)[0];
            G = src.at<Vec3b>(i, j)[1];
            R = src.at<Vec3b>(i, j)[2];

            R /= 255.0;
            B /= 255.0;
            G /= 255.0;

            X = 0.412453 * R + 0.357580 * G + 0.180423 * B;
            Y = 0.212671 * R + 0.715160 * G + 0.072169 * B;
            Z = 0.019334 * R + 0.119193 * G + 0.950227 * B;

            X = X / 95.0456;
            Y = Y / 100.0;
            Z = Z / 108.8754;

            if (Y > 0.008856) L = 116 * pow(Y, 1 / 3) - 16;
            else L = 903.3*Y;

            a = 500 * (fun(X) - fun(Y)) + 128;
            b = 200 * (fun(Y) - fun(Z)) + 128;

            lab.at<Vec3b>(i, j)[0] = b + 128;
            lab.at<Vec3b>(i, j)[1] = a + 128;
            lab.at<Vec3b>(i, j)[2] = L * 2.55;
        }
    }

    imshow("RGB", src);
    imshow("Lab", lab);
    Mat cvmat(src.rows, src.cols, src.type());
    cvtColor(src, cvmat, CV_RGB2Lab, 0);
    imshow("Correct", cvmat);
    waitKey(0);
}

我得到的结果(图像)与cvtColor函数获得的图像完全不同。

谢谢。

0 个答案:

没有答案