opencv 绘制单通道图片的直方图

来源:互联网 发布:海报设计软件手机版 编辑:程序博客网 时间:2024/06/11 20:52

1. [文件] hist_img.h

#ifndef HIST_IMG_H_INCLUDED#define HIST_IMG_H_INCLUDED#include <opencv\cv.h>#include <opencv\cxcore.h>#include <iostream>#define LOW_BOUND (0.f)#define HIGH_BOUND (255.f)#define BINS (10)#define BINWIDTH (20)/**-    Get a histogram image of the input image.    @param pImage an 1 channel image    @return Returns a histogram image-**/IplImage* HistImage(IplImage* pImage);#endif // HIST_IMG_H_INCLUDED

2. [文件] hist_img.cpp

#include "hist_img.h"using namespace std;IplImage* HistImage(IplImage* pImage){    if (!pImage)    {        cerr<<"The input image is NULL."<<endl;        return NULL;    }    if (1 != pImage->nChannels)    {        cerr<<"The input image's channels is not equal to 1."<<endl;        return NULL;    }    // create a histogram    int histSize = BINS;    float** range = new float*;    range[0] = new float[2];    range[0][0] = LOW_BOUND;    range[0][1] = HIGH_BOUND;    CvHistogram* pHist = cvCreateHist(1,&histSize,CV_HIST_ARRAY,range);    cvCalcHist(&pImage,pHist);    float fMaxValue = 0.f;    cvGetMinMaxHistValue(pHist,0,&fMaxValue,0,0);    // generate the histogram image    int height = 240;    int interval = cvRound(BINWIDTH * 2 / 5);    int width = histSize * BINWIDTH + (histSize - 1)*interval;    IplImage* pHistImg = cvCreateImage(cvSize(width,height),IPL_DEPTH_8U,3);    cvZero(pHistImg);    for (int i = 0;i < histSize;i++)    {        float fBinValue = cvQueryHistValue_1D(pHist,i);        int BinHeight = cvRound(fBinValue / fMaxValue * height);        CvScalar color = cvScalar(i*255/histSize,255,255,0);        CvPoint point1 = cvPoint(i*(BINWIDTH + interval),height);        CvPoint point2 = cvPoint(point1.x + BINWIDTH,height - BinHeight);        cvRectangle(pHistImg,point1,point2,color,-1,8,0);    }    cvReleaseHist(&pHist);    delete[] range[0];    delete range;    return pHistImg;}


原创粉丝点击