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

mac2022-06-30  17

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

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

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

最新回复(0)