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

时间:2018-11-03 22:22:46

标签: c++ visual-studio opencv histogram equalizer

编辑:
指针/引用的用法可能是错误的,但是,如果任何cv :: Mat变量在均衡块外声明(在我的情况下,它们是其成员的类的定义),则也会发生OpenCV行为。

我在代码中使用的逻辑与所描述的here相同,但是结果却得到了奇怪的黑白图像,请参见originalresult。我在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);
}

1 个答案:

答案 0 :(得分:0)

我很惊讶您的代码被编译。您使用的逻辑很好,但是您编码的指针(* 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);