暗通道去雾算法python
时间: 2023-10-01 22:10:25 浏览: 130
以下是一个简单的Python实现暗通道去雾算法的示例代码:
```python
import numpy as np
import cv2
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
def atm_light(img, dark):
[h, w] = img.shape[:2]
img_size = h * w
numpx = int(max(np.floor(img_size / 1000), 1))
darkvec = dark.reshape(img_size, 1)
imvec = img.reshape(img_size, 3)
indices = darkvec.argsort()[:img_size-numpx]
atmsum = np.zeros([1, 3])
for ind in range(len(indices)):
atmsum = atmsum + imvec[indices[ind]]
A = atmsum / (img_size-numpx)
return A
def transmission_estimate(img, A, size):
omega = 0.95
im3 = np.zeros(img.shape)
for ind in range(0, 3):
im3[:, :, ind] = img[:, :, ind] / A[0, ind]
transmission = 1 - omega * dark_channel(im3, size)
return transmission
def guided_filter(p, i, r, eps):
mean_i = cv2.boxFilter(i, cv2.CV_64F, (r, r))
mean_p = cv2.boxFilter(p, cv2.CV_64F, (r, r))
mean_ip = cv2.boxFilter(i*p, cv2.CV_64F, (r, r))
cov_ip = mean_ip - mean_i*mean_p
mean_ii = cv2.boxFilter(i*i, cv2.CV_64F, (r, r))
var_i = mean_ii - mean_i*mean_i
a = cov_ip / (var_i + eps)
b = mean_p - a*mean_i
mean_a = cv2.boxFilter(a, cv2.CV_64F, (r,r))
mean_b = cv2.boxFilter(b, cv2.CV_64F, (r,r))
q = mean_a*i + mean_b
return q
def refine_transmission(img, transmission):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.float64(gray) / 255
r = 60
eps = 0.0001
t = guided_filter(gray, transmission, r, eps)
return t
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
if __name__ == '__main__':
img = cv2.imread('input.jpg')
size = 15
A = atm_light(img, dark_channel(img, size))
transmission = transmission_estimate(img, A, size)
transmission = refine_transmission(img, transmission)
result = recover(img, transmission, A)
cv2.imwrite('result.jpg', result)
```
其中,`dark_channel`函数用于计算暗通道图像,`atm_light`函数用于估计大气光照,`transmission_estimate`函数用于估计透射率,`guided_filter`函数用于引导滤波,`refine_transmission`函数用于细化透射率,`recover`函数用于恢复图像。
这段代码实现了暗通道去雾算法并将结果保存到`result.jpg`中。你可以将输入图像替换为你自己的图像,然后运行代码。注意,这段代码只是一个简单的示例,实际上应该根据图像的特点进行调整。
阅读全文