请教显示彩色图像的RGB直方图

2024-12-21 12:24:29
推荐回答(1个)
回答1:

仅供参考
#include
#include
#include
using namespace std;

int main( int argc, char** argv )
{
IplImage * src;
// char *filename = argc==3?argv[2]: (char*)"1.jpg";
// src = cvLoadImage(filename, 1);

if(argc==2 &&(src = cvLoadImage(argv[1], 1)) != 0)
{
IplImage* rgb_r = cvCreateImage(cvGetSize(src), 8, 1);
IplImage* rgb_g = cvCreateImage(cvGetSize(src), 8, 1);
IplImage* rgb_b = cvCreateImage(cvGetSize(src), 8, 1);
IplImage* planes[] = {rgb_r, rgb_g, rgb_b};

int r_bin = 32, g_bin = 32, b_bin = 32;
int hist_size[] = {r_bin, g_bin, b_bin};

float r_ranges[] = {0, 255};
float g_ranges[] = {0, 255};
float b_ranges[] = {0, 255};
float* ranges[] = {r_ranges, g_ranges, b_ranges};
cvCvtPixToPlane(src, rgb_r, rgb_g, rgb_b, 0);

/* cvNamedWindow( "rgb_r", 0);
cvResizeWindow("rgb_r", 400, 350);
cvShowImage( "rgb_r", rgb_r );

cvNamedWindow( "rgb_b", 0);
cvResizeWindow("rgb_b", 400, 350);
cvShowImage( "rgb_b", rgb_b );

cvNamedWindow( "rgb_g", 0);
cvResizeWindow("rgb_g", 400, 350);
cvShowImage( "rgb_g", rgb_g);
*/
CvHistogram *hist;
hist = cvCreateHist(3, hist_size, CV_HIST_ARRAY, ranges, 1);
cvCalcHist(planes, hist, 0, 0);

float max_value;
cvGetMinMaxHistValue(hist, 0, &max_value, 0, 0);

int height = 260;
int width = (r_bin*g_bin*b_bin*6);
IplImage* hist_img = cvCreateImage(cvGetSize(src), 8, 3);
cvZero(hist_img);
int bin_w = width/(r_bin*g_bin*b_bin);

for(int r_c=0; r_c {
for(int g_c=0; g_c {
for(int b_c=0; b_c {
int i = r_c*g_bin + g_c*b_bin + b_c;
float bin_val = cvQueryHistValue_3D(hist, r_c, g_c, b_c);
int intensity = cvRound(bin_val*height/max_value);
CvScalar color= CV_RGB(r_c*255/r_bin, g_c*255/g_bin, b_c*255/b_bin);
if(intensity > 50)
{
printf("(r_c=%d, g_c=%d, b_c=%d) : (r=%d, g=%d, b=%d) intensity = %d\n", r_c, g_c, b_c,
color.val[2], color.val[1], color.val[0], intensity);
}
cvRectangle(hist_img, cvPoint(i*bin_w, height), cvPoint((i+1)*bin_w, height-intensity),
color, -1, 8, 0);
}
}
}
cvNamedWindow( "Source", 0);
cvResizeWindow("Source", 400, 350);
cvShowImage( "Source", src );

cvNamedWindow( "RGB Histogram", 0 );
cvResizeWindow("RGB Histogram", 1024, 350);
cvShowImage( "RGB Histogram", hist_img );

cvWaitKey(0);
}

return 0;
}