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

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值