gcanet图像去雾python实现

时间: 2024-01-10 10:02:33 浏览: 29
GCANet是一种图像去雾算法,可以使用Python实现。以下是一个实现的示例代码: ```python import cv2 import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.utils.data import DataLoader, Dataset import os # 定义GCANet模型 class GCANet(nn.Module): def __init__(self): super(GCANet, self).__init__() self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1) self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1) self.conv3 = nn.Conv2d(32, 64, kernel_size=3, padding=1) self.conv4 = nn.Conv2d(64, 128, kernel_size=3, padding=1) self.conv5 = nn.Conv2d(128, 256, kernel_size=3, padding=1) self.conv6 = nn.Conv2d(256, 512, kernel_size=3, padding=1) self.conv7 = nn.Conv2d(512, 1024, kernel_size=3, padding=1) self.conv8 = nn.Conv2d(1024, 2048, kernel_size=3, padding=1) self.conv9 = nn.Conv2d(2048, 1024, kernel_size=3, padding=1) self.conv10 = nn.Conv2d(1024, 512, kernel_size=3, padding=1) self.conv11 = nn.Conv2d(512, 256, kernel_size=3, padding=1) self.conv12 = nn.Conv2d(256, 128, kernel_size=3, padding=1) self.conv13 = nn.Conv2d(128, 64, kernel_size=3, padding=1) self.conv14 = nn.Conv2d(64, 32, kernel_size=3, padding=1) self.conv15 = nn.Conv2d(32, 16, kernel_size=3, padding=1) self.conv16 = nn.Conv2d(16, 3, kernel_size=3, padding=1) self.relu = nn.ReLU(inplace=True) self.pool = nn.MaxPool2d(kernel_size=2, stride=2) self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) self.sigmoid = nn.Sigmoid() self.gamma = nn.Parameter(torch.zeros(1)) self.beta = nn.Parameter(torch.zeros(1)) def forward(self, x): x1 = self.relu(self.conv1(x)) x = self.pool(x1) x2 = self.relu(self.conv2(x)) x = self.pool(x2) x3 = self.relu(self.conv3(x)) x = self.pool(x3) x4 = self.relu(self.conv4(x)) x = self.pool(x4) x5 = self.relu(self.conv5(x)) x = self.pool(x5) x6 = self.relu(self.conv6(x)) x = self.pool(x6) x7 = self.relu(self.conv7(x)) x = self.pool(x7) x8 = self.relu(self.conv8(x)) x = self.upsample(x8) x = torch.cat([x, x7], dim=1) x = self.relu(self.conv9(x)) x = self.upsample(x) x = torch.cat([x, x6], dim=1) x = self.relu(self.conv10(x)) x = self.upsample(x) x = torch.cat([x, x5], dim=1) x = self.relu(self.conv11(x)) x = self.upsample(x) x = torch.cat([x, x4], dim=1) x = self.relu(self.conv12(x)) x = self.upsample(x) x = torch.cat([x, x3], dim=1) x = self.relu(self.conv13(x)) x = self.upsample(x) x = torch.cat([x, x2], dim=1) x = self.relu(self.conv14(x)) x = self.upsample(x) x = torch.cat([x, x1], dim=1) x = self.relu(self.conv15(x)) x = self.conv16(x) x = self.gamma * x + self.beta x = self.sigmoid(x) return x # 定义数据集类 class MyDataset(Dataset): def __init__(self, img_path): self.img_path = img_path self.img_list = os.listdir(img_path) def __len__(self): return len(self.img_list) def __getitem__(self, idx): img_name = self.img_list[idx] img = cv2.imread(os.path.join(self.img_path, img_name)) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = img.astype(np.float32) / 255.0 img_hazy = img.copy() img_hazy[:, :, 0] = img_hazy[:, :, 0] * 0.3 + img_hazy[:, :, 1] * 0.59 + img_hazy[:, :, 2] * 0.11 img_hazy[:, :, 1] = img_hazy[:, :, 0] img_hazy[:, :, 2] = img_hazy[:, :, 0] img_hazy = img_hazy + np.random.randn(*img_hazy.shape) * 0.1 img_hazy = np.clip(img_hazy, 0, 1) return torch.from_numpy(img_hazy.transpose(2, 0, 1)), torch.from_numpy(img.transpose(2, 0, 1)) # 训练模型 def train(): device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') dataset = MyDataset('data') dataloader = DataLoader(dataset, batch_size=32, shuffle=True) model = GCANet().to(device) criterion = nn.MSELoss() optimizer = optim.Adam(model.parameters(), lr=1e-3) for epoch in range(50): running_loss = 0.0 for i, (img_hazy, img_gt) in enumerate(dataloader): img_hazy, img_gt = img_hazy.to(device), img_gt.to(device) optimizer.zero_grad() output = model(img_hazy) loss = criterion(output, img_gt) loss.backward() optimizer.step() running_loss += loss.item() if i % 10 == 9: print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 10)) running_loss = 0.0 torch.save(model.state_dict(), 'gcanet.pth') # 使用模型进行去雾 def test(): device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = GCANet().to(device) model.load_state_dict(torch.load('gcanet.pth')) img_hazy = cv2.imread('hazy.jpg') img_hazy = cv2.cvtColor(img_hazy, cv2.COLOR_BGR2RGB) img_hazy = img_hazy.astype(np.float32) / 255.0 img_hazy[:, :, 0] = img_hazy[:, :, 0] * 0.3 + img_hazy[:, :, 1] * 0.59 + img_hazy[:, :, 2] * 0.11 img_hazy[:, :, 1] = img_hazy[:, :, 0] img_hazy[:, :, 2] = img_hazy[:, :, 0] img_hazy = np.expand_dims(img_hazy.transpose(2, 0, 1), axis=0) img_hazy = torch.from_numpy(img_hazy).to(device) with torch.no_grad(): img_dehaze = model(img_hazy) img_dehaze = img_dehaze.cpu().numpy()[0].transpose(1, 2, 0) img_dehaze[:, :, 0] = img_dehaze[:, :, 0] * 1 + img_hazy[0, 0].cpu().numpy() img_dehaze[:, :, 1] = img_dehaze[:, :, 1] * 1 + img_hazy[0, 1].cpu().numpy() img_dehaze[:, :, 2] = img_dehaze[:, :, 2] * 1 + img_hazy[0, 2].cpu().numpy() img_dehaze = np.clip(img_dehaze, 0, 1) img_dehaze = cv2.cvtColor((img_dehaze * 255).astype(np.uint8), cv2.COLOR_RGB2BGR) cv2.imwrite('dehaze.jpg', img_dehaze) if __name__ == '__main__': train() test() ``` 需要注意的是,这里的训练数据集是在`data`文件夹中,文件夹中包含了一些有雾的图像和对应的无雾图像。训练代码会将这些数据集读入,并对模型进行训练。测试代码则是对一张有雾的图像进行去雾,去雾结果保存为`dehaze.jpg`。

相关推荐

最新推荐

recommend-type

python opencv 图像拼接的实现方法

高级图像拼接也叫作基于特征匹配的图像拼接,拼接时消去两幅图像相同的部分,实现拼接合成全景图。这篇文章主要介绍了python opencv 图像拼接,需要的朋友可以参考下
recommend-type

python实现图像外边界跟踪操作

主要介绍了python实现图像外边界跟踪操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

python实现LBP方法提取图像纹理特征实现分类的步骤

主要介绍了python实现LBP方法提取图像纹理特征实现分类的步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

python opencv 实现对图像边缘扩充

今天小编就为大家分享一篇python opencv 实现对图像边缘扩充,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

python用TensorFlow做图像识别的实现

使用方法很简单,只需要输入训练数据位置,设定参数和优化方法等,TensorFlow就可以将优化结果显示出来,节省了很大量的编程时间,TensorFlow的功能很多很强大,这边挑选了一个比较简单实现的方法,就是利用...
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

解释minorization-maximization (MM) algorithm,并给出matlab代码编写的例子

Minorization-maximization (MM) algorithm是一种常用的优化算法,用于求解非凸问题或含有约束的优化问题。该算法的基本思想是通过构造一个凸下界函数来逼近原问题,然后通过求解凸下界函数的最优解来逼近原问题的最优解。具体步骤如下: 1. 初始化参数 $\theta_0$,设 $k=0$; 2. 构造一个凸下界函数 $Q(\theta|\theta_k)$,使其满足 $Q(\theta_k|\theta_k)=f(\theta_k)$; 3. 求解 $Q(\theta|\theta_k)$ 的最优值 $\theta_{k+1}=\arg\min_\theta Q(
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。