clear all;
close all;
clc;

HazeImg_name = '/Users/apple/Desktop/Single Image Dehazing/Single Image Dehazing/Other Recourses/hazy_images/sam_4.bmp';
HazeImg = imread(HazeImg_name);
figure, imshow(uint8(HazeImg)), title('HazeImg');
[height, width, dimen]=size(HazeImg);

% estimate atmospheric light
winSize = floor(max([3, width*0.01, height*0.01]));

DarkImg = min(double(HazeImg), [], 3);
figure, imshow(uint8(DarkImg)), title('DarkImg');

DarkImg = ordfilt2(DarkImg, 1, ones(winSize,winSize), 'symmetric');
% DarkImg = minfilt2(DarkImg, [winSize, winSize]);
figure, imshow(uint8(DarkImg)), title('DarkImg');

method = 'method3';
A = airlight(HazeImg, DarkImg, method);

% estimate optimal transmission map
GrayImg = rgb2gray(HazeImg);
GrayImg = double(GrayImg);
figure, imshow(uint8(GrayImg)), title('GrayImg');
t_optimal = transmission(GrayImg, A);
figure, imshow(t_optimal), title('t_optimal');

%refine transmission map
radius = winSize * 4;
eps = 10 ^ -6;
t_refined = guidedfilter(GrayImg, t_optimal, radius, eps);
t_refined = min(t_refined, 31/32);
t_refined = max(t_refined, 6/32);
figure, imshow(t_refined), title('t_refined');

HazeImg = double(HazeImg);
DehazeImg(:,:,1) = (HazeImg(:,:,1) - (1-t_refined) * A) ./ t_refined;
DehazeImg(:,:,2) = (HazeImg(:,:,2) - (1-t_refined) * A) ./ t_refined;
DehazeImg(:,:,3) = (HazeImg(:,:,3) - (1-t_refined) * A) ./ t_refined;
figure, imshow(uint8(DehazeImg)), title('DehazeImg');

