C和opencv实现图像显示图像的直方图,使用IplImage
时间: 2023-05-30 18:04:53 浏览: 160
以下是C和OpenCV实现图像显示图像直方图的示例代码,使用IplImage:
```
#include <cv.h>
#include <highgui.h>
int main(int argc, char** argv)
{
// Load image
IplImage* img = cvLoadImage(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
// Create histogram
int histo[256] = {0};
for (int i = 0; i < img->height; i++) {
uchar* row = (uchar*) img->imageData + i * img->widthStep;
for (int j = 0; j < img->width; j++) {
histo[row[j]]++;
}
}
// Find histogram max value
int max = 0;
for (int i = 0; i < 256; i++) {
if (histo[i] > max) {
max = histo[i];
}
}
// Create histogram image
int imgWidth = 256, imgHeight = 200;
IplImage* histImg = cvCreateImage(cvSize(imgWidth, imgHeight), IPL_DEPTH_8U, 1);
cvZero(histImg);
for (int i = 0; i < 256; i++) {
int value = cvRound(histo[i] * (imgHeight - 10) / (float) max);
cvLine(histImg, cvPoint(i, imgHeight - 5), cvPoint(i, imgHeight - value - 5), cvScalar(255));
}
// Show image and histogram
cvNamedWindow("Image", CV_WINDOW_AUTOSIZE);
cvNamedWindow("Histogram", CV_WINDOW_AUTOSIZE);
cvShowImage("Image", img);
cvShowImage("Histogram", histImg);
cvWaitKey(0);
// Release memory
cvReleaseImage(&img);
cvReleaseImage(&histImg);
return 0;
}
```
该代码加载一张灰度图像,计算其直方图并显示在一个单独的窗口中。直方图显示为灰度图像,横轴为像素强度,纵轴为像素数量。注意,直方图显示的最大值是直方图中像素数量的最大值,而不是255。
阅读全文