#include <opencv2/opencv.hpp>
#include<vector>
using namespace std;
using namespace cv;
//绘制直方图
void showHistCallback(Mat img)
{
vector<Mat> bgr;
split(img, bgr);
int numbins = 256;
float range[] = { 0, 256 };
const float* histRange = { range };
Mat b_hist, g_hist, r_hist;
calcHist(&bgr[0], 1, 0, Mat(), b_hist, 1, &numbins, &histRange);
calcHist(&bgr[1], 1, 0, Mat(), g_hist, 1, &numbins, &histRange);
calcHist(&bgr[2], 1, 0, Mat(), r_hist, 1, &numbins, &histRange);
int width = 512;
int height = 256;
Mat histImage(height, width, CV_8UC3, Scalar(20, 20, 20));
normalize(b_hist, b_hist, 0, height, NORM_MINMAX);
normalize(g_hist, g_hist, 0, height, NORM_MINMAX);
normalize(r_hist, r_hist, 0, height, NORM_MINMAX);
int binStep = cvRound((float)width / (float)numbins);
for (int i = 1; i < numbins; i++)
{
line(histImage, Point(binStep*(i - 1), height - cvRound(b_hist.at<float>(i - 1))),
Point(binStep * (i), height - cvRound(b_hist.at<float>(i))), Scalar(255, 0, 0));
line(histImage, Point(binStep*(i - 1), height - cvRound(g_hist.at<float>(i - 1))),
Point(binStep * (i), height - cvRound(g_hist.at<float>(i))), Scalar(0, 255, 0));
line(histImage, Point(binStep*(i - 1), height - cvRound(r_hist.at<float>(i - 1))),
Point(binStep * (i), height - cvRound(r_hist.at<float>(i))), Scalar(0, 0, 255));
}
imshow("histImage", histImage);
}
//图像色彩均衡化
void equalizeCallback(Mat img)
{
Mat equalize;
Mat ycrcb;
cvtColor(img, ycrcb, COLOR_BGR2YCrCb);
vector<Mat> channels;
split(ycrcb, channels);
//只均衡Y通道
equalizeHist(channels[0], channels[0]);
merge(channels, ycrcb);
cvtColor(ycrcb, equalize, COLOR_YCrCb2BGR);
imshow("equlized", equalize);
}
//LOMO效果
void lomoCallBack(Mat img)
{
Mat lomo;
const double expeonential_e = exp(1.0);
Mat lut(1, 256, CV_8UC1);
for (int i = 0; i < 256; i++)
{
float x = (float)i / 256.0;
lut.at<uchar>(i) = cvRound(256 * (1 / (1 + pow(expeonential_e, -((x - 0.5) / 0.1)))));
}
//只对红色通道应用值变换
vector<Mat> bgr;
split(img, bgr);
//LUT(bgr[0], lut, bgr[0]);
//LUT(bgr[1], lut, bgr[1]);
LUT(bgr[2], lut, bgr[2]);
merge(bgr, lomo);
//创建昏暗的图像
Mat halo(img.rows, img.cols, CV_32FC3, Scalar(0.3, 0.3, 0.3));
//创建圆
circle(halo, Point(img.cols / 2, img.rows / 2), img.cols / 3, Scalar(1, 1, 1), -1);
blur(halo, halo, Size(img.cols / 3, img.cols / 3));
//将结果转为浮点型
Mat lomof;
lomo.convertTo(lomof, CV_32FC3);
//将结果和halo相乘
multiply(lomof, halo, lomof);
//转为8位图像
lomof.convertTo(lomo, CV_8UC3);
imshow("lomo", lomo);
}
int main()
{
Mat src = imread("1.jpg",1);
imshow("src", src);
showHistCallback(src);
equalizeCallback(src);
lomoCallBack(src);
waitKey(0);
return 0;
}
深入理解直方图
最新推荐文章于 2021-08-17 09:29:39 发布