C和opencv实现图像显示图像的直方图
时间: 2023-06-01 15:03:00 浏览: 87
在C语言中,可以使用OpenCV库来实现图像的直方图显示。具体步骤如下:
1. 加载图像
```c
IplImage* img = cvLoadImage("image.jpg", CV_LOAD_IMAGE_GRAYSCALE);
```
2. 计算直方图
```c
int histSize = 256;
float range[] = {0, 256};
const float* histRange = {range};
CvHistogram* hist = cvCreateHist(1, &histSize, CV_HIST_ARRAY, &histRange, 1);
cvCalcHist(&img, hist, 0, NULL);
cvNormalizeHist(hist, 1.0);
```
3. 绘制直方图
```c
int histHeight = 256;
int histWidth = 512;
int binWidth = cvRound((double)histWidth/histSize);
IplImage* histImg = cvCreateImage(cvSize(histWidth, histHeight), 8, 1);
cvSet(histImg, cvScalarAll(255));
float* histData = cvGetHistValueData(hist);
for (int i = 0; i < histSize; i++)
{
int val = cvRound(histData[i]*histHeight);
cvRectangle(histImg, cvPoint(i*binWidth, histHeight),
cvPoint((i+1)*binWidth, histHeight-val),
cvScalarAll(0), -1);
}
cvShowImage("Histogram", histImg);
```
完整代码如下:
```c
#include <cv.h>
#include <highgui.h>
int main()
{
IplImage* img = cvLoadImage("image.jpg", CV_LOAD_IMAGE_GRAYSCALE);
int histSize = 256;
float range[] = {0, 256};
const float* histRange = {range};
CvHistogram* hist = cvCreateHist(1, &histSize, CV_HIST_ARRAY, &histRange, 1);
cvCalcHist(&img, hist, 0, NULL);
cvNormalizeHist(hist, 1.0);
int histHeight = 256;
int histWidth = 512;
int binWidth = cvRound((double)histWidth/histSize);
IplImage* histImg = cvCreateImage(cvSize(histWidth, histHeight), 8, 1);
cvSet(histImg, cvScalarAll(255));
float* histData = cvGetHistValueData(hist);
for (int i = 0; i < histSize; i++)
{
int val = cvRound(histData[i]*histHeight);
cvRectangle(histImg, cvPoint(i*binWidth, histHeight),
cvPoint((i+1)*binWidth, histHeight-val),
cvScalarAll(0), -1);
}
cvShowImage("Histogram", histImg);
cvWaitKey(0);
cvReleaseImage(&img);
cvReleaseImage(&histImg);
cvReleaseHist(&hist);
return 0;
}
```
阅读全文