直方图归一化( Histogram Normalization )
有时直方图会偏向一边。
比如说,数据集中在 0 0 0处(左侧)的图像全体会偏暗,数据集中在 255 255 255处(右侧)的图像会偏亮。
如果直方图有所偏向,那么其动态范围( dynamic range )就会较低。
为了使人能更清楚地看见图片,让直方图归一化、平坦化是十分必要的。
这种归一化直方图的操作被称作灰度变换(Grayscale Transformation)。像素点取值范围从
[
c
,
d
]
[c,d]
[c,d]转换到
[
a
,
b
]
[a,b]
[a,b]的过程由下式定义。这回我们将灰度扩展到
[
0
,
255
]
[0, 255]
[0,255]范围:
x
o
u
t
=
{
a
(
if
x
i
n
<
c
)
b
−
a
d
−
c
(
x
i
n
−
c
)
+
a
(
else if
c
≤
x
i
n
<
d
)
b
(
else
)
x_{out}= \begin{cases} a& (\text{if}\quad x_{in}<c)\\ \frac{b-a}{d-c}\ (x_{in}-c)+a&(\text{else if}\quad c\leq x_{in}<d)\\ b&(\text{else}) \end{cases}
xout=⎩⎪⎨⎪⎧ad−cb−a (xin−c)+ab(ifxin<c)(else ifc≤xin<d)(else)
代码实现
import numpy as np
import matplotlib.pyplot as plt
from skimage.io import imread # 用来读取图片
%matplotlib inline
# 读取图片
path = 'C:/Users/86187/Desktop/image/'
file_in = path + 'cake.jpg'
img = imread(file_in)
plt.figure
imgshow = plt.imshow(img)
# 灰度化
# 灰度化函数
def BGR2GRAY(img):
# 获取图片尺寸
H, W, C = img.shape
# 灰度化
out = np.ones((H,W,3))
for i in range(H):
for j in range(W):
out[i,j,:] = 0.299*img[i,j,0] + 0.578*img[i,j,1] + 0.114*img[i,j,2]
out = out.astype(np.uint8)
return out
img = BGR2GRAY(img)
plt.figure
imgshow = plt.imshow(img)
img_ = img.copy()
img_ = img_.reshape(-1)
hist = plt.hist(img_, bins=255, rwidth=0.85, range=(0,255))
# 归一化函数
def normalHist(img):
a = 0
b = 255
c = img.min()
d = img.max()
img = (b-a)/(d-c)*(img-c)+a
img = img .astype(np.uint8)
return img
img1 = img.copy()
img1 = normalHist(img1)
imgshow = plt.imshow(img1)
plt.show()
hist1 = plt.hist(img1.reshape(-1),bins=255,rwidth=0.85,range=(0,255))