Python直方图、均衡化、高斯滤波

这篇博客介绍了Python中如何进行图像直方图的绘制、直方图均衡化和高斯滤波。通过matplotlib库和PCV库,展示了直方图均衡化增强图像对比度的过程,以及高斯滤波如何实现图像模糊。代码示例详细解释了每个步骤,包括原始图像与处理后图像的对比和直方图的变化。
摘要由CSDN通过智能技术生成

原图

在这里插入图片描述

直方图

直方图的概念

  一副数字图像在[0,G]范围内总共有L个灰度级,其直方图定义为下列离散函数
在这里插入图片描述

直方图的绘制

matplotlib库的hist函数:
  hist函数能够帮助绘制直方图。它的参数很多,这里用到前两个参数:x、bins。x参数表示一个像素的一维数组,如果是一维以上的数组可以使用flatten方法展平成一维,一般来说读入一幅图片都是一个二维的矩阵,都需要进行展平的操作。bins参数表示要显示直方图的柱数


代码:

# -*- coding: utf-8 -*-
from array import array

from PIL import Image
from pylab import *

# 添加中文字体支持
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\SimSun.ttc", size=14)
im = array(Image.open('03.jpg').convert('L'))  # 读取图像到数组中

figure()  # 新建一个图像
subplot(121)
gray()  # 不使用颜色信息
contour(im, origin='image')  # 在原点的左上角显示轮廓图像
axis('equal')
axis('off')
title(u'图像轮廓', fontproperties=font)

subplot(122)
hist(im.flatten(), 128)  # flatten方法将其转换成一维数组,指定柱数为128
title(u'图像直方图', fontproperties=font)
plt.xlim([0,260])
plt.ylim([0,11000])

show()

运行结果:
在这里插入图片描述

直方图均衡化

直方图均衡化原理

  直方图均衡化是指将一幅图像的灰度直方图变平,使变换后的图像中每个灰度值的分布概率都相同。在对图像做进一步处理之前,直方图均衡化通常是对图像灰度值进行归一化的一个非常好的方法,并且可以增强图像的对比度。在这种情况下,直方图均衡化的变换函数是图像中像素值的累积分布函数(cumulative distribution function,简写为 cdf,将像素值的范围映射到目标范围的归一化操作)。使用PCV库的histeq函数均衡化。

直方图均衡化实现

代码:

# -*- coding: utf-8 -*-
from array import array

from PIL import Image
from pylab import *
from PCV.tools import imtools

# 添加中文字体支持
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\SimSun.ttc", size=14)

im = array(Image.open('03.jpg').convert('L'))
#im = array(Image.open('../data/AquaTermi_lowcontrast.JPG').convert('L'))
im2, cdf = imtools.histeq(im)

figure()
subplot(2, 2, 1)
axis('off')
gray()
title(u'原始图像', fontproperties=font)
imshow(im)

subplot(2, 2, 2)
axis('off')
title(u'直方图均衡化后的图像', fontproperties=font)
imshow(im2)

subplot(2, 2, 3)
axis('off')
title(u'原始直方图', fontproperties=font)
#hist(im.flatten(), 128, cumulative=True, normed=True)
hist(im.flatten(), 128, density=True)

subplot(2, 2, 4)
axis('off')
title(u'均衡化后的直方图', fontproperties=font)
#hist(im2.flatten(), 128, cumulative=True, normed=True)
hist(im2.flatten(), 128, density=True)

show()

运行结果:
在这里插入图片描述  图中我们可以看到均衡化后图像的对比度增强了,均衡化后的直方图灰度值的分布也更加平坦。

高斯滤波

高斯滤波原理

什么是高斯滤波:
  高斯滤波是一种线性平滑滤波,它将正态分布用于图像处理,适用于消除高斯噪声,能够对图片进行模糊处理,使图像变得平滑,使图片产生模糊的效果。
  cv2.GussianBlur()函数可实现这一操作。

高斯滤波实现

代码:

import cv2
import matplotlib.pyplot as plt

im=cv2.imread("03.jpg")
# 高斯滤波
img_Guassian = cv2.GaussianBlur(im,(5,5),0)

plt.subplot(121)
plt.imshow(im)
plt.subplot(122)
plt.imshow(img_Guassian)

plt.show()

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值