欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python实现图像去雾效果的示例代码

程序员文章站 2022-06-16 19:53:34
目录修改部分训练测试数据集下载地址修改部分我利用该代码进行了去雾任务,并对原始代码进行了增删,去掉了人脸提取并对提取人脸美化的部分,如下图增改了一些数据处理代码,create_bigfile2.py和...

修改部分

我利用该代码进行了去雾任务,并对原始代码进行了增删,去掉了人脸提取并对提取人脸美化的部分,如下图

Python实现图像去雾效果的示例代码

增改了一些数据处理代码,create_bigfile2.py和load_bigfilev2为特定任务需要加的代码,这里数据处理用的是原始方法,即将训练数据打包成一个文件,一次性载入,可能会内存爆炸。去雾的如下

Python实现图像去雾效果的示例代码

另外,为了节省内存,可以不使用原始方法,我改写了online_dataset_for_odl_photos.py文件

用于我的加雾论文,此时可以不使用原始的create_bigfile和load_bigfile代码如下

# copyright (c) microsoft corporation.
# licensed under the mit license.
 
import os.path
import io
import zipfile
from data.base_dataset import basedataset, get_params, get_transform, normalize
from data.image_folder import make_dataset
from data.load_bigfile import bigfilememoryloader
import torchvision.transforms as tfs
from torchvision.transforms import functional as ff
 
 
from pil import image
import torchvision.transforms as transforms
import numpy as np
 
import random
import cv2
from io import bytesio
 
#图片转矩阵
def pil_to_np(img_pil):
    '''converts image in pil format to np.array.
    from w x h x c [0...255] to c x w x h [0..1]
    '''
    ar = np.array(img_pil)
 
    if len(ar.shape) == 3:
        ar = ar.transpose(2, 0, 1)
    else:
        ar = ar[none, ...]
 
    return ar.astype(np.float32) / 255.
 
#矩阵转图片
def np_to_pil(img_np):
    '''converts image in np.array format to pil image.
    from c x w x h [0..1] to  w x h x c [0...255]
    '''
    ar = np.clip(img_np * 255, 0, 255).astype(np.uint8)
 
    if img_np.shape[0] == 1:
        ar = ar[0]
    else:
        ar = ar.transpose(1, 2, 0)
 
    return image.fromarray(ar)
##
#以下合成噪声图片
##
def synthesize_salt_pepper(image,amount,salt_vs_pepper):
 
    ## give pil, return the noisy pil
 
    img_pil=pil_to_np(image)
 
    out = img_pil.copy()
    p = amount
    q = salt_vs_pepper
    flipped = np.random.choice([true, false], size=img_pil.shape,
                               p=[p, 1 - p])
    salted = np.random.choice([true, false], size=img_pil.shape,
                              p=[q, 1 - q])
    peppered = ~salted
    out[flipped & salted] = 1
    out[flipped & peppered] = 0.
    noisy = np.clip(out, 0, 1).astype(np.float32)
 
 
    return np_to_pil(noisy)
 
def synthesize_gaussian(image,std_l,std_r):
 
    ## give pil, return the noisy pil
 
    img_pil=pil_to_np(image)
 
    mean=0
    std=random.uniform(std_l/255.,std_r/255.)
    gauss=np.random.normal(loc=mean,scale=std,size=img_pil.shape)
    noisy=img_pil+gauss
    noisy=np.clip(noisy,0,1).astype(np.float32)
 
    return np_to_pil(noisy)
 
def synthesize_speckle(image,std_l,std_r):
 
    ## give pil, return the noisy pil
 
    img_pil=pil_to_np(image)
 
    mean=0
    std=random.uniform(std_l/255.,std_r/255.)
    gauss=np.random.normal(loc=mean,scale=std,size=img_pil.shape)
    noisy=img_pil+gauss*img_pil
    noisy=np.clip(noisy,0,1).astype(np.float32)
 
    return np_to_pil(noisy)
 
#图片缩小
def synthesize_low_resolution(img):
    w,h=img.size
 
    new_w=random.randint(int(w/2),w)
    new_h=random.randint(int(h/2),h)
 
    img=img.resize((new_w,new_h),image.bicubic)
 
    if random.uniform(0,1)<0.5:
        img=img.resize((w,h),image.nearest)
    else:
        img = img.resize((w, h), image.bilinear)
 
    return img
 
#处理图片
def converttojpeg(im,quality):
    #在内存中读写bytes
    with bytesio() as f:
        im.save(f, format='jpeg',quality=quality)
        f.seek(0)
        #使用image.open读出图像,然后转换为rgb通道,去掉透明通道a
        return image.open(f).convert('rgb')
 
#由(高斯)噪声生成图片
def blur_image_v2(img):
 
 
    x=np.array(img)
    kernel_size_candidate=[(3,3),(5,5),(7,7)]
    kernel_size=random.sample(kernel_size_candidate,1)[0]
    std=random.uniform(1.,5.)
 
    #print("the gaussian kernel size: (%d,%d) std: %.2f"%(kernel_size[0],kernel_size[1],std))
    blur=cv2.gaussianblur(x,kernel_size,std)
 
    return image.fromarray(blur.astype(np.uint8))
#由以上噪声函数随机生成含有噪声的图片
def online_add_degradation_v2(img):
 
    task_id=np.random.permutation(4)
 
    for x in task_id:
        if x==0 and random.uniform(0,1)<0.7:
            img = blur_image_v2(img)
        if x==1 and random.uniform(0,1)<0.7:
            flag = random.choice([1, 2, 3])
            if flag == 1:
                img = synthesize_gaussian(img, 5, 50)
            if flag == 2:
                img = synthesize_speckle(img, 5, 50)
            if flag == 3:
                img = synthesize_salt_pepper(img, random.uniform(0, 0.01), random.uniform(0.3, 0.8))
        if x==2 and random.uniform(0,1)<0.7:
            img=synthesize_low_resolution(img)
 
        if x==3 and random.uniform(0,1)<0.7:
            img=converttojpeg(img,random.randint(40,100))
 
    return img
 
#根据mask生成带有折痕的图片
#原论文中对于一些复杂的折痕会出现处理不佳的情况,在此进行改进,而不是简单进行加mask,
def irregular_hole_synthesize(img,mask):
 
    img_np=np.array(img).astype('uint8')
    mask_np=np.array(mask).astype('uint8')
    mask_np=mask_np/255
    img_new=img_np*(1-mask_np)+mask_np*255
 
 
    hole_img=image.fromarray(img_new.astype('uint8')).convert("rgb")
    #l为灰度图像
    return hole_img,mask.convert("l")
#生成全黑三通道图像mask
def zero_mask(size):
    x=np.zeros((size,size,3)).astype('uint8')
    mask=image.fromarray(x).convert("rgb")
    return mask
#########################################  my  ################################
 
class unpairoldphotos_srv2(basedataset):  ## synthetic + real old
    def initialize(self, opt):
        self.opt = opt
        self.isimage = 'domaina' in opt.name
        self.task = 'old_photo_restoration_training_vae'
        self.dir_ab = opt.dataroot
        # 载入voc以及真实灰度、彩色图
        #domina
        if self.isimage:
            path_clear = r'/home/vip/shy/ots/clear_images/' ##self.opt.path_clear
            path_old = r'/home/vip/shy/bringing-old-photos-back-to-life_v1/voc2007/real_rgb_old' ##self.opt.path_old
            path_haze = r'/home/vip/shy/ots/hazy/' ##self.opt.path_haze
            #self.load_img_dir_l_old=os.path.join(self.dir_ab,"real_l_old.bigfile")
            self.load_img_dir_rgb_old=path_old
            self.load_img_dir_clean=path_clear
            self.load_img_dir_synhaze=path_haze
 
            self.img_dir_synhaze = os.listdir(self.load_img_dir_synhaze)
            self.loaded_imgs_synhaze=[os.path.join(self.load_img_dir_synhaze,img) for img in self.img_dir_synhaze]
            self.img_dir_rgb_old = os.listdir(self.load_img_dir_rgb_old)
            self.loaded_imgs_rgb_old = [os.path.join(self.load_img_dir_rgb_old,img) for img in self.img_dir_rgb_old]
            self.loaded_imgs_clean = []
            for path_i in self.loaded_imgs_synhaze:
                    p,n = os.path.split(path_i)
                    pre,ex = os.path.splitext(n)
                    clear_pre = pre.split('_')[0]
                    clear_path = os.path.join(path_clear,clear_pre+ex)
                    self.loaded_imgs_clean.append(clear_path)
            print('________________filter whose size <256')
            self.filtered_imgs_clean = []
            self.filtered_imgs_synhaze = []
            self.filtered_imgs_old = []
            print('________________now filter syn and clean size <256')
            for i in range(len(self.loaded_imgs_synhaze)):
                img_name_syn = self.loaded_imgs_synhaze[i]
                img = image.open(img_name_syn)
                h, w = img.size
                img_name_clear = self.loaded_imgs_clean[i]
                if h < 256 or w < 256:
                    continue
                self.filtered_imgs_clean.append(img_name_clear)
                self.filtered_imgs_synhaze.append(img_name_syn)
            print('________________now filter old size <256')
            for i in range(len(self.loaded_imgs_rgb_old)):
                img_name_old = self.loaded_imgs_rgb_old[i]
                img = image.open(img_name_old)
                h, w = img.size
                if h < 256 or w < 256:
                    continue
                self.filtered_imgs_old.append(img_name_old)
 
        #dominb: if domina not in experiment's name ,load voc defultly
        else:
            path_clear = r'/home/vip/shy/ots/clear_images/' ##self.opt.path_clear
            self.load_img_dir_clean=path_clear
            self.loaded_imgs_clean = []
            self.img_dir_clean = os.listdir(self.load_img_dir_clean)
            self.loaded_imgs_clean = [os.path.join(self.load_img_dir_clean, img) for img in self.img_dir_clean]
            print('________________now filter old size <256')
            self.filtered_imgs_clean = []
            for i in range(len(self.loaded_imgs_clean)):
                img_name_clean = self.loaded_imgs_clean[i]
                img = image.open(img_name_clean)
                h, w = img.size
                if h < 256 or w < 256:
                    continue
                self.filtered_imgs_clean.append(img_name_clean)
        ####
        print("-------------filter the imgs whose size <256 finished -------------")
 
        self.pid = os.getpid()
 
    def __getitem__(self, index):
 
 
        is_real_old=0
 
        sampled_dataset=none
        degradation=none
        #随机抽取一张图片(从合成的老照片 和 真实老照片 中)
        if self.isimage: ## domain a , contains 2 kinds of data: synthetic + real_old
            p=random.uniform(0,2)
            if p>=0 and p<1:
                sampled_dataset=self.filtered_imgs_old
                self.load_img_dir=self.load_img_dir_rgb_old
                self.num = len(sampled_dataset)
                is_real_old=1
            if p>=1 and p<2:
                sampled_dataset=self.filtered_imgs_synhaze
                self.load_img_dir=self.load_img_dir_synhaze
                self.num = len(sampled_dataset)
                degradation=1
        #domin b
        else:
            #载入过滤后小于256大小的图
            sampled_dataset=self.filtered_imgs_clean
            self.load_img_dir=self.load_img_dir_clean
            self.num = len(sampled_dataset)
 
        index=random.randint(0,self.num-1)
        img_name = sampled_dataset[index]
        a = image.open(img_name)
        path = img_name
        #########################################################################
        # i, j, h, w = tfs.randomcrop.get_params(a, output_size=(256, 256))
        # a = ff.crop(a, i, j, h, w)
        # a = a.convert("rgb")
        # a_tensor = #tfs.totensor()(a)
        #########################################################################
        transform_params = get_params(self.opt, a.size)
        a_transform = get_transform(self.opt, transform_params)
        a_tensor = a_transform(a.convert("rgb"))
 
        b_tensor = inst_tensor = feat_tensor = 0
        input_dict = {'label': a_tensor, 'inst': is_real_old, 'image': a_tensor,
                        'feat': feat_tensor, 'path': path}
        return input_dict
 
    def __len__(self):
        return  len(self.filtered_imgs_clean)## actually, this is useless, since the selected index is just a random number
                                        #control the epoch through the iters =len(loaded_imgs_clean)
    def name(self):
        return 'unpairoldphotos_sr'
 
 
 
 
# ###################################################################################3
# #非成对的老照片图像载入器(合成的老的和真实的老的照片,他们并非对应的,合成的老的照片由voc数据集经处理生成)
# class unpairoldphotos_sr(basedataset):  ## synthetic + real old
#     def initialize(self, opt):
#         self.opt = opt
#         self.isimage = 'domaina' in opt.name
#         self.task = 'old_photo_restoration_training_vae'
#         self.dir_ab = opt.dataroot
#         # 载入voc以及真实灰度、彩色图
#         #domina
#         if self.isimage:
#
#             #self.load_img_dir_l_old=os.path.join(self.dir_ab,"real_l_old.bigfile")
#             self.load_img_dir_rgb_old=os.path.join(self.dir_ab,"real_rgb_old.bigfile")
#             self.load_img_dir_clean=os.path.join(self.dir_ab,"voc_rgb_jpegimages.bigfile")
#             self.load_img_dir_synhaze=os.path.join(self.dir_ab,"voc_rgb_synhaze.bigfile")
#
#             #self.loaded_imgs_l_old=bigfilememoryloader(self.load_img_dir_l_old)
#             self.loaded_imgs_rgb_old=bigfilememoryloader(self.load_img_dir_rgb_old)
#             self.loaded_imgs_clean=bigfilememoryloader(self.load_img_dir_clean)
#             self.loaded_imgs_synhaze=bigfilememoryloader(self.load_img_dir_synhaze)
#
#         #dominb: if domina not in experiment's name ,load voc defultly
#         else:
#             # self.load_img_dir_clean=os.path.join(self.dir_ab,self.opt.test_dataset)
#             self.load_img_dir_clean=os.path.join(self.dir_ab,"voc_rgb_jpegimages.bigfile")
#             self.loaded_imgs_clean=bigfilememoryloader(self.load_img_dir_clean)
#             self.load_img_dir_synhaze=os.path.join(self.dir_ab,"voc_rgb_synhaze.bigfile")
#             self.loaded_imgs_synhaze=bigfilememoryloader(self.load_img_dir_synhaze)
#
#         ####
#         print("-------------filter the imgs whose size <256 in voc-------------")
#         self.filtered_imgs_clean=[]
#         self.filtered_imgs_synhaze=[]
#
#         # 过滤出voc中小于256的图片
#         for i in range(len(self.loaded_imgs_clean)):
#             img_name,img=self.loaded_imgs_clean[i]
#             synimg_name,synimg=self.loaded_imgs_synhaze[i]
#
#             h,w=img.size
#             if h<256 or w<256:
#                 continue
#             self.filtered_imgs_clean.append((img_name,img))
#             self.filtered_imgs_synhaze.append((synimg_name,synimg))
#
#
#         print("--------origin image num is [%d], filtered result is [%d]--------" % (
#         len(self.loaded_imgs_clean), len(self.filtered_imgs_clean)))
#         ## filter these images whose size is less than 256
#
#         # self.img_list=os.listdir(load_img_dir)
#         self.pid = os.getpid()
#
#     def __getitem__(self, index):
#
#
#         is_real_old=0
#
#         sampled_dataset=none
#         degradation=none
#         #随机抽取一张图片(从合成的老照片 和 真实老照片 中)
#         if self.isimage: ## domain a , contains 2 kinds of data: synthetic + real_old
#             p=random.uniform(0,2)
#             if p>=0 and p<1:
#                 if random.uniform(0,1)<0.5:
#                     # sampled_dataset=self.loaded_imgs_l_old
#                     # self.load_img_dir=self.load_img_dir_l_old
#
#                     sampled_dataset=self.loaded_imgs_rgb_old
#                     self.load_img_dir=self.load_img_dir_rgb_old
#                 else:
#                     sampled_dataset=self.loaded_imgs_rgb_old
#                     self.load_img_dir=self.load_img_dir_rgb_old
#                 is_real_old=1
#             if p>=1 and p<2:
#                 sampled_dataset=self.filtered_imgs_synhaze
#                 self.load_img_dir=self.load_img_dir_synhaze
#
#                 degradation=1
#         #domin b
#         else:
#             #载入过滤后小于256大小的图
#             sampled_dataset=self.filtered_imgs_clean
#             self.load_img_dir=self.load_img_dir_clean
#
#         sampled_dataset_len=len(sampled_dataset)
#
#         index=random.randint(0,sampled_dataset_len-1)
#
#         img_name,img = sampled_dataset[index]
#
#         #already old
#         #if degradation is not none:
#         #    #对图片进行降质做旧处理
#         #    img=online_add_degradation_v2(img)
#
#         path=os.path.join(self.load_img_dir,img_name)
#
#         # ab = image.open(path).convert('rgb')
#         # split ab image into a and b
#
#         # apply the same transform to both a and b
#         #随机对图片转换为灰度图
#         if random.uniform(0,1) <0.1:
#             img=img.convert("l")
#             img=img.convert("rgb")
#             ## give a probability p, we convert the rgb image into l
#
#         #调整大小
#         a=img
#         w,h=a.size
#         if w<256 or h<256:
#             a=transforms.scale(256,image.bicubic)(a)
#         # 将图片裁剪为256*256,对于一些小于256的老照片,先进行调整大小
#         ## since we want to only crop the images (256*256), for those old photos whose size is smaller than 256, we first resize them.
#         transform_params = get_params(self.opt, a.size)
#         a_transform = get_transform(self.opt, transform_params)
#
#         b_tensor = inst_tensor = feat_tensor = 0
#         a_tensor = a_transform(a)
#
#         #存入字典
#         #a_tensor  :     old or syn imgtensor;
#         #is_real_old:     1:old ; 0:syn
#         #feat       :     0
#         input_dict = {'label': a_tensor, 'inst': is_real_old, 'image': a_tensor,
#                         'feat': feat_tensor, 'path': path}
#         return input_dict
#
#     def __len__(self):
#         return len(self.loaded_imgs_clean) ## actually, this is useless, since the selected index is just a random number
#
#     def name(self):
#         return 'unpairoldphotos_sr'
#################################    my   ####################        if self.isimage:
#成对图像载入器(原始图及其合成旧图)
# mapping
class pairoldphotosv2(basedataset):
    def initialize(self, opt):
        self.opt = opt
        self.isimage = 'imagan' in opt.name #actually ,useless ;
        self.task = 'old_photo_restoration_training_mapping'
        self.dir_ab = opt.dataroot
        #训练模式,载入
        if opt.istrain:
            path_clear = r'/home/vip/shy/ots/clear_images/'
            path_haze = r'/home/vip/shy/ots/hazy/'
            self.load_img_dir_clean=path_clear
            self.load_img_dir_synhaze=path_haze
 
            self.img_dir_synhaze = os.listdir(self.load_img_dir_synhaze)
            self.loaded_imgs_synhaze=[os.path.join(self.load_img_dir_synhaze,img) for img in self.img_dir_synhaze]
            self.loaded_imgs_clean = []
            for path_i in self.loaded_imgs_synhaze:
                    p,n = os.path.split(path_i)
                    pre,ex = os.path.splitext(n)
                    clear_pre = pre.split('_')[0]
                    clear_path = os.path.join(path_clear,clear_pre+ex)
                    self.loaded_imgs_clean.append(clear_path)
            print('________________filter whose size <256')
            self.filtered_imgs_clean = []
            self.filtered_imgs_synhaze = []
            print('________________now filter syn and clean size <256')
            for i in range(len(self.loaded_imgs_synhaze)):
                img_name_syn = self.loaded_imgs_synhaze[i]
                img = image.open(img_name_syn)
                h, w = img.size
                img_name_clear = self.loaded_imgs_clean[i]
                if h < 256 or w < 256:
                    continue
                self.filtered_imgs_clean.append(img_name_clear)
                self.filtered_imgs_synhaze.append(img_name_syn)
 
            print("--------origin image num is [%d], filtered result is [%d]--------" % (
            len(self.loaded_imgs_clean), len(self.filtered_imgs_clean)))
        #测试模式时,仅载入测试集
        else:
            if self.opt.test_on_synthetic:
                ############valset#########
                path_val_clear = r'/home/vip/shy/sots/outdoor/gt' ######none###############self.opt.path_clear
                path_val_haze = r'/home/vip/shy/sots/outdoor/hazy' #########none#############self.opt.path_haze
                self.load_img_dir_clean = path_val_clear
                self.load_img_dir_synhaze = path_val_haze
 
                self.img_dir_synhaze = os.listdir(self.load_img_dir_synhaze)
                self.loaded_imgs_synhaze = [os.path.join(self.load_img_dir_synhaze, img) for img in
                                            self.img_dir_synhaze]
                self.loaded_imgs_clean = []
                for path_i in self.loaded_imgs_synhaze:
                    p, n = os.path.split(path_i)
                    pre, ex = os.path.splitext(n)
                    clear_pre = pre.split('_')[0]
                    clear_path = os.path.join(self.load_img_dir_clean, clear_pre + ex)
                    self.loaded_imgs_clean.append(clear_path)
                print('________________filter whose size <256')
                self.filtered_val_imgs_clean = []
                self.filtered_val_imgs_synhaze = []
                print('________________now filter val syn and clean size <256')
                for i in range(len(self.loaded_imgs_synhaze)):
                    img_name_syn = self.loaded_imgs_synhaze[i]
                    img = image.open(img_name_syn)
                    h, w = img.size
                    img_name_clear = self.loaded_imgs_clean[i]
                    if h < 256 or w < 256:
                        continue
                    self.filtered_val_imgs_clean.append(img_name_clear)
                    self.filtered_val_imgs_synhaze.append(img_name_syn)
                print('________________finished filter val syn and clean ')
 
            else:
                ############testset#########
                path_test_clear = r'/home/vip/shy/sots/outdoor/gt' ##################self.opt.path_test_clear
                path_test_haze = r'/home/vip/shy/sots/outdoor/hazy' ###################self.opt.path_test_haze
                self.load_img_dir_clean=path_test_clear
                self.load_img_dir_synhaze=path_test_haze
 
                self.img_dir_synhaze = os.listdir(self.load_img_dir_synhaze)
                self.loaded_imgs_synhaze=[os.path.join(self.load_img_dir_synhaze,img) for img in self.img_dir_synhaze]
                self.loaded_imgs_clean = []
                for path_i in self.loaded_imgs_synhaze:
                        p,n = os.path.split(path_i)
                        pre,ex = os.path.splitext(n)
                        clear_pre = pre.split('_')[0]
                        clear_path = os.path.join(self.load_img_dir_clean,clear_pre+ex)
                        self.loaded_imgs_clean.append(clear_path)
                print('________________filter whose size <256')
                self.filtered_test_imgs_clean = []
                self.filtered_test_imgs_synhaze = []
                print('________________now filter testset syn and clean size <256')
                for i in range(len(self.loaded_imgs_synhaze)):
                    img_name_syn = self.loaded_imgs_synhaze[i]
                    img = image.open(img_name_syn)
                    h, w = img.size
                    img_name_clear = self.loaded_imgs_clean[i]
                    if h < 256 or w < 256:
                        continue
                    self.filtered_test_imgs_clean.append(img_name_clear)
                    self.filtered_test_imgs_synhaze.append(img_name_syn)
                print('________________finished filter testset syn and clean ')
 
            print("--------origin image num is [%d], filtered result is [%d]--------" % (
            len(self.loaded_imgs_synhaze), len(self.filtered_test_imgs_synhaze)))
 
 
        self.pid = os.getpid()
 
    def __getitem__(self, index):
 
 
        #训练模式
        if self.opt.istrain:
            #(b为清晰voc数据集)
            img_name_clean = self.filtered_imgs_clean[index]
            b = image.open(img_name_clean)
            img_name_synhaze = self.filtered_imgs_synhaze[index]
            s = image.open(img_name_synhaze)
            path = os.path.join(img_name_clean)
            #生成成对图像(b为清晰voc数据集,a对应的含噪声的图像)
            a=s
 
        ### remind: a is the input and b is corresponding gt
        #ceshi daima wei xiugai #####################################################
        else:
            #测试模式
            #(b为清晰voc数据集,a对应的含噪声的图像)
 
            if self.opt.test_on_synthetic:
                #valset
                img_name_b = self.filtered_test_imgs_clean[index]
                b = image.open(img_name_b)
                img_name_a=self.filtered_test_imgs_synhaze[index]
                a = image.open(img_name_a)
                path = os.path.join(img_name_a)
            else:
                #testset
                img_name_b = self.filtered_val_imgs_clean[index]
                b = image.open(img_name_b)
                img_name_a=self.filtered_val_imgs_synhaze[index]
                a = image.open(img_name_a)
                path = os.path.join(img_name_a)
 
        #去掉透明通道
        # if random.uniform(0,1)<0.1 and self.opt.istrain:
        #     a=a.convert("l")
        #     b=b.convert("l")
        a=a.convert("rgb")
        b=b.convert("rgb")
 
        # apply the same transform to both a and b
        #获取变换相关参数test_dataset
        transform_params = get_params(self.opt, a.size)
        #变换数据,数据增强
        a_transform = get_transform(self.opt, transform_params)
        b_transform = get_transform(self.opt, transform_params)
 
        b_tensor = inst_tensor = feat_tensor = 0
        a_tensor = a_transform(a)
        b_tensor = b_transform(b)
 
        # input_dict = {'label': a_tensor, 'inst': inst_tensor, 'image': b_tensor,
        #             'feat': feat_tensor, 'path': path}
        input_dict = {'label': b_tensor, 'inst': inst_tensor, 'image': a_tensor,
                    'feat': feat_tensor, 'path': path}
 
        return input_dict
 
    def __len__(self):
 
        if self.opt.istrain:
            return len(self.filtered_imgs_clean)
        else:
            return len(self.filtered_test_imgs_clean)
 
    def name(self):
        return 'pairoldphotos'
#
 
 
#
#
# #成对图像载入器(原始图及其合成旧图)
# # mapping
# class pairoldphotos(basedataset):
#     def initialize(self, opt):
#         self.opt = opt
#         self.isimage = 'imagan' in opt.name #actually ,useless ;
#         self.task = 'old_photo_restoration_training_mapping'
#         self.dir_ab = opt.dataroot
#         #训练模式,载入voc
#         if opt.istrain:
#             self.load_img_dir_clean= os.path.join(self.dir_ab, "voc_rgb_jpegimages.bigfile")
#             self.loaded_imgs_clean = bigfilememoryloader(self.load_img_dir_clean)
#
#             self.load_img_dir_synhaze= os.path.join(self.dir_ab, "voc_rgb_synhaze.bigfile")
#             self.loaded_imgs_synhaze = bigfilememoryloader(self.load_img_dir_synhaze)
#
#             print("-------------filter the imgs whose size <256 in voc-------------")
#             #过滤出voc中小于256的图片
#             self.filtered_imgs_clean = []
#             self.filtered_imgs_synhaze = []
#
#             for i in range(len(self.loaded_imgs_clean)):
#                 img_name, img = self.loaded_imgs_clean[i]
#                 synhazeimg_name, synhazeimg = self.loaded_imgs_clean[i]
#
#                 h, w = img.size
#                 if h < 256 or w < 256:
#                     continue
#                 self.filtered_imgs_clean.append((img_name, img))
#                 self.filtered_imgs_synhaze.append((synhazeimg_name, synhazeimg))
#
#             print("--------origin image num is [%d], filtered result is [%d]--------" % (
#             len(self.loaded_imgs_clean), len(self.filtered_imgs_clean)))
#         #测试模式时,仅载入测试集
#         else:
#             self.load_img_dir=os.path.join(self.dir_ab,opt.test_dataset)
#             self.loaded_imgs=bigfilememoryloader(self.load_img_dir)
#
#         self.pid = os.getpid()
#
#     def __getitem__(self, index):
#
#
#         #训练模式
#         if self.opt.istrain:
#             #(b为清晰voc数据集)
#             img_name_clean,b = self.filtered_imgs_clean[index]
#             img_name_synhaze,s = self.filtered_imgs_synhaze[index]
#
#             path = os.path.join(self.load_img_dir_clean, img_name_clean)
#             #生成成对图像(b为清晰voc数据集,a对应的含噪声的图像)
#             if self.opt.use_v2_degradation:
#                 a=s
#             ### remind: a is the input and b is corresponding gt
#         #ceshi daima wei xiugai #####################################################
#         else:
#             #测试模式
#             #(b为清晰voc数据集,a对应的含噪声的图像)
#             if self.opt.test_on_synthetic:
#
#                 img_name_b,b=self.loaded_imgs[index]
#                 a=online_add_degradation_v2(b)
#                 img_name_a=img_name_b
#                 path = os.path.join(self.load_img_dir, img_name_a)
#             else:
#                 img_name_a,a=self.loaded_imgs[index]
#                 img_name_b,b=self.loaded_imgs[index]
#                 path = os.path.join(self.load_img_dir, img_name_a)
#
#         #去掉透明通道
#         if random.uniform(0,1)<0.1 and self.opt.istrain:
#             a=a.convert("l")
#             b=b.convert("l")
#             a=a.convert("rgb")
#             b=b.convert("rgb")
#         ## in p, we convert the rgb into l
#
#
#         ##test on l
#
#         # split ab image into a and b
#         # w, h = img.size
#         # w2 = int(w / 2)
#         # a = img.crop((0, 0, w2, h))
#         # b = img.crop((w2, 0, w, h))
#         w,h=a.size
#         if w<256 or h<256:
#             a=transforms.scale(256,image.bicubic)(a)
#             b=transforms.scale(256, image.bicubic)(b)
#
#         # apply the same transform to both a and b
#         #获取变换相关参数
#         transform_params = get_params(self.opt, a.size)
#         #变换数据,数据增强
#         a_transform = get_transform(self.opt, transform_params)
#         b_transform = get_transform(self.opt, transform_params)
#
#         b_tensor = inst_tensor = feat_tensor = 0
#         a_tensor = a_transform(a)
#         b_tensor = b_transform(b)
#
#         input_dict = {'label': a_tensor, 'inst': inst_tensor, 'image': b_tensor,
#                     'feat': feat_tensor, 'path': path}
#         return input_dict
#
#     def __len__(self):
#
#         if self.opt.istrain:
#             return len(self.filtered_imgs_clean)
#         else:
#             return len(self.loaded_imgs)
#
#     def name(self):
#         return 'pairoldphotos'
# #####################################################################
# #成对带折痕图像载入器
# class pairoldphotos_with_hole(basedataset):
#     def initialize(self, opt):
#         self.opt = opt
#         self.isimage = 'imagegan' in opt.name
#         self.task = 'old_photo_restoration_training_mapping'
#         self.dir_ab = opt.dataroot
#         #训练模式下,载入成对的带有裂痕的合成图片
#         if opt.istrain:
#             self.load_img_dir_clean= os.path.join(self.dir_ab, "voc_rgb_jpegimages.bigfile")
#             self.loaded_imgs_clean = bigfilememoryloader(self.load_img_dir_clean)
#
#             print("-------------filter the imgs whose size <256 in voc-------------")
#             #过滤出大小小于256的图片
#             self.filtered_imgs_clean = []
#             for i in range(len(self.loaded_imgs_clean)):
#                 img_name, img = self.loaded_imgs_clean[i]
#                 h, w = img.size
#                 if h < 256 or w < 256:
#                     continue
#                 self.filtered_imgs_clean.append((img_name, img))
#
#             print("--------origin image num is [%d], filtered result is [%d]--------" % (
#             len(self.loaded_imgs_clean), len(self.filtered_imgs_clean)))
#
#         else:
#             self.load_img_dir=os.path.join(self.dir_ab,opt.test_dataset)
#             self.loaded_imgs=bigfilememoryloader(self.load_img_dir)
#         #载入不规则mask
#         self.loaded_masks = bigfilememoryloader(opt.irregular_mask)
#
#         self.pid = os.getpid()
#
#     def __getitem__(self, index):
#
#
#
#         if self.opt.istrain:
#             img_name_clean,b = self.filtered_imgs_clean[index]
#             path = os.path.join(self.load_img_dir_clean, img_name_clean)
#
#
#             b=transforms.randomcrop(256)(b)
#             a=online_add_degradation_v2(b)
#             ### remind: a is the input and b is corresponding gt
#
#         else:
#             img_name_a,a=self.loaded_imgs[index]
#             img_name_b,b=self.loaded_imgs[index]
#             path = os.path.join(self.load_img_dir, img_name_a)
#
#             #a=a.resize((256,256))
#             a=transforms.centercrop(256)(a)
#             b=a
#
#         if random.uniform(0,1)<0.1 and self.opt.istrain:
#             a=a.convert("l")
#             b=b.convert("l")
#             a=a.convert("rgb")
#             b=b.convert("rgb")
#         ## in p, we convert the rgb into l
#
#         if self.opt.istrain:
#             #载入mask
#             mask_name,mask=self.loaded_masks[random.randint(0,len(self.loaded_masks)-1)]
#         else:
#             # 载入mask
#             mask_name, mask = self.loaded_masks[index%100]
#         #调整mask大小
#         mask = mask.resize((self.opt.loadsize, self.opt.loadsize), image.nearest)
#
#         if self.opt.random_hole and random.uniform(0,1)>0.5 and self.opt.istrain:
#             mask=zero_mask(256)
#
#         if self.opt.no_hole:
#             mask=zero_mask(256)
#
#         #由mask合成带有折痕的图片
#         a,_=irregular_hole_synthesize(a,mask)
#
#         if not self.opt.istrain and self.opt.hole_image_no_mask:
#             mask=zero_mask(256)
#         #获取做旧变换参数
#         transform_params = get_params(self.opt, a.size)
#         a_transform = get_transform(self.opt, transform_params)
#         b_transform = get_transform(self.opt, transform_params)
#         #对mask进行相同的左右翻转
#         if transform_params['flip'] and self.opt.istrain:
#             mask=mask.transpose(image.flip_left_right)
#         #归一化
#         mask_tensor = transforms.totensor()(mask)
#
#
#         b_tensor = inst_tensor = feat_tensor = 0
#         a_tensor = a_transform(a)
#         b_tensor = b_transform(b)
#
#         input_dict = {'label': a_tensor, 'inst': mask_tensor[:1], 'image': b_tensor,
#                     'feat': feat_tensor, 'path': path}
#         return input_dict
#
#     def __len__(self):
#
#         if self.opt.istrain:
#             return len(self.filtered_imgs_clean)
#
#         else:
#             return len(self.loaded_imgs)
#
#     def name(self):
#         return 'pairoldphotos_with_hole'

用于去雾时,我改写得代码如下,增加了利用清晰图像和对应的深度图生成雾图的代码,合并至源代码中的online_dataset_for_odl_photos.py中。如下

# copyright (c) microsoft corporation.
# licensed under the mit license.
 
import os.path
import io
import zipfile
from data.base_dataset import basedataset, get_params, get_transform, normalize
from data.image_folder import make_dataset
import torchvision.transforms as transforms
from data.load_bigfile import bigfilememoryloader
from data.load_bigfilev2 import bigfilememoryloaderv2
 
from io import bytesio
import os
import glob
import cv2, math
import random
import numpy as np
import h5py
import os
from pil import image
import scipy.io
 
def pil_to_np(img_pil):
    '''converts image in pil format to np.array.
    from w x h x c [0...255] to c x w x h [0..1]
    '''
    ar = np.array(img_pil)
 
    if len(ar.shape) == 3:
        ar = ar.transpose(2, 0, 1)
    else:
        ar = ar[none, ...]
 
    return ar.astype(np.float32) / 255.
 
 
def np_to_pil(img_np):
    '''converts image in np.array format to pil image.
    from c x w x h [0..1] to  w x h x c [0...255]
    '''
    ar = np.clip(img_np * 255, 0, 255).astype(np.uint8)
 
    if img_np.shape[0] == 1:
        ar = ar[0]
    else:
        ar = ar.transpose(1, 2, 0)
 
    return image.fromarray(ar)
 
def synthesize_salt_pepper(image,amount,salt_vs_pepper):
 
    ## give pil, return the noisy pil
 
    img_pil=pil_to_np(image)
 
    out = img_pil.copy()
    p = amount
    q = salt_vs_pepper
    flipped = np.random.choice([true, false], size=img_pil.shape,
                               p=[p, 1 - p])
    salted = np.random.choice([true, false], size=img_pil.shape,
                              p=[q, 1 - q])
    peppered = ~salted
    out[flipped & salted] = 1
    out[flipped & peppered] = 0.
    noisy = np.clip(out, 0, 1).astype(np.float32)
 
 
    return np_to_pil(noisy)
 
def synthesize_gaussian(image,std_l,std_r):
 
    ## give pil, return the noisy pil
 
    img_pil=pil_to_np(image)
 
    mean=0
    std=random.uniform(std_l/255.,std_r/255.)
    gauss=np.random.normal(loc=mean,scale=std,size=img_pil.shape)
    noisy=img_pil+gauss
    noisy=np.clip(noisy,0,1).astype(np.float32)
 
    return np_to_pil(noisy)
 
def synthesize_speckle(image,std_l,std_r):
 
    ## give pil, return the noisy pil
 
    img_pil=pil_to_np(image)
 
    mean=0
    std=random.uniform(std_l/255.,std_r/255.)
    gauss=np.random.normal(loc=mean,scale=std,size=img_pil.shape)
    noisy=img_pil+gauss*img_pil
    noisy=np.clip(noisy,0,1).astype(np.float32)
 
    return np_to_pil(noisy)
 
 
def synthesize_low_resolution(img):
    w,h=img.size
 
    new_w=random.randint(int(w/2),w)
    new_h=random.randint(int(h/2),h)
 
    img=img.resize((new_w,new_h),image.bicubic)
 
    if random.uniform(0,1)<0.5:
        img=img.resize((w,h),image.nearest)
    else:
        img = img.resize((w, h), image.bilinear)
 
    return img
 
 
 
 
def converttojpeg(im,quality):
    with bytesio() as f:
        im.save(f, format='jpeg',quality=quality)
        f.seek(0)
        return image.open(f).convert('rgb')
 
 
def blur_image_v2(img):
 
 
    x=np.array(img)
    kernel_size_candidate=[(3,3),(5,5),(7,7)]
    kernel_size=random.sample(kernel_size_candidate,1)[0]
    std=random.uniform(1.,5.)
 
    #print("the gaussian kernel size: (%d,%d) std: %.2f"%(kernel_size[0],kernel_size[1],std))
    blur=cv2.gaussianblur(x,kernel_size,std)
 
    return image.fromarray(blur.astype(np.uint8))
def perlin_noise(im,varargin):
    """
        this is the function for adding perlin noise to the depth map. it is a
    simplified implementation of the paper:
    an image sunthesizer
    ken perlin, siggraph, jul. 1985
    the bicubic interpolation is used, compared to the original version.
    reference:
    hazerd: an outdoor scene dataset and benchmark for single image dehazing
    ieee international conference on image processing, sep 2017
    the paper and additional information on the project are available at:
    https://labsites.rochester.edu/gsharma/research/computer-vision/hazerd/
    if you use this code, please cite our paper.
    input:
      im: depth map
      varargin{1}: decay term
    output:
      im: result of transmission with perlin noise added
    authors:
      yanfu zhang: yzh185@ur.rochester.edu
      li ding: l.ding@rochester.edu
      gaurav sharma: gaurav.sharma@rochester.edu
    last update: may 2017
    :return:
    """
    # (h, w, c) = im.shape
    # i = 1
    # if nargin == 1:
    #     decay = 2
    # else:
    #     decay = varargin{1}
    # l_bound = min(h,w)
    # while i <= l_bound:
    #     d = imresize(randn(i, i)*decay, im.shape, 'bicubic')
    #     im = im+d
    #     i = i*2
    # im = c(im);
    # return im
    pass
 
def srgb2lrgb(i0):
    gamma = ((i0 + 0.055) / 1.055)**2.4
    scale = i0 / 12.92
    return np.where (i0 > 0.04045, gamma, scale)
 
def lrgb2srgb(i1):
    gamma =  1.055*i1**(1/2.4)-0.055
    scale = i1 * 12.92
    return np.where (i1 > 0.0031308, gamma, scale)
 
#return : depth matrix
def get_depth(depth_or_trans_name):
    #depth_or_trans_name为mat类型文件或者img类型文件地址
    data = scipy.io.loadmat(depth_or_trans_name)
    depths = data['imdepth'] #深度变量
    #print(data.keys())  #打印mat文件中所有变量
    depths = np.array(depths)
    return depths
 
 
 
 
 
def irregular_hole_synthesize(img,mask):
 
    img_np=np.array(img).astype('uint8')
    mask_np=np.array(mask).astype('uint8')
    mask_np=mask_np/255
    img_new=img_np*(1-mask_np)+mask_np*255
 
    hole_img=image.fromarray(img_new.astype('uint8')).convert("rgb")
 
    return hole_img,mask.convert("l")
 
def zero_mask(size):
    x=np.zeros((size,size,3)).astype('uint8')
    mask=image.fromarray(x).convert("rgb")
    return mask
 
def hazy_simu(img_name,depth_or_trans_name,airlight=0.76,is_imdepth=1): ##for outdoor
    """
    this is the function for haze simulation with the parameters given by
    the paper:
    hazerd: an outdoor scene dataset and benchmark for single image dehazing
    ieee internation conference on image processing, sep 2017
    the paper and additional information on the project are available at:
    https://labsites.rochester.edu/gsharma/research/computer-vision/hazerd/
    if you use this code, please cite our paper.
    important note: the code uses the convention that pixel locations with a
    depth value of 0 correspond to objects that are very far and for the
    simulation of haze these are placed a distance of 2 times the visual
    range.
    authors:
    yanfu zhang: yzh185@ur.rochester.edu
    li ding: l.ding@rochester.edu
    gaurav sharma: gaurav.sharma@rochester.edu
    last update: may 2017
    python version update : aug 2021
    authors :
    haoying sun : 1913434222@qq.com
    parse inputs and set default values
    set default parameter values. some of these are used only if they are not
    passed in
    :param img_name: the directory and name of a haze-free rgb image, the name
                     should be in the format of ..._rgb.jpg
    :param depth_name: the corresponding directory and name of the depth map, in
                     .mat file, the name should be in the format of ..._depth.mat
    :param save_dir: the directory to save the simulated images
    :param pert_perlin: 1 for adding perlin noise, default 0
    :param airlight:  3*1 matrix in the range [0,1]
    :param visual_range: a vector of any size
    :return: image name of hazy image
    """
    # if random.uniform(0, 1) < 0.5:
    visual_range = [0.05, 0.1, 0.2, 0.5, 1]  #  visual range in km #可自行调整,或者使用range函数设置区间,此时需要修改beta_param,尚未研究
    beta_param = 3.912     #default beta parameter corresponding to visual range of 1000m
 
    a = airlight
    #print('simulating hazy image for:{}'.format(img_name))
    vr = random.choice(visual_range)
 
    #print('viusal value: {} km'.format(vr) )
    #im1 = cv2.imread(img_name)
    img_pil = pil_to_np(img_name)
 
    #convert srgb to linear rgb
    i = srgb2lrgb(img_pil)
 
    if is_imdepth:
        depths = depth_or_trans_name
 
        d = depths/1000   # convert meter to kilometer
        if depths.max()==0:
            d = np.where(d == 0,0.01, d) ####
        else:
            d = np.where(d==0,2*vr,d)
        #set regions where depth value is set to 0 to indicate no valid depth to
        #a distance of two times the visual range. these regions typically
        #correspond to sky areas
 
        #convert depth map to transmission
        beta = beta_param / vr
        beta_return = beta
        beta = np.ones(d.shape) * beta
        transmission = np.exp((-beta*d))
        transmission_3 = np.array([transmission,transmission,transmission])
 
        #obtain simulated linear rgb hazy image.eq. 3 in the hazerd paper
        ic = transmission_3 * i + (1 - transmission_3) * a
    else:
        ic = pil_to_np(depth_or_trans_name) * i + (1 - pil_to_np(depth_or_trans_name)) * a
 
    # convert linear rgb to srgb
    i2 = lrgb2srgb(ic)
    haze_img = np_to_pil(i2)
    # haze_img = np.asarray(haze_img)
    # haze_img = cv2.cvtcolor(haze_img, cv2.color_rgb2bgr)
    # haze_img = image.fromarray(haze_img)
    return haze_img,airlight,beta_return
 
def hazy_reside_training(img_name,depth_or_trans_name,is_imdepth=1):
    """
    reside的 training中:a :(0.7, 1.0) ,   beta:(0.6, 1.8)
    :param img_name:
    :param depth_or_trans_name:
    :param pert_perlin:
    :param is_imdepth:
    :return:
    """
    beta = random.uniform(0.6, 1.8)
    beta_return = beta
    airlight = random.uniform(0.7, 1.0)
 
    a = airlight
 
    #print('viusal value: {} km'.format(vr) )
    #im1 = cv2.imread(img_name)
    img_pil = pil_to_np(img_name)
 
    #convert srgb to linear rgb
    i = srgb2lrgb(img_pil)
 
    if is_imdepth:
        depths = depth_or_trans_name
 
        #convert depth map to transmission
        if depths.max()==0:
            d = np.where(depths == 0,1, depths)
        else:
            d = depths / depths.max()
            d = np.where(d == 0, 1, d)
 
        beta = np.ones(d.shape) * beta
        transmission = np.exp((-beta*d))
        transmission_3 = np.array([transmission,transmission,transmission])
 
        #obtain simulated linear rgb hazy image.eq. 3 in the hazerd paper
        ic = transmission_3 * i + (1 - transmission_3) * a
 
    else:
        ic = pil_to_np(depth_or_trans_name) * i + (1 - pil_to_np(depth_or_trans_name)) * a
 
    # convert linear rgb to srgb
    i2 = lrgb2srgb(ic)
    #i2 = cv2.cvtcolor(i2, cv2.color_bgr2rgb)
 
    haze_img = np_to_pil(i2)
    # haze_img = np.asarray(haze_img)
    # haze_img = cv2.cvtcolor(haze_img, cv2.color_rgb2bgr)
    # haze_img = image.fromarray(haze_img)
    return haze_img,airlight,beta_return
 
def hazy_reside_ots(img_name,depth_or_trans_name,is_imdepth=1):
    """
    reside的 ots中:a [0.8, 0.85, 0.9, 0.95, 1] ,   beta:[0.04, 0.06, 0.08, 0.1, 0.12, 0.16, 0.2]
    :param img_name:
    :param depth_or_trans_name:
    :param pert_perlin:
    :param is_imdepth:
    :return:
    """
    beta = random.choice([0.04, 0.06, 0.08, 0.1, 0.12, 0.16, 0.2])
    beta_return = beta
    airlight = random.choice([0.8, 0.85, 0.9, 0.95, 1])
    #print(beta)
    #print(airlight)
    a = airlight
 
    #print('viusal value: {} km'.format(vr) )
    #im1 = cv2.imread(img_name)
 
    #img = cv2.cvtcolor(np.asarray(img_name), cv2.color_rgb2bgr)
    img_pil = pil_to_np(img_name)
 
    #convert srgb to linear rgb
    i = srgb2lrgb(img_pil)
 
    if is_imdepth:
        depths = depth_or_trans_name
        #convert depth map to transmission
        if depths.max()==0:
                d = np.where(depths == 0, 1, depths)
        else:
            d = depths/(depths.max())
            d = np.where(d == 0, 1, d)
 
        beta = np.ones(d.shape) * beta
        transmission = np.exp((-beta*d))
        transmission_3 = np.array([transmission,transmission,transmission])
 
        #obtain simulated linear rgb hazy image.eq. 3 in the hazerd paper
        ic = transmission_3 * i + (1 - transmission_3) * a
 
    else:
        ic = pil_to_np(depth_or_trans_name) * i + (1 - pil_to_np(depth_or_trans_name)) * a
 
    # convert linear rgb to srgb
    i2 = lrgb2srgb(ic)
    haze_img = np_to_pil(i2)
 
    #haze_img = np.asarray(haze_img)
    #haze_img = cv2.cvtcolor(haze_img, cv2.color_rgb2bgr)
    #haze_img = image.fromarray(haze_img)
    return haze_img,airlight,beta_return
def online_add_degradation_v2(img,depth_or_trans):
    noise = 0
    task_id=np.random.permutation(4)
    if random.uniform(0,1)<0.3:
        noise = 1
        #print('noise')
        for x in task_id:
            #为增加更多变化,随机进行30%的丢弃,即<0.7
            if x==0 and random.uniform(0,1)<0.7:
                img = blur_image_v2(img)
            if x==1 and random.uniform(0,1)<0.7:
                flag = random.choice([1, 2, 3])
                if flag == 1:
                    img = synthesize_gaussian(img, 5, 50) # gaussian white noise with σ ∈ [5,50]
                if flag == 2:
                    img = synthesize_speckle(img, 5, 50)
                if flag == 3:
                    img = synthesize_salt_pepper(img, random.uniform(0, 0.01), random.uniform(0.3, 0.8))
            if x==2 and random.uniform(0,1)<0.7:
                img=synthesize_low_resolution(img)
 
            if x==3 and random.uniform(0,1)<0.7:
                img=converttojpeg(img,random.randint(40,100))
                #jpeg compression whose level is in the range of [40,100]
    add_haze = random.choice([1,2,3])
    if add_haze == 1:
        img, airlight, beta  = hazy_reside_ots(img, depth_or_trans)
    elif add_haze  == 2:
        img, airlight, beta  = hazy_simu(img, depth_or_trans)
    else:
        img, airlight, beta  = hazy_reside_training(img, depth_or_trans)
    # else:
    #     if add_haze < 0.1:
    #         img = hazy_reside_ots(img, depth_or_trans)
    #     elif add_haze > 0.1 and add_haze < 0.2:
    #         img = hazy_simu(img, depth_or_trans)
    #     else:
    #         img = hazy_reside_training(img, depth_or_trans)
    return img#,noise,airlight,beta
 
 
class unpairoldphotos_sr(basedataset):  ## synthetic + real old
    def initialize(self, opt):
        self.opt = opt
        self.isimage = 'domaina' in opt.name
        self.task = 'old_photo_restoration_training_vae'
        self.dir_ab = opt.dataroot
        if self.isimage:
 
            self.load_npy_dir_depth=os.path.join(self.dir_ab,"voc_rgb_depthnpy.bigfile")
            self.load_img_dir_rgb_old=os.path.join(self.dir_ab,"real_rgb_old.bigfile")
            self.load_img_dir_clean=os.path.join(self.dir_ab,"voc_rgb_jpegimages.bigfile")
 
            self.loaded_npys_depth=bigfilememoryloaderv2(self.load_npy_dir_depth)
            self.loaded_imgs_rgb_old=bigfilememoryloader(self.load_img_dir_rgb_old)
            self.loaded_imgs_clean=bigfilememoryloader(self.load_img_dir_clean)
 
        else:
            # self.load_img_dir_clean=os.path.join(self.dir_ab,self.opt.test_dataset)
            self.load_img_dir_clean=os.path.join(self.dir_ab,"voc_rgb_jpegimages.bigfile")
            self.loaded_imgs_clean=bigfilememoryloader(self.load_img_dir_clean)
 
            self.load_npy_dir_depth=os.path.join(self.dir_ab,"voc_rgb_depthnpy.bigfile")
            self.loaded_npys_depth=bigfilememoryloaderv2(self.load_npy_dir_depth)
 
        ####
        print("-------------filter the imgs whose size <256 in voc-------------")
        self.filtered_imgs_clean=[]
        self.filtered_npys_depth = []
        for i in range(len(self.loaded_imgs_clean)):
            img_name,img=self.loaded_imgs_clean[i]
            npy_name, npy = self.loaded_npys_depth[i]
            h,w=img.size
            if h<256 or w<256:
                continue
            self.filtered_imgs_clean.append((img_name,img))
            self.filtered_npys_depth.append((npy_name, npy))
        print("--------origin image num is [%d], filtered result is [%d]--------" % (
        len(self.loaded_imgs_clean), len(self.filtered_imgs_clean)))
        ## filter these images whose size is less than 256
 
        # self.img_list=os.listdir(load_img_dir)
        self.pid = os.getpid()
 
    def __getitem__(self, index):
 
 
        is_real_old=0
 
        sampled_dataset=none
        sampled_depthdataset = none
        degradation=none
        if self.isimage: ## domain a , contains 2 kinds of data: synthetic + real_old
            p=random.uniform(0,2)
            if p>=0 and p<1:
                #if random.uniform(0,1)<0.5:
                    #  buyao  huidutu
                    #sampled_dataset=self.loaded_imgs_l_old
                    #self.load_img_dir=self.load_img_dir_l_old
                    sampled_dataset = self.loaded_imgs_rgb_old
                    self.load_img_dir = self.load_img_dir_rgb_old
 
 
                # else:
                #     sampled_dataset=self.loaded_imgs_rgb_old
                #     self.load_img_dir=self.load_img_dir_rgb_old
 
 
                    is_real_old=1
            if p>=1 and p<2:
                sampled_dataset=self.filtered_imgs_clean
                self.load_img_dir=self.load_img_dir_clean
 
                sampled_depthdataset=self.filtered_npys_depth
                self.load_npy_dir=self.load_npy_dir_depth
 
                degradation=1
        else:
 
            sampled_dataset=self.filtered_imgs_clean
            self.load_img_dir=self.load_img_dir_clean
 
            sampled_depthdataset = self.filtered_npys_depth
            self.load_npy_dir = self.load_npy_dir_depth
 
        sampled_dataset_len=len(sampled_dataset)
        #print('sampled_dataset_len::::',sampled_dataset_len)
        index=random.randint(0,sampled_dataset_len-1)
 
        img_name,img = sampled_dataset[index]
        # print(img_name)
        # print(img)
        # print(index)
 
        #print(npy_name)
        #print(npy)
        if degradation is not none:
            npy_name, npy = sampled_depthdataset[index]
            img=online_add_degradation_v2(img,npy)
        path=os.path.join(self.load_img_dir,img_name)
 
        # ab = image.open(path).convert('rgb')
        # split ab image into a and b
 
        # apply the same transform to both a and b
 
        # if random.uniform(0,1) <0.1:
        #     img=img.convert("l")
        #     img=img.convert("rgb")
        #     ## give a probability p, we convert the rgb image into l
 
 
        a=img
        w,h=a.size
        if w<256 or h<256:
            a=transforms.scale(256,image.bicubic)(a)
        ## since we want to only crop the images (256*256), for those old photos whose size is smaller than 256, we first resize them.
 
        transform_params = get_params(self.opt, a.size)
        a_transform = get_transform(self.opt, transform_params)
 
        b_tensor = inst_tensor = feat_tensor = 0
        a_tensor = a_transform(a)
 
 
        input_dict = {'label': a_tensor, 'inst': is_real_old, 'image': a_tensor,
                        'feat': feat_tensor, 'path': path}
        return input_dict
 
    def __len__(self):
        return len(self.loaded_imgs_clean) ## actually, this is useless, since the selected index is just a random number
 
    def name(self):
        return 'unpairoldphotos_sr'
 
 
class pairoldphotos(basedataset):
    def initialize(self, opt):
        self.opt = opt
        self.isimage = 'imagegan' in opt.name
        self.task = 'old_photo_restoration_training_mapping'
        self.dir_ab = opt.dataroot
        if opt.istrain:
            self.load_img_dir_clean= os.path.join(self.dir_ab, "voc_rgb_jpegimages.bigfile")
            self.loaded_imgs_clean = bigfilememoryloader(self.load_img_dir_clean)
 
            self.load_npy_dir_depth= os.path.join(self.dir_ab, "voc_rgb_depthnpy.bigfile")
            self.loaded_npys_depth = bigfilememoryloaderv2(self.load_npy_dir_depth)
 
            print("-------------filter the imgs whose size <256 in voc-------------")
            self.filtered_imgs_clean = []
            self.filtered_npys_depth = []
            for i in range(len(self.loaded_imgs_clean)):
                img_name, img = self.loaded_imgs_clean[i]
                npy_name, npy = self.loaded_npys_depth[i]
                h, w = img.size
                if h < 256 or w < 256:
                    continue
                self.filtered_imgs_clean.append((img_name, img))
                self.filtered_npys_depth.append((npy_name, npy))
            print("--------origin image num is [%d], filtered result is [%d]--------" % (
            len(self.loaded_imgs_clean), len(self.filtered_imgs_clean)))
 
        else:
            self.load_img_dir=os.path.join(self.dir_ab,opt.test_dataset)
            self.loaded_imgs=bigfilememoryloader(self.load_img_dir)
 
            self.load_depth_dir = os.path.join(self.dir_ab, opt.test_depthdataset)
            self.loaded_npys = bigfilememoryloaderv2(self.load_depth_dir)
 
 
        self.pid = os.getpid()
 
    def __getitem__(self, index):
 
 
 
        if self.opt.istrain:
            img_name_clean,b = self.filtered_imgs_clean[index]
            npy_name_depth,d = self.filtered_npys_depth[index]
            path = os.path.join(self.load_img_dir_clean, img_name_clean)
            if self.opt.use_v2_degradation:
                a=online_add_degradation_v2(b,d)
            ### remind: a is the input and b is corresponding gt
        else:
 
            if self.opt.test_on_synthetic:
 
                img_name_b,b=self.loaded_imgs[index]
                npy_name_d,d=self.loaded_npys[index]
                a=online_add_degradation_v2(b,d)
                a.save('../mybig_data/' + index + '.jpg')
 
                img_name_a=img_name_b
                path = os.path.join(self.load_img_dir, img_name_a)
            else:
                img_name_a,a=self.loaded_imgs[index]
                img_name_b,b=self.loaded_imgs[index]
                path = os.path.join(self.load_img_dir, img_name_a)
 
 
        # if random.uniform(0,1)<0.1 and self.opt.istrain:
        #     a=a.convert("l")
        #     b=b.convert("l")
        #     a=a.convert("rgb")
        #     b=b.convert("rgb")
        # ## in p, we convert the rgb into l
 
 
        ##test on l
 
        # split ab image into a and b
        # w, h = img.size
        # w2 = int(w / 2)
        # a = img.crop((0, 0, w2, h))
        # b = img.crop((w2, 0, w, h))
        w,h=a.size
        if w<256 or h<256:
            a=transforms.scale(256,image.bicubic)(a)
            b=transforms.scale(256, image.bicubic)(b)
 
        # apply the same transform to both a and b
        transform_params = get_params(self.opt, a.size)
        a_transform = get_transform(self.opt, transform_params)
        b_transform = get_transform(self.opt, transform_params)
 
        b_tensor = inst_tensor = feat_tensor = 0
        a_tensor = a_transform(a)
        b_tensor = b_transform(b)
 
        input_dict = {'label': a_tensor, 'inst': inst_tensor, 'image': b_tensor,
                    'feat': feat_tensor, 'path': path}
        return input_dict
 
    def __len__(self):
 
        if self.opt.istrain:
            return len(self.filtered_imgs_clean)
        else:
            return len(self.loaded_imgs)
 
    def name(self):
        return 'pairoldphotos'
 
#del
class pairoldphotos_with_hole(basedataset):
    def initialize(self, opt):
        self.opt = opt
        self.isimage = 'imagegan' in opt.name
        self.task = 'old_photo_restoration_training_mapping'
        self.dir_ab = opt.dataroot
        if opt.istrain:
            self.load_img_dir_clean= os.path.join(self.dir_ab, "voc_rgb_jpegimages.bigfile")
            self.loaded_imgs_clean = bigfilememoryloader(self.load_img_dir_clean)
 
            print("-------------filter the imgs whose size <256 in voc-------------")
            self.filtered_imgs_clean = []
            self.filtered_npys_depth = []
            for i in range(len(self.loaded_imgs_clean)):
                img_name, img = self.loaded_imgs_clean[i]
                npy_name, npy = self.loaded_npys_depth[i]
                h, w = img.size
                if h < 256 or w < 256:
                    continue
                self.filtered_imgs_clean.append((img_name, img))
                self.filtered_npys_depth.append((npy_name, npy))
            print("--------origin image num is [%d], filtered result is [%d]--------" % (
            len(self.loaded_imgs_clean), len(self.filtered_imgs_clean)))
 
        else:
            self.load_img_dir=os.path.join(self.dir_ab,opt.test_dataset)
            self.loaded_imgs=bigfilememoryloader(self.load_img_dir)
 
            self.load_depth_dir = os.path.join(self.dir_ab, opt.test_depthdataset)
            self.loaded_npys = bigfilememoryloaderv2(self.load_depth_dir)
 
        self.loaded_masks = bigfilememoryloader(opt.irregular_mask)
 
        self.pid = os.getpid()
 
    def __getitem__(self, index):
 
 
 
        if self.opt.istrain:
            img_name_clean,b = self.filtered_imgs_clean[index]
            npy_name_depth, d = self.filtered_npys_depth[index]
 
            path = os.path.join(self.load_img_dir_clean, img_name_clean)
 
            a=online_add_degradation_v2(b,d)
            b=transforms.randomcrop(256)(b)
 
            ### remind: a is the input and b is corresponding gt
 
        else:
            img_name_a,a=self.loaded_imgs[index]
            img_name_b,b=self.loaded_imgs[index]
            path = os.path.join(self.load_img_dir, img_name_a)
 
            #a=a.resize((256,256))
            a=transforms.centercrop(256)(a)
            b=a
 
        if random.uniform(0,1)<0.1 and self.opt.istrain:
            a=a.convert("l")
            b=b.convert("l")
            a=a.convert("rgb")
            b=b.convert("rgb")
        ## in p, we convert the rgb into l
 
        if self.opt.istrain:
            mask_name,mask=self.loaded_masks[random.randint(0,len(self.loaded_masks)-1)]
        else:
            mask_name, mask = self.loaded_masks[index%100]
        mask = mask.resize((self.opt.loadsize, self.opt.loadsize), image.nearest)
 
        if self.opt.random_hole and random.uniform(0,1)>0.5 and self.opt.istrain:
            mask=zero_mask(256)
 
        if self.opt.no_hole:
            mask=zero_mask(256)
 
 
        a,_=irregular_hole_synthesize(a,mask)
 
        if not self.opt.istrain and self.opt.hole_image_no_mask:
            mask=zero_mask(256)
 
        transform_params = get_params(self.opt, a.size)
        a_transform = get_transform(self.opt, transform_params)
        b_transform = get_transform(self.opt, transform_params)
 
        if transform_params['flip'] and self.opt.istrain:
            mask=mask.transpose(image.flip_left_right)
 
        mask_tensor = transforms.totensor()(mask)
 
 
        b_tensor = inst_tensor = feat_tensor = 0
        a_tensor = a_transform(a)
        b_tensor = b_transform(b)
 
        input_dict = {'label': a_tensor, 'inst': mask_tensor[:1], 'image': b_tensor,
                    'feat': feat_tensor, 'path': path}
        return input_dict
 
    def __len__(self):
 
        if self.opt.istrain:
            return len(self.filtered_imgs_clean)
 
        else:
            return len(self.loaded_imgs)
 
    def name(self):
        return 'pairoldphotos_with_hole'

把比较重要的改动写了下,以上在之前得博客中有的提到过。

训练测试

run.py里前面有三行存放了训练、测试、数据准备(请查看data文件夹里里的代码,可以不需要此部分)的代码,需要酌情修改。如下

############test############
#python run.py --input_folder /home/vip/shy/hbdh/haze --output_folder /home/vip/shy/hbdh/l1-feat30-01 --gpu 0  
 
############dataset prepare#################
# python create_bigfile.py
 
############train a、b、mapping############
#python train_domain_a.py --use_v2_degradation --continue_train --training_dataset domain_a --name domaina_sr_old_photos --label_nc 0 --loadsize 256 --finesize 256 --dataroot ../mybig_data/ --no_instance --resize_or_crop crop_only --batchsize 48 --no_html --gpu_ids 0,1 --self_gen --nthreads 4 --n_downsample_global 3 --k_size 4 --use_v2 --mc 64 --start_r 1 --kl 1 --no_cgan --outputs_dir your_output_folder --checkpoints_dir your_ckpt_folder
#python train_domain_b.py --continue_train --training_dataset domain_b --name domainb_old_photos --label_nc 0 --loadsize 256 --finesize 256 --dataroot ../mybig_data/  --no_instance --resize_or_crop crop_only --batchsize 48 --no_html --gpu_ids 0,1 --self_gen --nthreads 4 --n_downsample_global 3 --k_size 4 --use_v2 --mc 64 --start_r 1 --kl 1 --no_cgan --outputs_dir your_output_folder  --checkpoints_dir your_ckpt_folder
#python train_mapping.py --use_v2_degradation --training_dataset mapping --use_vae_which_epoch latest --continue_train --name mapping_quality --label_nc 0 --loadsize 256 --finesize 256 --dataroot ../mybig_data/ --no_instance --resize_or_crop crop_only --batchsize 16 --no_html --gpu_ids 0,1 --nthreads 8 --load_pretraina ./your_ckpt_folder/domaina_sr_old_photos --load_pretrainb ./your_ckpt_folder/domainb_old_photos --l2_feat 60 --n_downsample_global 3 --mc 64 --k_size 4 --start_r 1 --mapping_n_block 6 --map_mc 512 --use_l1_feat --outputs_dir your_output_folder --checkpoints_dir your_ckpt_folder

数据集

注意,以下四个文件为我按照原始论文打包的训练集,其中voc_rgb_depthnpy.bigfile文件有两个,1.6g大小的为nyuv2中的深度矩阵(1399张),2.9g的为nyuv2中的深度矩阵和额外我添加的图像对应的深度矩阵(504张裁剪后的hazerd数据集和85张我收集的天空图像)。voc_rgb_jpegimages.bigfile为深度矩阵对应的真实图像。

Python实现图像去雾效果的示例代码

以上的bigfile文件具体截图如下:

voc_rgb_jpegimages.bigfile 1.2g如下

Python实现图像去雾效果的示例代码

voc_rgb_jpegimages.bigfile 1.69g除了上面nyuv2外,还有我处理的(hazerd和收集的天空)如下:

Python实现图像去雾效果的示例代码

Python实现图像去雾效果的示例代码

深度矩阵就是上面图像对应的深度npy文件。

另外还是真实雾图,需要自己下载,可以酌情滤掉过于低质的图像,我利用的是开源数据集reside beta

下载地址

根据个人需要下载,里面有些文件过大。

我把我的去雾的代码打包并发布,地址如下:

获取链接  提取码:haze

加雾的代码其实很简单,就是把输入和输出反一下,然后让align部分对应的一行代码反一下。

以上就是python实现图像去雾效果的示例代码的详细内容,更多关于python图像去雾的资料请关注其它相关文章!