C和opencv实现图像显示图像的紫色的直方图,使用IplImage
时间: 2023-05-30 18:05:10 浏览: 90
以下是使用C和OpenCV实现图像显示图像紫色直方图的示例代码,使用IplImage结构体:
```
#include <stdio.h>
#include <stdlib.h>
#include <cv.h>
#include <highgui.h>
int main(int argc, char** argv)
{
// Load image
IplImage* img = cvLoadImage(argv[1], CV_LOAD_IMAGE_UNCHANGED);
if (!img)
{
printf("Error loading image\n");
return -1;
}
// Create grayscale image
IplImage* gray = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1);
cvCvtColor(img, gray, CV_BGR2GRAY);
// Create histogram
int histSize = 256;
float range[] = { 0, 256 };
float* ranges[] = { range };
CvHistogram* hist = cvCreateHist(1, &histSize, CV_HIST_ARRAY, ranges, 1);
// Calculate histogram
cvCalcHist(&gray, hist, 0, 0);
// Find bin for purple color
int purpleBin = cvRound(cvQueryHistValue_1D(hist, 140)); // Purple color range: 120-160
// Display histogram
int histWidth = 512;
int histHeight = 400;
int binWidth = cvRound((double)histWidth / histSize);
IplImage* histImg = cvCreateImage(cvSize(histWidth, histHeight), 8, 3);
cvZero(histImg);
for (int i = 0; i < histSize; i++)
{
int binValue = cvRound(cvGetReal1D(hist->bins, i));
CvScalar color;
if (i == purpleBin)
color = CV_RGB(255, 0, 255); // Purple bin
else
color = CV_RGB(255, 255, 255); // Other bins
cvRectangle(histImg, cvPoint(i*binWidth, histHeight), cvPoint((i+1)*binWidth, histHeight - binValue/10), color, -1, 8, 0);
}
cvNamedWindow("Histogram", CV_WINDOW_AUTOSIZE);
cvShowImage("Histogram", histImg);
// Display image
cvNamedWindow("Image", CV_WINDOW_AUTOSIZE);
cvShowImage("Image", img);
cvWaitKey(0);
// Release resources
cvReleaseImage(&img);
cvReleaseImage(&gray);
cvReleaseImage(&histImg);
cvReleaseHist(&hist);
return 0;
}
```
该程序首先加载图像,然后创建灰度图像,并使用OpenCV的cvCalcHist函数计算直方图。然后找到紫色直方图的bin,并创建一个新的IplImage对象,用于显示直方图。在该图像中,紫色的直方图bin被突出显示。最后,程序显示原始图像和直方图,并等待用户按下任意键以退出。
阅读全文