效果
原理
得到灰度化值,将灰度化的值带入0-255内,增加,得到可视化图形
源码
// 绘制直方图
QImage drawHistogram(const QImage &image)
{
QVector<int> histogram(256, 0);
// 计算图像的灰度直方图
for (int y = 0; y < image.height(); ++y) {
for (int x = 0; x < image.width(); ++x) {
QColor color(image.pixel(x, y));
int intensity = qGray(color.rgb());
histogram[intensity]++;
}
}
int maxValue = *std::max_element(histogram.constBegin(), histogram.constEnd());
QImage histogramImage(256, maxValue, QImage::Format_RGB32);
histogramImage.fill(Qt::white);
QPainter painter(&histogramImage);
painter.setPen(Qt::black);
for (int i = 0; i < histogram.size(); ++i) {
int height = histogram[i] * histogramImage.height() / maxValue;
painter.drawLine(i, histogramImage.height(), i, histogramImage.height() - height);
}
return histogramImage;
}