整个过程主要分为四步,一是将RGB颜色空间转换维HSV颜色空间,二是提取有光照分量,采用retinex相关算法对光照进行多尺度高斯卷积,三是采用伽马函数对多尺度光照分量进行处理,最后将HSV空间颜色转换为RGB。流程图见下,代码直接附上,尺度参数可调,伽马参数也可调。
import cv2
import numpy as np
import os
def adjust_gamma(image, gamma=1.0):
invGamma = 1.0 / gamma
# table = []
print(image)
image=np.array(image).astype(np.uint8)
# table.append(((i / 255.0) ** invGamma) * 255)
# table = np.array(table).astype("uint8")
gamma_table = [np.power(x / 255.0, invGamma) * 255.0 for x in range(256)]
# numpy数组默认数据类型为int32,需要将数据类型转换成opencv图像适合使用的无符号8位整型uint8,否则会报错
gamma_table = np.round(np.array(gamma_table)).astype(np.uint8)
print(image)
return cv2.LUT(image, gamma_table)
def MSR(img, scales):
weight = 1 / 3.0
scales_size = len(scales)
h, w = img.shape[:2]
log_R = np.zeros((h, w), dtype=np.float32)
for i in range(scales_size):
img = replaceZeroes(img)
# print('img',scales[i],img)
L_blur = cv2.GaussianBlur(img, (scales[i], scales[i]), 0)
L_blur = replaceZeroes(L_blur)
dst_Img = cv2.log(img / 255.0)
dst_Lblur = cv2.log(L_blur / 255.0)
dst_Ixl = cv2.multiply(dst_Img, dst_Lblur)
log_R += weight * cv2.subtract(dst_Img, dst_Ixl)
dst_R = cv2.normalize(log_R, None, 0, 255, cv2.NORM_MINMAX)
log_uint8 = cv2.convertScaleAbs(dst_R)
return log_uint8
def replaceZeroes(data):
min_nonzero = min(data[np.nonzero(data)])
data[data == 0] = min_nonzero
return data
dir='H:/python_project/test/underwater/'
file=os.listdir(dir)
for name in file:
imgname=dir+name
# imgname='image/486.jpg'
im =cv2.imread(imgname)
H,W=im.shape[0:2]
cv2.imshow('original image',im)
HSV_img = cv2.cvtColor(im,cv2.COLOR_BGR2HSV)
cv2.imshow('HSV_img',HSV_img)
h_gray, s_gray, v_gray = cv2.split(HSV_img)
# cv2.imshow('image1',h_gray)
# cv2.imshow('image2',s_gray)
# cv2.imshow('image3',v_gray)
Hsize=min(H,W)+1
print(Hsize)
size = 3
# q=np.sqrt(2)
SIGMA1=15
SIGMA2=31
SIGMA3=61
# print('q',q,[int(15/q), int(80/q), int(250/q)])
scales = [15, 101, 301]
gaus=MSR(v_gray, scales)
# 二维gamma卷积
m=np.mean(gaus)
# out=np.zeros((H,W))
gamma=np.power(0.8,((gaus-m)/m))
print(gamma)
out=255*(np.power(v_gray/255,gamma))
out_frame = np.zeros((out.shape[0],out.shape[1],3),dtype = np.uint8)
out_frame[:,:,0] = h_gray
out_frame[:,:,1] = s_gray
out_frame[:,:,2] = out
cv2.imshow('out_frame',out_frame)
RGB_img = cv2.cvtColor(out_frame,cv2.COLOR_HSV2BGR)
cv2.imshow('gaus_image1',RGB_img)
cv2.waitKey(0)
```python
在这里插入代码片