基于open cv中RGB直方图绘制及图像处理

@[TOC]基于open cv中RGB直方图绘制及图像处理
通过大三一年对计算机视觉与模式识别的学习,对opencv有了更深一层的理解与认识,
以下是配置完成opencv之后RGB直方图绘制及图像处理的步骤及代码。
(步骤简单分为图像导入,RGB直方图绘制,及对图像进行包括腐蚀、模糊处理、canny边缘检测算法的处理)
以下是代码实现:
#include
#include
#include
#include
#include //图像处理头文件

using namespace cv;

int main()
{
// 读入一张图片(poyanghu缩小图)
Mat img = imread(“C:\Pictures\Saved Pictures\7444.jpg_wh300.jpg”);
imshow(“原图”, img);
//绘制RGB三色直方图
//1 参数准备
int bins = 256;
int hist_size[] = { bins };
float range[] = { 0,256 };
const float* ranges[] = { range };
MatND redhist, greenhist, bluehist;
int channels_r[] = { 0 };

//进行直方图的计算(包括红色分量、绿色分量、蓝色分量)
calcHist(&img, 1, channels_r, Mat(),//不使用掩膜
redhist, 1, hist_size, ranges,
true, false);

int channels_g[] = { 1 };
calcHist(&img, 1, channels_g, Mat(),//不使用掩膜
greenhist, 1, hist_size, ranges,
true, false);

int channels_b[] = { 2 };
calcHist(&img, 1, channels_b, Mat(),//不使用掩膜
bluehist, 1, hist_size, ranges,
true,
false);
//-----------------------------------绘制出三色直方图------------------------------------------
//参数准备
double maxvalue_red, maxvalue_green, maxvalue_blue;
minMaxIdx(redhist, 0, &maxvalue_red, 0, 0);
minMaxIdx(greenhist, 0, &maxvalue_green, 0, 0);
minMaxIdx(bluehist, 0, &maxvalue_blue, 0, 0);
int scale = 1;
int hisheight = 256;
Mat hisimage = Mat::zeros(hisheight, bins * 3, CV_8UC3);

//正式开始绘制
for (int i = 1; i < bins; i++)
{
//参数准备
float binvalue_red = redhist.at(i);
float binvalue_green = greenhist.at(i);
float binvalue_blue = bluehist.at(i);

int intensity_red =
cvRound(binvalue_redhisheight / maxvalue_red); //要绘制的高度
int intensity_green =
cvRound(binvalue_green
hisheight / maxvalue_green);
int intensity_blue=
cvRound(binvalue_bluehisheight / maxvalue_blue);
//绘制红色分量的直方图
rectangle(hisimage, Point(i
scale, hisheight - 1), Point((i + 1)*scale - 1, hisheight - intensity_red), Scalar(255, 0, 0));

//绘制绿色分量的直方图
rectangle(hisimage, Point((i+bins)*scale, hisheight - 1), Point((i+bins + 1)*scale - 1, hisheight - intensity_green), Scalar( 0, 255, 0));

//绘制蓝色分量的直方图
rectangle(hisimage, Point((i+bins*2)scale, hisheight - 1), Point((i+bins2 + 1)*scale - 1, hisheight - intensity_blue), Scalar(0,0,255));
}

//在窗口中显示出绘制好的直方图
imshow(“图像的RGB直方图”,hisimage);
waitKey(5);

//进行图像腐蚀操作
Mat element = getStructuringElement(MORPH_RECT, Size(15, 15));
Mat dstimage1;
Mat dstimage2;
erode(img, dstimage1, element);
//进行均值滤波图像模糊操作
blur(img, dstimage2, Size(7, 7));
//进行canny边缘检测
Mat edge, grayimage; //参数定义
//将原图像转换为灰度图像
cvtColor(img, grayimage, CV_BGR2GRAY);
blur(grayimage, edge, Size(3, 3)); //先是用3*3内核来降噪
//运行canny算子
Canny(edge, edge, 3, 9, 3);
// 在窗口中显示图片
imshow(“原图”, img);
//显示效果图
imshow(“效果图-腐蚀操作”,dstimage1);
imshow(“效果图-模糊操作”, dstimage2);
imshow(“效果图-canny边缘监测操作”, edge);

// 等待60000ms后窗口自动关闭
waitKey(60000);
return 0;
}

你可能感兴趣的:(基于open cv中RGB直方图绘制及图像处理)