MLap commited on
Commit
763db33
1 Parent(s): 19943fc

Main file added

Browse files
Files changed (1) hide show
  1. DeFogify_Main.py +52 -0
DeFogify_Main.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import gradio as gr
4
+
5
+ def dark_channel(img, size=15):
6
+ r, g, b = cv2.split(img)
7
+ min_img = cv2.min(r, cv2.min(g, b))
8
+ kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (size, size))
9
+ dc_img = cv2.erode(min_img, kernel)
10
+ return dc_img
11
+
12
+ def get_atmo(img, percent=0.001):
13
+ mean_perpix = np.mean(img, axis=2).reshape(-1)
14
+ mean_topper = mean_perpix[:int(img.shape[0] * img.shape[1] * percent)]
15
+ return np.mean(mean_topper)
16
+
17
+ def get_trans(img, atom, w=0.95):
18
+ x = img / atom
19
+ t = 1 - w * dark_channel(x, 15)
20
+ return t
21
+
22
+ def guided_filter(p, i, r, e):
23
+ mean_I = cv2.boxFilter(i, cv2.CV_64F, (r, r))
24
+ mean_p = cv2.boxFilter(p, cv2.CV_64F, (r, r))
25
+ corr_I = cv2.boxFilter(i * i, cv2.CV_64F, (r, r))
26
+ corr_Ip = cv2.boxFilter(i * p, cv2.CV_64F, (r, r))
27
+ var_I = corr_I - mean_I * mean_I
28
+ cov_Ip = corr_Ip - mean_I * mean_p
29
+ a = cov_Ip / (var_I + e)
30
+ b = mean_p - a * mean_I
31
+ mean_a = cv2.boxFilter(a, cv2.CV_64F, (r, r))
32
+ mean_b = cv2.boxFilter(b, cv2.CV_64F, (r, r))
33
+ q = mean_a * i + mean_b
34
+ return q
35
+
36
+ def dehaze(image):
37
+ img = image.astype('float64') / 255
38
+ img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY).astype('float64') / 255
39
+
40
+ atom = get_atmo(img)
41
+ trans = get_trans(img, atom)
42
+ trans_guided = guided_filter(trans, img_gray, 20, 0.0001)
43
+ trans_guided = cv2.max(trans_guided, 0.25)
44
+
45
+ result = np.empty_like(img)
46
+ for i in range(3):
47
+ result[:, :, i] = (img[:, :, i] - atom) / trans_guided + atom
48
+
49
+ return (result * 255).astype(np.uint8) # expected images in the uint8 format (pixel values between 0 and 255)
50
+
51
+ PixelDehazer = gr.Interface(fn=dehaze, inputs=gr.Image(type="numpy"), outputs="image") # passed image as numpy array
52
+ PixelDehazer.launch()