简介

BestYOLO:https://github.com/WangRongsheng/BestYOLO

BestYOLO是一个以科研和竞赛为导向的最好的YOLO实践框架!

目前BestYOLO是一个完全基于YOLOv5 v7.0 进行改进的开源库,该库将始终秉持以落地应用为导向,以轻便化使用为宗旨,简化各种模块的改进。目前已经集成了基于torchvision.models 模型为BackboneYOLOv5目标检测算法,同时也将逐渐开源更多YOLOv5应用程序。

合成雾增强算法

合成雾数据增强算法是一种基于图像处理技术的算法,用于增加由雾霾天气产生的雾气效果,从而提高图像的质量和可用性。该算法通过模拟雾气的形成原理,对图像进行处理和合成,使其看起来更加真实和自然。

合成雾数据增强算法的具体实现步骤如下:

  1. 提取图像的深度信息和细节信息,包括场景的几何结构、纹理和颜色等。

  2. 通过计算雾气的传播模型,确定雾气的密度和浓度,从而模拟出雾气效果。

  3. 根据模拟的雾气效果,对图像进行混合处理,包括颜色平衡、对比度调整以及明暗度等参数的调整。

  4. 针对特定场景的需求,可以对雾气的效果进行调整和优化,比如增强景深、调整雾气的颜色和透明度等。

通过合成雾数据增强算法,可实现对图像的自然场景雾化处理,从而提高图像的可视化效果和实用性。该算法在计算机视觉、图像处理、人工智能等领域都有着广泛的应用和研究价值。

实现效果

为YOLOv5\YOLOv8引入合成雾数据增强算法

synthetic_fog.py

"""
直接运行程序可以测试合成雾气效果
Produced by: zhangzhengde@sjtu.edu.cn
"""
import os
import math
import cv2
import time
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import shutilclass SyntheticFog(object):def __init__(self):passdef __call__(self, show=False):img_path = '../example/fog_image/raw.jpg'# img_path = '../sources/IMG_6685.JPG'assert os.path.exists(img_path), f'error: img does not exists, {img_path}'img = cv2.imread(img_path)print(img.shape)img = img/255.0print(f'fogging...')t0 = time.time()br = 0.7th = 0.05fogged_img = self.fogging_img(img, brightness=br, thickness=th,high_efficiency=True)print(f'fogging time: {(time.time()-t0)*1000:.4f}ms')rf = 1  # resize factorimg = cv2.resize(img, (int(img.shape[1]*rf), int(img.shape[0]*rf)))fogged_img = cv2.resize(fogged_img, ((int(fogged_img.shape[1]*rf)), (int(fogged_img.shape[0]*rf))))fogged_img = np.array(fogged_img*255, dtype=np.uint8)if show:cv2.imshow('src', img)cv2.imshow('fogged', fogged_img)cv2.waitKey(0)cv2.imwrite(f'../example/fog_image/fogged_br{br}_th{th}.jpg', fogged_img)def fogging_dir(self, sp, tp=None, random_params=True, brightness=None, thickness=None, save_src_img=False):"""fogging images in a directory:param sp: str, source dir path:param tp: str, target dir path, tp is fogged_{sp} by default:param random_params: bool, use random brightness and fog thickness params if True:param brightness: float, 0.1 to 0.9, gray of synthetic fog, pure white fog if 1, dark fog if 0.:param thickness: float, 0.01 to 0.09, thickness of synthetic fog, the larger the value, the thicker the fog.:param save_src_img: save source image at the same time i.e. copy source imgs to tp:return: None, all fogged images will be saved to target dir path."""tp = tp if tp is not None else f'{Path(sp).parent}/fogged_{Path(sp).name}'if os.path.exists(tp):ipt = input(f'Target dir: {tp} exists, do you want to remove it and continue. [Yes]/No: ')if ipt in ['', 'Yes', 'Y', 'yes']:shutil.rmtree(tp)else:print('do nothing')exit()os.makedirs(f'{tp}')imgs = [x for x in os.listdir(sp) if str(Path(x).suffix).lower() in ['.jpg', '.bmp']]print(f'Fogging {len(imgs)} images in dir {sp}, \nfogged images will be save to {tp}.')bar = tqdm(imgs)for i, img_name in enumerate(bar):img_path = f'{sp}/{img_name}'# stem = Path(img_path).stem# suffix = Path(img_path).suffixif save_src_img:  # save source imgshutil.copy(f'{sp}/{img_name}', f'{tp}/{img_name}')img = cv2.imread(img_path)h, w, c = img.shapenormed_img = img.copy()/255.0if random_params:br = np.clip(0.2 * np.random.randn() + 0.5, 0.1, 0.9)  # 0.1~0.9th = np.clip(0.01 * np.random.randn() + 0.05, 0.01, 0.09)else:br = brightnessth = thicknessassert br is not Noneassert th is not Nonefogged_img = self.fogging_img(normed_img, br, th, high_efficiency=True)fogged_img = np.array(fogged_img * 255, dtype=np.uint8)cv2.imwrite(f'{tp}/fogged_{img_name}', fogged_img)bar.set_description(f'Fogged image saved, fogged_{img_name}')def fogging_img(self, img, brightness=0.7, thickness=0.05, high_efficiency=True):"""fogging single image:param img: src img:param brightness: brightness:param thickness: fog thickness, without fog when 0, max 0.1,:param high_efficiency: use matrix to improve fogging speed when high_efficiency is True, else use loopslow efficiency: about 4000ms, high efficiency: about 80ms, tested in (864, 1152, 3) img:return: fogged image"""assert 0 <= brightness <= 1assert 0 <= thickness <= 0.1fogged_img = img.copy()h, w, c = fogged_img.shapeif not high_efficiency:  # use default loop to fogging, low efficiencysize = np.sqrt(np.max(fogged_img.shape[:2]))  # 雾化尺寸center = (h // 2, w // 2)  # 雾化中心# print(f'shape: {img.shape} center: {center} size: {size}')  # 33# d_list = []for j in range(h):for l in range(w):d = -0.04 * math.sqrt((j - center[0]) ** 2 + (l - center[1]) ** 2) + size# print(f'd {d}')td = math.exp(-thickness * d)# d_list.append(td)fogged_img[j][l][:] = fogged_img[j][l][:] * td + brightness * (1 - td)# x = np.arange(len(d_list))# plt.plot(x, d_list, 'o')# if j == 5:#     breakelse:  # use matrix  # TODO: 直接使用像素坐标,距离参数不适用于大分辨率图像,会变成鱼眼镜头的样子. done.use_pixel = Truesize = np.sqrt(np.max(fogged_img.shape[:2])) if use_pixel else 1  # 雾化尺寸h, w, c = fogged_img.shapehc, wc = h // 2, w // 2mask = self.get_mask(h=h, w=w, hc=hc, wc=wc, pixel=use_pixel)  # (h, w, 2)d = -0.04 * np.linalg.norm(mask, axis=2) + sizetd = np.exp(-thickness * d)for cc in range(c):fogged_img[..., cc] = fogged_img[..., cc] * td + brightness*(1-td)# a = np.linalg.norm(mask, axis=2)# print(f'size: {fogged_img.shape} a: {a} max: {np.max(fogged_img)} {np.min(fogged_img)}')fogged_img = np.clip(fogged_img, 0, 1)  # 解决黑白噪点的问题# print(f'mask: {mask[:, :, 1]} {mask.shape}')# print(f'd: {d} {d.shape}')return fogged_imgdef get_mask(self, h, w, hc, wc, pixel=True):mask = np.zeros((h, w, 2), dtype=np.float32)if pixel:mask[:, :, 0] = np.repeat(np.arange(h).reshape((h, 1)), w, axis=1) - hcmask[:, :, 1] = np.repeat(np.arange(w).reshape((1, w)), h, axis=0) - wcelse:mask[:, :, 0] = np.repeat(np.linspace(0, 1, h).reshape(h, 1), w, axis=1) - 0.5mask[:, :, 1] = np.repeat(np.linspace(0, 1, w).reshape((1, w)), h, axis=0) - 0.5return maskif __name__ == '__main__':synf = SyntheticFog()synf(show=True)

fog_augment.py

"""
fogging train and test datasets using synthetic fog algorithm
"""import os, sys
import shutil
from pathlib import Path
import numpy as np
from tqdm import tqdm
import cv2
import random
from copy import deepcopyfrom synthetic_fog import SyntheticFogclass AugmentCrosswalkDataset(object):def __init__(self, source_path):self.sp = source_path  # source pathp = Path(self.sp)self.tp = f'{p.parent}/fogged_{p.stem}'  # target pathself.sf = SyntheticFog()  # synthetic fog objectdef augment(self, show=False):"""augment train and test set in YOLOv5 format"""# 逐张进行增强sp = self.sptp = self.tpprint(f'fogged data will be saved to: {tp}')if os.path.exists(self.tp):shutil.rmtree(self.tp)os.makedirs(f'{self.tp}/train/images')os.makedirs(f'{self.tp}/test/images')os.makedirs(f'{self.tp}/train/labels')os.makedirs(f'{self.tp}/test/labels')for trte in ['train', 'test']:pi = f'{sp}/{trte}/images'  # path of imagespl = f'{sp}/{trte}/labels'ti = f'{tp}/{trte}/images'tl = f'{tp}/{trte}/labels'imgs = [f'{x}' for x in os.listdir(pi) if x.endswith('.jpg')]#print(f'transform {trte} images, total: {len(imgs)}, transformed total: {2*len(img)}.')bar = tqdm(imgs)for i, img_name in enumerate(bar):img_path = f'{pi}/{img_name}'stem = Path(img_path).stemassert os.path.exists(img_path), f'img does not exists {img_path}'# 先拷贝原始图像和标注shutil.copy(img_path, f'{ti}/{img_name}')shutil.copy(f'{pl}/{stem}.txt', f'{tl}/{stem}.txt')# foggingimg = cv2.imread(img_path)h, w, c = img.shape# random brightness and thicknessbr = np.clip(0.2 * np.random.randn() + 0.5, 0.1, 0.9)  # 0.1~0.9th = np.clip(0.01 * np.random.randn() + 0.05, 0.01, 0.09)normed_img = img.copy()/255.0fogged_img = self.sf.fogging_img(normed_img, brightness=br, thickness=th, high_efficiency=True)fogged_img = np.array(fogged_img*255, dtype=np.uint8)# save fogged images and labelscv2.imwrite(f'{ti}/fogged_{img_name}', fogged_img)shutil.copy(f'{pl}/{stem}.txt', f'{tl}/fogged_{stem}.txt')if show:print(f'img_name: {Path(img_path).name} img: {img.shape} br: {br} th: {th} max: {np.max(fogged_img)}')self.show(img, name='src_img', wait=False)self.show(fogged_img, name='fogged_img', wait=False)if cv2.waitKey(0) == ord('q'):breakbar.set_description(f'Img and fogged img saved, {stem}.')def show(self, img, name='xx', wait=True):h, w, c = img.shapescale = 0.5show_img = cv2.resize(img, (int(w*scale), int(h*scale)))cv2.imshow(name, show_img)if wait:cv2.waitKey(0)def augment_testset(self, dir):"""augment only test set"""self.sf.fogging_dir(sp=dir, tp=None, random_params=True, save_src_img=True)if __name__ == '__main__':source_path = './data'acd = AugmentCrosswalkDataset(source_path)acd.augment(show=False)# test_imgs_path = '/home/zzd/datasets/crosswalk/testsets_1770/Images'# acd.augment_testset(test_imgs_path)

所有离线增强的数据都可以用于YOLOv5或者YOLOv8模型的训练,可以有效提升YOLO算法的模型泛化性能。

为YOLOv5、YOLOv8带来全新的数据增强方式-合成雾增强算法相关推荐

  1. TensorFlow全新的数据读取方式:Dataset API入门教程

    Dataset API是TensorFlow 1.3版本中引入的一个新的模块,主要服务于数据读取,构建输入数据的pipeline. 此前,在TensorFlow中读取数据一般有两种方法: 1.使用pl ...

  2. AOP常用的几种增强方式,各自的特点

    SpringAOP的5种增强类型应用讲解 一.前言 spring框架中为我们提供的增强包括针对切面的增强和针对切入点的增强,对一个方法的增强底层使用的是动态代理,所以在学习springAop增强之前大 ...

  3. 全新数据增强方式KeepAugment,简单高效提升模型精度!

    点击上方"3D视觉工坊",选择"星标" 干货第一时间送达 作者丨Edison_G 来源丨计算机视觉研究院 导读 数据增强(DA)是深度学习训练过程中,必不可少的 ...

  4. 让AI精准识别盗版,脸书开源数据增强库:支持图文音视频,提供100多种增强方式...

    月石一 发自 凹非寺 量子位 报道 | 公众号 QbitAI 只要稍微动点手脚,就会给AI模型的鲁棒性带来挑战. 在AI眼里,下面这两张图片可能毫无关联. 现在,Facebook AI开源了用于数据增 ...

  5. 微信8.0全心全意考虑用户需求为企业开展网络营销带来全新思考

    当前微信已然拥有12亿用户,远超其他同类型软件,而微信也并非一成不变,在2021年初正式推出了8.0版本,从新版本中可以更多地发现当下微信再一次将用户需求作为重点,有针对性的对不同需求群体做出了改变, ...

  6. httppost数据上传 unity_Unity中国增强版发布

    本文转自Unity Connect官方文章 我们在Unite Shanghai 2019大会结束以后,发布两项针对中国地区的本地化服务:Unity Hub 2.0中文版以及Unity中文版文档(网页版 ...

  7. 定义下一代存储,打造全新一代数据基础设施

    简介: 智能时代,阿里云正重新定义下一代存储,打造全新一代数据基础设施.在未来,数据势必呈爆发式地增长,那么对于存储的性能,必然会提出更高.更严苛的要求.此次直播阿里云将为大家带来7款存储产品新功能的 ...

  8. 总结 62 种在深度学习中的数据增强方式

    数据增强 数据增强通常是依赖从现有数据生成新的数据样本来人为地增加数据量的过程 这包括对数据进行不同方向的扰动处理 或使用深度学习模型在原始数据的潜在空间(latent space)中生成新数据点从而 ...

  9. 数据增强方式mosaic(基于yolo4)代码实现python

    近几天在研究数据增强的方式,看到了mosaic,并且需要用到它,查阅了一些代码,根据个人数据,修改了代码,现有三套代码实现了mosaic,但也有些许问题. mosaic数据增强方式是一次性从数据集中随 ...

最新文章

  1. 填谷式无源pfc电路_有源PFC电路上各个元件的作用-安泰维修
  2. linux自动启动network服务,Windows/Linux 创建开机启动服务
  3. 武汉计算机应用中职学校,武汉市中职学校计算机应用基础课程抽考.Doc
  4. java https soap,Java Https Soap Server(Tomcat-Axis2)
  5. NYOJ-491 幸运三角形
  6. python-redis连接管理
  7. 天津商业大学C语言题库,天津商业大学c语言机考改错及解答(含答案)解析.doc
  8. 已知两点坐标求水平距离_知道两个点的坐标X,Y,如何计算出两点间的距离以及角度,公式是什么...
  9. 敏捷团队章程的实践精要
  10. xtrabackup全量备份与全量恢复
  11. css flex布局iOS8兼容性问题
  12. 怎樣制作线段动画_教程:如何制作一个绘制线条动画
  13. 5-3 jmu-java-m05-使用Comparator接口排序 (10分)
  14. 幽默笑话,隔壁的长舌妇,木子家原创
  15. 海贼王83名刀:无上大快刀12工、大快刀21工、良快刀50工
  16. Java架构师成长之道之Java架构师技术栈
  17. 本机配置nginx后css样式失效
  18. 如何摆脱极域2016(及以下版本)的控制
  19. linux如何用vi查找字符串替换,在Vi里面实现字符串的批量替换
  20. 华为服务器网口显示down,[已解决]华为三层交换机新建vlan后端口总是down的状态[已解决]~有好心人帮忙看看吗?谢谢~ - 华为技术论坛 - 51CTO技术论坛_中国领先的IT技术社区...

热门文章

  1. PMI-ACP练习题(1)
  2. 销售系统如何主动获客?揭秘个性化推荐背后的技术支持
  3. Web网页自动化实战《4.获取所有酒店的名字、价格、评分信息,并写入文件》上篇...
  4. InfoPath Analyzer
  5. OutputCache缓存技术
  6. mysql查看缓冲池_关于MySQL数据库监控指标总结:缓冲池使用情况
  7. Win32汇编--如何使用资源 [菜单和加速键]
  8. MySql之in查询优化
  9. JavaScript开发工具WebStorm使用教程:WebStorm项目
  10. awk从放弃到入门(9):awk数组详解