DeHaze的opencv算法实现
时间: 2023-11-30 09:43:17 浏览: 29
DeHaze是一种用于去除图像中雾霾的算法,它可以通过对图像进行逆向模型估计来还原出原始图像。下面是使用OpenCV实现DeHaze算法的步骤:
1.读取图像并将其转换为浮点数格式。
```python
import cv2
import numpy as np
img = cv2.imread('image.jpg')
img = img.astype('float64') / 255.0
```
2.计算图像的暗通道。
```python
def dark_channel(img, size):
b, g, r = cv2.split(img)
dc = cv2.min(cv2.min(r, g), b)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (size, size))
dark = cv2.erode(dc, kernel)
return dark
dark = dark_channel(img, 15)
```
3.计算图像的大气光。
```python
def atm_light(img, dark):
[h, w] = img.shape[:2]
img_size = h * w
flat_img = img.reshape(img_size, 3)
flat_dark = dark.reshape(img_size, 1)
indices = np.argsort(flat_dark, axis=0)
indices = indices[img_size - img_size // 1000:]
atmsum = np.zeros([1, 3])
for ind in range(1, len(indices)):
atmsum = atmsum + flat_img[indices[ind]]
A = atmsum / (len(indices) - 1)
return A
A = atm_light(img, dark)
```
4.计算透射率。
```python
def transmission(img, A, size):
omega = 0.95
im3 = np.empty(img.shape, img.dtype)
for ind in range(0, 3):
im3[:, :, ind] = img[:, :, ind] / A[0, ind]
transmission = 1 - omega * dark_channel(im3, size)
return transmission
trans = transmission(img, A, 15)
```
5.恢复原始图像。
```python
def recover(img, t, A, tx=0.1):
res = np.empty(img.shape, img.dtype)
t = cv2.max(t, tx)
for ind in range(0, 3):
res[:, :, ind] = (img[:, :, ind] - A[0, ind]) / t + A[0, ind]
return res
result = recover(img, trans, A, 0.1)
```
6.将结果保存到文件中。
```python
cv2.imwrite('result.jpg', result * 255)
```