直方图操作
1、直方图均衡化
直方图均衡化api:
2、代码实现
#include <opencv2/opencv.hpp>
#include <iostream>
int main(int argc, char** argv)
{
Mat img = imread("G:/testpic/img.png");
if (img.empty())
{
printf("cannot load the image");
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", img);
//直方图均衡化
Mat gray, ehist;
cvtColor(img, gray, COLOR_BGR2GRAY);
equalizeHist(gray, ehist);
imshow("output", ehist);
waitKey(0);
return 0;
}
原图:
直方图均衡化:
3、直方图的计算
分离单通道
计算直方图
归一化:
normalize(InputArry src,InputOutputArray dst,double alpha=1,double beta=0,int norm_type=NORM_L2,int dtype=-1,InputArray mark=noArry())
归一化数据。该函数分为范围归一化与数据值归一化
参数说明
src 输入数组;
dst 输出数组,数组的大小和原数组一致;
alpha 1,用来规范值,2.规范范围,并且是下限;
beta 只用来规范范围并且是上限;//为0时则为值归一化,否则为范围归一化
norm_type 归一化选择的数学公式类型;
dtype 当为负,输出在大小深度通道数都等于输入,当为正,输出只在深度与输如不同,不同的地方游dtype决定;
mark 掩码。选择感兴趣区域,选定后只能对该区域进行操作。
4、直方图计算代码实现
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
Mat img = imread("G:/testpic/img.png");
if (!img.data)
{
printf("cannot load the image");
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", img);
//划分通道
Mat brg_planes;
split(img, bgr_planes);
//归一化
Mat b_hist, g_hist, r_hist;
int high = 512;
int wide = 400;
Mat histImage(wide, high, Scalar(255,255,255));
//归一化
normalize(bgr_planes[0], b_hist, 0, high, NORM_MINMAX, -1, Mat());
normalize(bgr_planes[1], g_hist, 0, high, NORM_MINMAX, -1, Mat());
normalize(bgr_planes[2], r_hist, 0, high, NORM_MINMAX, -1, Mat());
//直方图计算
int histsize = 256;
float range[] = {0, 256};
const float* histrange = {range};
calcHist(&bgr_planes[0], 1, 0, Mat(), b_list, 1, &histsize, &histrange, true, false);
calcHist(&bgr_planes[1], 1, 0, Mat(), g_list, 1, &histsize, &histrange, true, false);
clacHist(&bgr_planes[2], 1, 0, Mat(), r_list, 1, &histsize, &histrange, true, false);
//画线
bin_W = cvRound(wide / histsize);
for (size_t i = 1; i < histsize; i++)
{
line(histImage, Point((i-1)*bin_w, high - b_hist.at<float>(i-1)), Point((i)*bin_w, high - b_hist.at<float>(i)),
Scalar(255,0,0), -1, LINE_AA);
line(histImage, Point((i-1)*bin_w, high - g_hist.at<float>(i-1)), Point((i)*bin_w, high - g_hist.at<float>(i)),
Scalar(0,255,0), -1, LINE_AA);
line(histImage, Point((i-1)*bin_W, high - r_hist.at<float>(i-1)), Point((i)*bin_w, high - r_hist.at<float> (i)),Scalar(0,0,255), -1, LINE_AA);
}
imshow("output", histImage);
waitKey(0);
return 0;
}