本文主要是介绍庞峰Opencv学习(三)--灰度直方图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
灰度直方图是一个帮助分析图像很有力的工具吧,今天学习了下,一天不敲代码就生疏啊- -
灰度直方图这个程序主要有几个函数和结构体先说一下:
1. CreateHIst
CvHistogram* cvCreateHist( int dims, int* sizes, int type, float** ranges=NULL, int uniform=1 );
dims代表直方图是几维的,本程序是一个一维直方图,即bins只由x坐标索引
sizes 代表有多少个bins
type有两种类型一是稠密数组CV_HIST_ARRAY和稀疏数组CV_HIST_TREE,这里由于是一维直方图我们选择稠密数组
ranges代表了bins中值得取值范围,这里我们的灰度值为0-255,所以选取0-255
uniform归一化标识,默认为1,标识x方向被等分为sizes个bins
2. CalcHist
void cvCalcHist( IplImage** image, CvHistogram* hist, int accumulate=0, const CvArr* mask=NULL );
image为输入图像s
hist为直方图指针
这里需要注意如果要计算的图像是多通道时,可以用多个单通道图来表示
#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
#include <stdio.h>
IplImage* DisplayHist(CvHistogram* hist, float xscalar=1, float yscalar =1)
{
float maxHist=0;
cvGetMinMaxHistValue(hist, 0, &maxHist , 0 ,0);
IplImage* histimg = cvCreateImage(cvSize(256*xscalar,64*yscalar),8 ,1);
cvZero(histimg);
//取出直方图中的灰度值,并进行归一化处理
float currentVal=0;
float nextVal=0;
for (int i=0; i<255;i++)
{
currentVal = cvQueryHistValue_1D(hist,i);
nextVal = cvQueryHistValue_1D(hist,i+1);
CvPoint pt[4];
pt[1] = cvPoint(i*xscalar, 64*yscalar);
pt[2] = cvPoint((i+1)*xscalar, 64*yscalar);
pt[3] = cvPoint((i+1)*xscalar, (64-(nextVal/maxHist)*64)*yscalar);
pt[4] = cvPoint(i*xscalar, (64-(currentVal/maxHist)*64)*yscalar);
//填充凸多边形
int npts = 5;
CvPoint pts[5];
pts[0]=pt[1];
pts[1]=pt[2];
pts[2]=pt[3];
pts[3]=pt[4];
pts[4]=pt[1];
cvFillConvexPoly(histimg,pts,npts,cvScalar(255));//白色填充
}
return histimg;
}
void main()
{
IplImage* src = cvLoadImage("lena.jpg");
cvNamedWindow("src");
cvShowImage("src",src);
CvHistogram* hist;
int sizes = 256;//有256个bins
int dims = 1;//一维直方图
float range[] = {0,255}; //灰度图深度0-255
float* ranges[] = {range};
hist = cvCreateHist(dims, &sizes, CV_HIST_ARRAY/*稠密数组*/,ranges,1);
cvClearHist(hist);
IplImage* bimg = cvCreateImage(cvGetSize(src), 8 , 1);
IplImage* gimg = cvCreateImage(cvGetSize(src), 8 , 1);
IplImage* rimg = cvCreateImage(cvGetSize(src), 8 , 1);
cvSplit(src,bimg,gimg,rimg,NULL);
cvCalcHist(&bimg,hist,0,0);
IplImage *bhist = DisplayHist(hist);
cvNamedWindow("b");
cvShowImage("b",bhist);
cvClearHist(hist);
cvCalcHist(&gimg,hist,0,0);
IplImage *ghist = DisplayHist(hist);
cvNamedWindow("g");
cvShowImage("g",ghist);
cvClearHist(hist);
cvCalcHist(&rimg,hist,0,0);
IplImage *rhist = DisplayHist(hist);
cvNamedWindow("r");
cvShowImage("r",rhist);
cvClearHist(hist);
cvWaitKey(0);
cvReleaseImage(&src);
cvReleaseImage(&bimg);
cvReleaseImage(&gimg);
cvReleaseImage(&rimg);
}
这篇关于庞峰Opencv学习(三)--灰度直方图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!