OpenCV EqualizeHist() 从彩色图像创建黑白图像

OpenCV EqualizeHist() creates black and white image from colour image

编辑:
pointer/reference 用法可能是错误的,但是如果任何 cv::Mat 变量在均衡块之外声明(在我的例子中,在 class 它们的定义中,也会发生这种 OpenCV 行为是成员).

我在代码中使用的逻辑与 here, yet I get a weird black and white image as the result, see original and result 中描述的逻辑相同。我在 Visual Studio 2017 15.8.8 中使用 OpenCV 4.0.0 和 C++。以前的声明:

cv::Mat *equalized_image;
cv::Mat &original_image = cv::Mat(cv::imread(file_path));

其中 file_path 是一个 std::string。均衡:

if (original_image.channels() >= 3) {
    // convert to YCrCb colourspace for luminance channel
    cv::cvtColor(original_image, *equalized_image, cv::COLOR_BGR2YCrCb);

    // split image by channels
    std::vector<cv::Mat> channels;
    cv::split(*equalized_image, channels);

    // equalize only the histogram of the luminance channel
    cv::equalizeHist(channels[0], channels[0]);

    // merge back
    cv::merge(channels, *equalized_image);

    // convert back to BGR colourspace
    cv::Mat result;
    cv::cvtColor(*equalized_image, result, cv::COLOR_YCrCb2BGR);

    cv::namedWindow("Equalized");
    cv::imshow("Equalized", result);
}

我很惊讶你的代码可以编译。您使用的逻辑很好,但是您编写的指针 (*equalized_image) 和引用 (&original_image) 令人困惑。如果您 运行 处于发布模式,它可以做一些有趣的事情来初始化内存并使事情正常进行。始终首先在调试模式下检查您的代码。

将您的代码更改为此,它应该会按预期工作:

cv::Mat equalized_image;
cv::Mat original_image = cv::imread(file_path);

// convert to YCrCb colourspace for luminance channel
cv::cvtColor(original_image, equalized_image, cv::COLOR_BGR2YCrCb);

// split image by channels
std::vector<cv::Mat> channels;
cv::split(equalized_image, channels);

// equalize only the histogram of the luminance channel
cv::equalizeHist(channels[0], channels[0]);

// merge back
cv::merge(channels, equalized_image);

// convert back to BGR colourspace
cv::Mat result;
cv::cvtColor(equalized_image, result, cv::COLOR_YCrCb2BGR);

cv::namedWindow("Equalized");
cv::imshow("Equalized", result);
waitKey(0);