C和opencv实现图像显示图像的蓝色的直方图,使用IplImage
时间: 2023-05-30 18:05:06 浏览: 178
直方图均衡化,直方图均衡化原理,Visual C++
以下是使用C和OpenCV实现图像显示图像的蓝色直方图的示例代码:
```c
#include <cv.h>
#include <highgui.h>
int main(int argc, char** argv)
{
// 读取图像
IplImage* img = cvLoadImage(argv[1], CV_LOAD_IMAGE_COLOR);
// 分离通道
IplImage* blue = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1);
cvSplit(img, blue, NULL, NULL, NULL);
// 计算直方图
CvHistogram* hist;
int hist_size = 256;
float range[] = {0, 256};
float* ranges[] = {range};
hist = cvCreateHist(1, &hist_size, CV_HIST_ARRAY, ranges, 1);
cvCalcHist(&blue, hist, 0, NULL);
// 获取最大值
float max_value = 0;
cvGetMinMaxHistValue(hist, NULL, &max_value, NULL, NULL);
// 创建画布
int width = 512, height = 400;
IplImage* canvas = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
cvZero(canvas);
// 绘制直方图
int bin_width = cvRound((double) width / hist_size);
for (int i = 0; i < hist_size; i++) {
float bin_value = cvGetReal1D(hist->bins, i);
int intensity = cvRound(bin_value * height / max_value);
cvRectangle(canvas, cvPoint(i * bin_width, height), cvPoint((i + 1) * bin_width, height - intensity), CV_RGB(0, 0, 255), -1);
}
// 显示图像和直方图
cvNamedWindow("Image", CV_WINDOW_AUTOSIZE);
cvNamedWindow("Histogram", CV_WINDOW_NORMAL);
cvShowImage("Image", img);
cvShowImage("Histogram", canvas);
cvWaitKey(0);
// 释放内存
cvReleaseImage(&img);
cvReleaseImage(&blue);
cvReleaseImage(&canvas);
cvReleaseHist(&hist);
cvDestroyAllWindows();
return 0;
}
```
该代码会读取一张图像,将其蓝色通道分离出来,计算蓝色直方图,并在窗口中显示原始图像和蓝色直方图。请注意,该示例代码使用的是IplImage而不是Mat。如果使用Mat,代码会有所不同。
阅读全文