要點:
1、讀取攝像頭
2、從一副彩色圖像中分離出R、G、B三個通道(cvSplit)
3. 分別對每個通道圖像創建直方圖,並顯示
源碼如下:
// Camera_Capture_Histogram.cpp : Defines the entry point for the console application.
//author: JarvisChu
//date: 2012-1-14
#include "stdafx.h"
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace std;
const char* pstrSrcWnd = "Src";
const char* pstrBHistWnd = "b plane";
const char* pstrGHistWnd = "g plane";
const char* pstrRHistWnd = "r plane";
//計算和繪製直方圖(R,G,B)
/* img 通道圖像
* hist_img: 直方圖的繪圖圖像
* pstrWndName: 繪圖窗口
*/
void draw_histogram(IplImage* img,IplImage* hist_img,const char* pstrWndName)
{
CvHistogram* hist = NULL;
int bin_count = 256;
float range[] = {0,255};
float* ranges[]={range};
hist = cvCreateHist(1, //一維
&bin_count, //每一維上bin(直方柱)的個數, 此處爲 256 【由上述兩個參數,函數就會創建一個1*256的矩陣】
CV_HIST_ARRAY,
ranges,
1);
cvClearHist(hist); //防止初始化時有其它數據,先清理一下
cvCalcHist(&img,hist,0,0);
//得到直方圖的最值及標號
float min,max;
int min_idx,max_idx;
cvGetMinMaxHistValue(hist,&min,&max,&min_idx,&max_idx);
//cout<<"min: "<<min<<" max:"<<max<<endl;
if(max == 0) {cout<<"max =0 err!"<<endl;max = 100;}
//縮放直方圖的大小,和圖像相適應
cvScale(hist->bins,hist->bins,((double)hist_img->height)/max,0);
//設置所有的直方圖的數值爲255
cvSet(hist_img,cvScalarAll(255),0);
// 平均每個直放柱的寬度
int bin_w=cvRound((double)hist_img->width/bin_count);
//畫直方圖
for(int i=0;i<bin_count;i++)
{
cvRectangle(hist_img,
cvPoint(i*bin_w,hist_img->height), //左下角的點(i*bin_w,height)
cvPoint((i+1)*bin_w, hist_img->height-cvRound(cvGetReal1D(hist->bins,i))),//右上角的點((i+1)*bin_w,圖像高度-直方柱的高度)
cvScalarAll(0),
-1,
8,
0);
}
//顯示直方圖
cvShowImage(pstrWndName,hist_img);
}
int _tmain(int argc, _TCHAR* argv[])
{
//創建窗口
cvNamedWindow(pstrSrcWnd,1);
cvNamedWindow(pstrBHistWnd,1);
cvNamedWindow(pstrGHistWnd,1);
cvNamedWindow(pstrRHistWnd,1);
//讀取攝像頭
CvCapture* capture = cvCreateCameraCapture(-1);
if(!capture) cout<<"無法打開攝像頭"<<endl;
//讀取一幀數據以獲取參數
IplImage* frame = NULL;
frame = cvQueryFrame(capture);
//B G R 通道
CvSize img_size;img_size.width = frame->width;img_size.height = frame->height;
IplImage* b = cvCreateImage(img_size,8,1);
IplImage* g = cvCreateImage(img_size,8,1);
IplImage* r = cvCreateImage(img_size,8,1);
//直方圖
CvSize size;size.width = 320;size.height = 200;
IplImage* b_hist_img = cvCreateImage(size,8,1);
IplImage* g_hist_img = cvCreateImage(size,8,1);
IplImage* r_hist_img = cvCreateImage(size,8,1);
while(1)
{
frame = cvQueryFrame(capture);
if(!frame) break;
//分割BGR通道
cvSplit(frame,b,g,r,0);
//顯示攝像頭圖像
cvShowImage(pstrSrcWnd,frame);
//繪製直方圖
draw_histogram(b,b_hist_img,pstrBHistWnd);
draw_histogram(g,g_hist_img,pstrGHistWnd);
draw_histogram(r,r_hist_img,pstrRHistWnd);
char c = cvWaitKey(330);
if(c == 27) break;
}
cvReleaseImage(&frame);
cvReleaseImage(&b);
cvReleaseImage(&g);
cvReleaseImage(&r);
cvReleaseImage(&b);
cvReleaseImage(&g);
cvReleaseImage(&r);
cvDestroyAllWindows();
return 0;
}
效果如下: