📜  直方图图像处理python(1)

📅  最后修改于: 2023-12-03 14:56:27.778000             🧑  作者: Mango

直方图图像处理 Python

在计算机视觉领域,直方图是一种常见的图像处理技术,它可以用来显示图像的灰度分布。使用 Python 语言,可以通过一些库来实现直方图图像处理。

安装

使用 Python 进行直方图图像处理需要先安装以下库:

  • numpy
  • matplotlib

安装方法可以使用 pip 安装:

pip install numpy
pip install matplotlib
实现

在 Python 中,使用 Matplotlib 库中的 hist() 函数可以生成直方图图像。例如,以下代码可以读取一张图片并显示其灰度分布:

import cv2
import numpy as np
import matplotlib.pyplot as plt
 
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
 
hist,bins = np.histogram(img.flatten(),256,[0,256])
 
plt.hist(img.flatten(),256,[0,256], color = 'r')
plt.xlim([0,256])
plt.show()

该代码首先读取一张图片并将其转换为灰度图像。然后使用 NumPy 库中的 histogram() 函数来计算其灰度分布,生成直方图数据。最后,使用 Matplotlib 库中的 hist() 函数来绘制直方图图像。

示例

下面是一个完整的示例程序,可以读取一张图片并显示其灰度分布图:

import cv2
import numpy as np
import matplotlib.pyplot as plt
 
img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
 
hist,bins = np.histogram(img.flatten(),256,[0,256])
 
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max()/ cdf.max()
 
plt.plot(cdf_normalized, color = 'b')
plt.hist(img.flatten(),256,[0,256], color = 'r')
plt.xlim([0,256])
plt.legend(('cdf','histogram'), loc = 'upper left')
plt.show()

该程序首先读取一张图片并将其转换为灰度图像。然后使用 NumPy 库中的 histogram() 函数来计算其灰度分布,生成直方图数据。计算累积分布函数(CDF)和归一化的 CDF,最后使用 Matplotlib 库中的 plot() 函数绘制 CDF 曲线和 hist() 函数绘制灰度分布直方图。最终得到的图像如下图所示:

histogram

结论

本文介绍了 Python 中直方图图像处理的方法。使用 Matplotlib 库中的 hist() 函数可以方便地生成直方图图像,可用于显示图像的灰度分布。需要注意的是,计算灰度分布和累积分布函数时,使用 NumPy 库中的函数可以极大提高计算效率。