1 灰度图的直方图均衡化
灰度直方图的均衡化的过程是一个累计概率完成映射的过程,举个例子:
像素0-100的概率累计相加得到0.5,则用255*0.5进行映射得到50来代替这个100这个像素值。又相应的API,这里就不做API的代码了,我们写均衡化的源码,代码如下:
import cv2
import numpy as np
img = cv2.imread('1.jpg', 1)
cv2.imshow('src', img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('dst', gray)
count = np.zeros(256, np.float)
for i in range(0, height):
for j in range(0, width):
pixel = gray[i, j]
# 转化为int类型
index = int(pixel)
count[index] = count[index]+1
for i in range(0, 255):
count[i] = count[i]/(height*width)
sum1 = float(0)
for i in range(0, 256):
sum1 = sum1 + count[i]
count[i] = sum1
# print(count)
# 计算映射表
map1 = np.zeros(256, np.uint16)
for i in range(0, 256):
map1[i] = np.uint16(count[i]*255)
# 映射
for i in range(0, height):
for j in range(0, width):
pixel = gray[i, j]
gray[i, j] = map1[pixel]
cv2.imshow('dst2', gray)
cv2.waitKey(0)
得到的效果如下:
2 彩色直方图均衡化
原理和灰度直方图均衡化一样,下面是源码
import cv2
import numpy as np
img = cv2.imread('1.jpg', 1)
cv2.imshow('src', img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
count_b = np.zeros(256, np.float)
count_g = np.zeros(256, np.float)
count_r = np.zeros(256, np.float)
for i in range(0, height):
for j in range(0, width):
(b, g, r) = img[i, j]
# 转化为int类型
index_b = int(b)
index_g = int(g)
index_r = int(r)
count_b[index_b] = count_b[index_b]+1
count_g[index_g] = count_g[index_g] + 1
count_r[index_r] = count_r[index_r] + 1
for i in range(0, 255):
count_b[i] = count_b[i] / (height*width)
count_g[i] = count_g[i] / (height * width)
count_r[i] = count_r[i] / (height * width)
sum1 = float(0)
sum2 = float(0)
sum3 = float(0)
for i in range(0, 256):
sum1 = sum1 + count_b[i]
sum2 = sum2 + count_g[i]
sum3 = sum3 + count_r[i]
count_b[i] = sum1
count_g[i] = sum2
count_r[i] = sum3
# print(count)
# 计算映射表
map1 = np.zeros(256, np.uint16)
map2 = np.zeros(256, np.uint16)
map3 = np.zeros(256, np.uint16)
for i in range(0, 256):
map1[i] = np.uint16(count_b[i]*255)
map2[i] = np.uint16(count_g[i]*255)
map3[i] = np.uint16(count_r[i]*255)
dst = np.zeros((height, width, 3), np.uint8)
# 映射
for i in range(0, height):
for j in range(0, width):
(b, g, r) = img[i, j]
b = map1[b]
g = map2[g]
r = map3[r]
dst[i, j] = (b, g, r)
cv2.imshow('dst2', dst)
cv2.waitKey(0)
代码较为简单,效果图如下: