OpenCV:绘制图像的BGR三通道直方图

#include 
#include 
#include 

IplImage* DrawHistogram(CvHistogram* hist, float scaleX = 1, float scaleY = 1){

    float histMax = 0;
    cvGetMinMaxHistValue(hist, 0, &histMax, 0, 0); //获取直方图的最大值

    IplImage* imageHist = cvCreateImage(cvSize(256*scaleX, 64*scaleY), 8, 1);
    cvZero(imageHist);

    for(int i = 0; i < 255; ++i){

        //查询直方图每个单位的x值对应的y值
        float histValue = cvQueryHistValue_1D(hist, i);
        float nextValue = cvQueryHistValue_1D(hist, i+1);

        CvPoint pt1 = cvPoint(i* scaleX, 64*scaleY);
        CvPoint pt2 = cvPoint((i+1)*scaleX, 64*scaleY);
        CvPoint pt3 = cvPoint((i+1)*scaleX, 64*scaleY - (nextValue/histMax)*64*scaleY);
        CvPoint pt4 = cvPoint(i*scaleX, 64*scaleY - (histValue/histMax)*64*scaleY);

        int numPts = 5;
        CvPoint pts[5];
        pts[0] = pt1;
        pts[1] = pt2;
        pts[2] = pt3;
        pts[3] = pt4;
        pts[4] = pt1;

        //通道直方图为连续的,所以填充两两相邻直方柱之间区域
        cvFillConvexPoly(imageHist, pts, numPts, cvScalar(255));

    }
    return imageHist;
}
int main(int argc, char** argv){

    IplImage *src = cvLoadImage(".\\test1.png");
    cvNamedWindow("src");
    cvShowImage("src", src);

    int dims = 1;
    int size = 256;
    float range[] = {0, 255};
    float *ranges[] = {range};
    CvHistogram * hist;
    hist = cvCreateHist(dims, &size, CV_HIST_ARRAY, ranges, 1); //创建直方图
    cvClearHist(hist);	//清除直方图

    IplImage* imageRed = cvCreateImage(cvGetSize(src), 8, 1);
    IplImage* imageGreen = cvCreateImage(cvGetSize(src), 8, 1);
    IplImage* imageBlue = cvCreateImage(cvGetSize(src), 8, 1);

    //将源图像分割出RGB三通道
    cvSplit(src, imageBlue, imageGreen, imageRed, NULL);

    cvCalcHist(&imageBlue, hist, 0, 0); //根据Blue通道计算直方图
    IplImage* histBlue = DrawHistogram(hist, 1, 1);
    cvClearHist(hist);

    cvCalcHist(&imageGreen, hist, 0, 0);
    IplImage* histGreen = DrawHistogram(hist, 1, 1);
    cvClearHist(hist);

    cvCalcHist(&imageRed, hist, 0, 0);
    IplImage* histRed = DrawHistogram(hist, 1, 1);
    cvClearHist(hist);

    cvNamedWindow("B");
    cvNamedWindow("G");
    cvNamedWindow("R");

    cvShowImage("B", histBlue);
    cvShowImage("G", histGreen);
    cvShowImage("R", histRed);

    cvWaitKey(0);
}

运行结果:

OpenCV:绘制图像的BGR三通道直方图_第1张图片



你可能感兴趣的:(OpenCV,OpenCV)