根据输入的灰度图像,分别计算图像的均值、方差等统计特征,并计算图像的直方图特征并以图形方式显示图像的直方图(用C或C++语言实现)。
时间: 2024-02-12 07:07:53 浏览: 48
以下是一个使用C++语言实现的示例程序,可以计算灰度图像的均值、方差和直方图特征,并以图形方式显示直方图:
```cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
double get_mean(const Mat& img) {
double sum = 0;
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
sum += img.at<uint8_t>(i, j);
}
}
return sum / (img.rows * img.cols);
}
double get_variance(const Mat& img, double mean) {
double sum = 0;
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
double diff = img.at<uint8_t>(i, j) - mean;
sum += diff * diff;
}
}
return sum / (img.rows * img.cols - 1);
}
vector<int> get_histogram(const Mat& img) {
vector<int> hist(256, 0);
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
hist[img.at<uint8_t>(i, j)]++;
}
}
return hist;
}
void show_histogram(const vector<int>& hist) {
int max_count = *max_element(hist.begin(), hist.end());
int height = 256;
int width = hist.size() * 2;
Mat image(height, width, CV_8UC1, Scalar(255));
for (int i = 0; i < hist.size(); i++) {
int count = hist[i];
int x1 = i * 2;
int y1 = height;
int x2 = (i + 1) * 2 - 1;
int y2 = height - count * height / max_count;
rectangle(image, Point(x1, y1), Point(x2, y2), Scalar(0), -1);
}
imshow("Histogram", image);
}
int main(int argc, char** argv) {
if (argc < 2) {
cout << "Usage: " << argv[0] << " <image_file>" << endl;
return 0;
}
Mat image = imread(argv[1], IMREAD_GRAYSCALE);
if (image.empty()) {
cout << "Failed to open image file " << argv[1] << endl;
return 0;
}
double mean = get_mean(image);
double variance = get_variance(image, mean);
vector<int> hist = get_histogram(image);
cout << "Mean: " << mean << endl;
cout << "Variance: " << variance << endl;
namedWindow("Image", WINDOW_NORMAL);
imshow("Image", image);
namedWindow("Histogram", WINDOW_NORMAL);
show_histogram(hist);
waitKey(0);
return 0;
}
```
这个程序使用OpenCV库来读取图像文件和显示图像和直方图。可以通过命令行参数指定要处理的图像文件。程序首先计算图像的均值和方差,并输出到控制台上。然后计算图像的直方图,将直方图特征显示在一个图形窗口中。
阅读全文