直方图均值化;
要求:
1、不改变像素之间的相对亮度大小
2、处理后的像素值分布在0-255之间
3、将图像的灰度区间拉大,增强对比度让图像更清晰
步骤:
1、统计图像中每个灰度级的像素个数
2、计算每个灰度级的累计概率分布(0-1)
3、依据累计分布值计算其对应的灰度值(0-255)
4、映射回原来坐标的像素值
代码:
一、基础的图像操作
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread("lisa.jpg")
B,G,R = cv2.split(img);
zeros = np.zeros(img.shape[:2],dtype="uint8")
plt.figure(figsize=(7,7))
plt.subplot(221)
plt.imshow(cv2.merge([B,zeros,zeros]))
plt.subplot(222)
plt.imshow(cv2.merge([zeros,G,zeros]))
plt.subplot(223)
plt.imshow(cv2.merge([zeros,zeros,R]))
plt.subplot(224)
plt.imshow(cv2.merge([R,G,B]))
二、直方图均衡化
img = cv2.imread("hist.png")
plt.imshow(img,cmap="gray")
img_gay = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
rows = img.shape[0]
cols = img.shape[1]
hist = np.zeros(256)
for j in range(rows):
for k in range(cols):
tmp = img_gay[j][k]
hist[tmp] = hist[tmp] + 1
plt.subplot(311)
plt.plot(hist)
trans = hist / (rows * cols)
for i in range(1,256):
trans[i] = trans[i] + trans[i-1]
trans = trans * 255
plt.subplot(312)
plt.plot(trans)
img_balance = img_gay.copy()
for j in range(rows):
for k in range(cols):
tmp = img_gay[j][k]
img_balance[j][k] = int(trans[tmp])
hist_h = np.zeros(256)
for j in range(rows):
for k in range(cols):
tmp = img_balance[j][k]
hist_h[tmp] = hist_h[tmp] + 1
plt.subplot(313)
plt.plot(hist_h)
plt.figure(figsize=(7,7))
plt.imshow(cv2.vconcat([img_gay,img_balance]),cmap='gray')