OpenCV && C++ 07 - Histogram Equalization of a Color image with OpenCV

Code

/*
作者:郑大峰
时间:2019年09月20日
环境:OpenCV 4.1.1 + VS2017
内容:Histogram Equalization of a Color image with OpenCV
*/

#include "pch.h"
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main()
{
    Mat image = imread("15484.jpg");

    if (image.empty())
    {
        cout << "Could not open or find the image" << endl;
        cin.get();
        return -1;
    }

    //Convert the image from BGR to YCrCb color space
    Mat hist_equalized_image;
    cvtColor(image, hist_equalized_image, COLOR_BGR2YCrCb);

    //Split the image into 3 channels; Y, Cr and Cb channels respectively and store it in a std::vector
    vector<Mat> vec_channels;
    split(hist_equalized_image, vec_channels);

    //Equalize the histogram of only the Y channel 
    equalizeHist(vec_channels[0], vec_channels[0]);

    //Merge 3 channels in the vector to form the color image in YCrCB color space.
    merge(vec_channels, hist_equalized_image);

    //Convert the histogram equalized image from YCrCb to BGR color space again
    cvtColor(hist_equalized_image, hist_equalized_image, COLOR_YCrCb2BGR);

    //Define the names of windows
    String windowNameOfOriginalImage = "Original Image";
    String windowNameOfHistogramEqualized = "Histogram Equalized Color Image";

    // Create windows with the above names
    namedWindow(windowNameOfOriginalImage, WINDOW_NORMAL);
    namedWindow(windowNameOfHistogramEqualized, WINDOW_NORMAL);

    // Show images inside the created windows.
    imshow(windowNameOfOriginalImage, image);
    imshow(windowNameOfHistogramEqualized, hist_equalized_image);

    waitKey(0); // Wait for any key stroke

    destroyAllWindows(); //destroy all open windows

    return 0;
}

Result

从这个图片中,我们可以发现,原始图像在经过直方图均衡化之后,左侧偏暗的部分,稍稍变亮了,右侧偏亮的部分,稍稍变暗了。这就是直方图均衡化的作用了。

1370690-20190920180730670-1518197543.png

Explanation

//Convert the image from BGR to YCrCb color space
Mat hist_equalized_image;
cvtColor(image, hist_equalized_image, COLOR_BGR2YCrCb);

我们加载的图像是 BGR 颜色空间的,因为在该颜色空间下三个通道(蓝、绿、红)都存储了颜色信息,所以我们不能对他们进行直方图均衡化,否则会改变颜色。我们可以将图片的颜色空间改成 YCrCb ,在这个颜色空间下,Y 通道只存储灰度信息,而 Cr 和 Cb 通道存储颜色信息,所以我们可以仅对 Y 通道进行直方图均衡化,再转换成 BGR 颜色空间。

转载于:https://www.cnblogs.com/zdfffg/p/11558430.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值