In opencv, RGB is converted to gray, and gray is converted to RGB. Why are the colors different?

#include <opencv2/opencv.hpp>

int main()
{
    // 读取RGB图像
    cv::Mat rgbImage = cv::imread("image.jpg");

    // 将RGB图像转换为灰度图像
    cv::Mat grayImage;
    cv::cvtColor(rgbImage, grayImage, cv::COLOR_RGB2GRAY);

    // 将灰度图像转换回RGB图像
    cv::Mat rgbImage2;
    cv::cvtColor(grayImage, rgbImage2, cv::COLOR_GRAY2RGB);

    // 输出结果
    cv::imshow("RGB Image", rgbImage);
    cv::imshow("Gray Image", grayImage);
    cv::imshow("RGB Image 2", rgbImage2);
    cv::waitKey(0);

    return 0;
}

When converting an RGB image to a grayscale image, color information is lost because grayscale images only contain brightness information and not color information. Grayscale images have only one channel per pixel, representing the brightness level, rather than a combination of red, green, and blue channels.

When you convert the grayscale image back to an RGB image again, OpenCV will map each grayscale pixel value back into RGB space. Since there is only one channel of brightness value in a grayscale image, all channels in an RGB image are assigned the same value. This way, the image looks like a grayscale image, but in reality it just uses the same grayscale value on each channel.

If you want to convert a grayscale image back to the original RGB image and keep the color unchanged, it's not possible because the color information has been lost when converting the RGB image to grayscale. Grayscale images only contain brightness information, not the red, green, and blue channel values ​​of the original image. Therefore, the original RGB colors cannot be recovered from grayscale images.

If you want to preserve color information during conversion, you need to use other color spaces, such as HSV or Lab, which can preserve more color information. However, even if other color spaces are used, the original RGB colors cannot be completely restored, because the conversion of color information always introduces a certain loss.

Guess you like

Origin blog.csdn.net/pingchangxin_6/article/details/131658057