目录
0.1原始图像1
0.2加了噪声的图像
20-23:直方图相关操作
输入图像:灰度较暗的图像
20.画直方图
使用 Matplotlib 来绘制 imori_dark.jpg !
直方图显示了不同数值的像素出现的次数。在 Matplotlib 中有 hist() 函数提供绘制直方图的接口。
plt.hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype=‘bar’, align=‘mid’, orientation=‘vertical’, rwidth=None, log=False, color=None, label=None, stacked=False)
常用:
x:指定要绘制直方图的数据。
bins:指定直方图条形的个数。
range:指定直方图数据的上下界,默认包含绘图数据的最大值和最小值。
rwidth:设置直方图条形的宽度
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Read image
img = cv2.imread("../1.jpg").astype(np.float)
# Display histogram
#img.ravel():功能为将多维数组降为一维数组
plt.hist(img.ravel(), bins=255, rwidth=0.8, range=(0, 255))
plt.savefig("out.png")
plt.show()
21.直方图归一化
直方图会存在偏差。比如说,数据集中在 处(左侧)的图像全体会偏暗,数据集中在 处(右侧)的图像会偏亮。
如果直方图有所偏向,那么其动态范围( dynamic range )就会较低。
为了使人能更清楚地看见图片,让直方图归一化、平坦化是十分必要的。
这种归一化直方图的操作被称作灰度变换(Grayscale Transformation)。将像素点取值范围从[c,d] 转 换到[a,b] 的过程由下式定义。
import cv2
import numpy as np
import matplotlib.pyplot as plt
# histogram normalization
def hist_normalization(img, a=0, b=255):
# get max and min
c = img.min()
d = img.max()
out = img.copy()
# normalization
out = (b-a) / (d - c) * (out - c) + a
out[out < a] = a
out[out > b] = b
out = out.astype(np.uint8)
return out
# Read image
img = cv2.imread("../imori_dark.jpg").astype(np.float)
H, W, C = img.shape
# histogram normalization
out = hist_normalization(img) #先归一化
# Display histogram
plt.hist(out.ravel(), bins=255, rwidth=0.8) #再画直方图
plt.savefig("out_his.png")
plt.show()
# Save result
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.imwrite("out.jpg", out)
22.改变直方图的标准差和平均值
可以使用下式将平均值为m标准差为s 的直方图变成平均值为m1 标准差为 s1的直方图。这里并不是变更直方图的动态范围,而是让直方图变得平坦。
def hist_mani(