直方图均衡化

ops/2024/9/24 10:33:35/

概念

直方图均衡化是图像处理领域中利用图像直方图对对比度进行调整的方法,通过拉伸像素强度分布范围来增强图像对比度。

原理

  • 均衡化指的是把一个分布 (给定的直方图) 映射 到另一个分布 (一个更宽更统一的强度值分布),从而令强度值分布会在整个范围内展开。

  • 要想实现均衡化的效果,映射函数应该是一个 累积分布函数 ( cumulative distribution function, cdf ) 。对于直方图 H ( i ) H(i) H(i),它的累积分布函数 H ′ ( i ) H^{'}(i) H(i)

    H ′ ( i ) = ∑ j = 0 i H ( j ) H^{'}(i) = \sum_{j=0}^i H(j) H(i)=j=0iH(j)

    要使用其作为映射函数,我们必须对最大值为255 (或者用图像的最大强度值) 的累积分布 H ′ ( i ) H^{'}(i) H(i) 进行归一化。

  • 最后,我们使用一个简单的映射过程来获得均衡化后像素的强度值,假设原图为 I ( x , y ) I(x,y) I(x,y),均衡化后像素强度值 I ′ ( x , y ) I^{'}(x,y) I(x,y)

    I ′ ( x , y ) = H ′ ( I ( x , y ) ) I^{'}(x,y) = H^{'}(I(x,y)) I(x,y)=H(I(x,y))

代码实现

以 OpenCV 为例,其直方图均衡化函数为 equalizeHist(),代码实现如下:

/** @brief Equalizes the histogram of a grayscale image.The function equalizes the histogram of the input image using the following algorithm:- Calculate the histogram \f$H\f$ for src .
- Normalize the histogram so that the sum of histogram bins is 255.
- Compute the integral of the histogram:
\f[H'_i =  \sum _{0  \le j < i} H(j)\f]
- Transform the image using \f$H'\f$ as a look-up table: \f$\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\f$The algorithm normalizes the brightness and increases the contrast of the image.@param src Source 8-bit single channel image.
@param dst Destination image of the same size and type as src .*/
CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst );void cv::equalizeHist( InputArray _src, OutputArray _dst )
{CV_INSTRUMENT_REGION();CV_Assert( _src.type() == CV_8UC1 );if (_src.empty())return;CV_OCL_RUN(_src.dims() <= 2 && _dst.isUMat(),ocl_equalizeHist(_src, _dst))Mat src = _src.getMat();_dst.create( src.size(), src.type() );Mat dst = _dst.getMat();CV_OVX_RUN(!ovx::skipSmallImages<VX_KERNEL_EQUALIZE_HISTOGRAM>(src.cols, src.rows),openvx_equalize_hist(src, dst))CALL_HAL(equalizeHist, cv_hal_equalize_hist, src.data, src.step, dst.data, dst.step, src.cols, src.rows);Mutex histogramLockInstance;const int hist_sz = EqualizeHistCalcHist_Invoker::HIST_SZ;int hist[hist_sz] = {0,};int lut[hist_sz];EqualizeHistCalcHist_Invoker calcBody(src, hist, &histogramLockInstance);EqualizeHistLut_Invoker      lutBody(src, dst, lut);cv::Range heightRange(0, src.rows);if(EqualizeHistCalcHist_Invoker::isWorthParallel(src))parallel_for_(heightRange, calcBody);elsecalcBody(heightRange);int i = 0;while (!hist[i]) ++i;int total = (int)src.total();if (hist[i] == total){dst.setTo(i);return;}float scale = (hist_sz - 1.f)/(total - hist[i]);int sum = 0;for (lut[i++] = 0; i < hist_sz; ++i){sum += hist[i];lut[i] = saturate_cast<uchar>(sum * scale);}if(EqualizeHistLut_Invoker::isWorthParallel(src))parallel_for_(heightRange, lutBody);elselutBody(heightRange);
}

应用举例

C++ 代码如下:

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>using namespace cv;
using std::cout;
using std::endl;int main(int argc, char** argv)
{CommandLineParser parser(argc, argv, "{@input | wukong.png | input image}");Mat src = imread(samples::findFile(parser.get<String>("@input")), IMREAD_COLOR);if (src.empty()){cout << "Could not open or find the image!\n" << endl;cout << "Usage: " << argv[0] << " <Input image>" << endl;return EXIT_FAILURE;}// 转换为灰度图像cvtColor(src, src, COLOR_BGR2GRAY);Mat dst;// 直方图均衡化equalizeHist(src, dst);imshow("Source image", src);imshow("Equalized Image", dst);waitKey();return EXIT_SUCCESS;}

Python 代码如下:

python">import cv2
import matplotlib.pyplot as plt# 读取图像
img = cv2.imread('../data/wukong.png', cv2.IMREAD_COLOR)
# 转换为灰度图
src = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 直方图均衡化
dst = cv2.equalizeHist(src)
# 显示原图和均衡化后的图
fig, axes = plt.subplots(2, 2, figsize=(18, 9))
axes[0, 0].imshow(src, cmap='gray')
axes[1, 0].imshow(dst, cmap='gray')
axes[0, 1].hist(src.ravel(), 256, [0, 256], color='#fc8403')
axes[1, 1].hist(dst.ravel(), 256, [0, 256], color='#fc8403')
# 显示直方图网格
axes[0, 1].grid(axis='y', linestyle='-.', alpha=0.5)
axes[1, 1].grid(axis='y', linestyle='-.', alpha=0.5)
# 设置标题
axes[0, 0].set_title('Original Image')
axes[1, 0].set_title('Equalized Image')
axes[0, 1].set_title('Histogram of Original Image')
axes[1, 1].set_title('Histogram of Equalized Image')
# 显示图表
plt.show()

直方图均衡化效果


http://www.ppmy.cn/ops/99543.html

相关文章

闲谈 那么问题来了,黑神话是用什么语言开发的?

蹭个热度&#xff0c;顺便站起身消遣消遣聊聊天 提问&#xff1a;“黑神话工作室的初代程序员否分到原始股&#xff1f;” 我是真不知道&#xff0c;但如果有分股份&#xff0c;那不是一夜暴富&#xff0c;想想就爽吧 评论区求解&#xff0c;图片自取

采用ELK搭建日志平台,安装elasticsearch-head

1、下载elasticsearch-head https://gitcode.com/ 需要账号密码才能下载 2、解压 yum install -y unzip zip unzip elasticsearch-head-master.zip 3、执行安装命令 mv elasticsearch-head-master /usr/local/elasticsearch-head-master cd /usr/local/elasticsearch-head…

ShellSweepPlus 介绍:开源 Web Shell 检测

ShellSweepPlus 概述 ShellSweepPlus是一款开源工具,旨在帮助安全团队检测潜在的 Web Shell。它是 ShellSweep 的增强版 Webshell 的威胁 Web shell 对组织构成重大威胁,因为它们为攻击者提供了对受感染 Web 服务器的未经授权的访问和控制。攻击者可以利用这些 shell 来:…

怎么快速定位bug?如何编写测试用例?

&#x1f345; 点击文末小卡片&#xff0c;免费获取软件测试全套资料&#xff0c;资料在手&#xff0c;涨薪更快 作为一名测试人员如果连常见的系统问题都不知道如何分析&#xff0c;频繁将前端人员问题指派给后端人员&#xff0c;后端人员问题指派给前端人员&#xff0c;那么在…

图解Redis五大数据类型

五种数据类型的不同之处&#xff0c;是value在存储时的形式不同。 hash类型 value类型是<key,value>键值对。如果发生hash冲突&#xff0c;用开放定址法解决&#xff0c;不拉链&#xff01; key值重复&#xff0c;则新值覆盖旧值 List类型 Set类型 与List的类似&…

Excel平均值与减法技巧

Excel中&#xff0c;表格怎么求平均值&#xff1f; 打开Excel&#xff0c;创建一个新的工作表或者打开需要操作的工作表。在需要计算平均值的单元格中&#xff0c;输入“AVERAGE (A1:A12)”。 这个函数的作用就是计算平均值。 其中A1代表A列第一个单元格&#xff0c;A12代表A列…

[ 全部搞定 - 发票导出表格 ] PDF发票提取到表,图片发票提取到表格,扫描件发票提取到表格,全电发票PDF,全电发票扫描件识别导出EXCEL表格

最近很多朋友说找PDF发票提取Excel表格的&#xff0c;找到了图片识别Excel表格的&#xff0c;有的找图片识别Excel表格的&#xff0c;找到了PDF发票提取表格的&#xff0c;所以就很难搞&#xff0c;还有的说都想要 今天一篇文章&#xff0c;全部搞定所有发票【电子发票&#x…

JavaScript 文件上传详解与实现

文件上传是 Web 开发中常见的功能之一&#xff0c;几乎所有的 Web 应用都会涉及到上传文件&#xff0c;如上传图片、视频、文档等。 一、基本文件上传实现 1.1 HTML 表单元素 文件上传通常通过 <input> 元素的 type"file" 来实现。以下是一个简单的 HTML 文…