0

0

opencv图像数据增强笔记

P粉084495128

P粉084495128

发布时间:2025-07-23 11:02:15

|

561人浏览过

|

来源于php中文网

原创

本文是使用OpenCV实现各类图像增广的笔记,介绍了图片放缩、二值化与阈值处理(含大津法)、翻转(含随机翻转)、去噪声、腐蚀膨胀、旋转、亮度调节、随机裁剪等14种图像增广方法,每种方法均给出了相应的实现代码及效果展示。

☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R1 模型☜☜☜

opencv图像数据增强笔记 - php中文网

opencv实现各类图像增广笔记

图像增广方法有很多,此项目做了如下几个例子的展示(后续再有所其它应用会更新,如果各位有其它需求欢迎评论区催更)

  • 图片放缩
  • 图片二值化,阈值处理(大津法求最优阀值)
  • 图片翻转
  • 图片去噪声
  • 图片的腐蚀膨胀
  • 图片旋转
  • 图片亮度调节
  • 图片随机裁剪
  • 图片随机添加蒙版
  • 图片边缘填充
  • 修改图片饱和度
  • 图片放大、平移
  • x轴的剪切变换,角度15°

定义函数类结构如下:

歌者PPT
歌者PPT

歌者PPT,AI 写 PPT 永久免费

下载
class FunctionClass:
    def __init__(self, parameter):        self.parameter=parameter    def __call__(self, img):

1 图片展示

In [ ]
# 导入相关包import cv2import numpy as npfrom matplotlib import pyplot as plt
%matplotlib inline
In [ ]
filename = 'lena.jpg'img = cv2.imread(filename)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)print(img.shape) # 输出通道数,大小是350*350 3通道plt.imshow(img)
(350, 350, 3)
<matplotlib.image.AxesImage at 0x7f0cdc371310>
<Figure size 432x288 with 1 Axes>

2 图片放缩

In [ ]
class Resize:
    def __init__(self, size):
        self.size=size    def __call__(self, img):
        return cv2.resize(img, self.size)# Resize( (600, 600))通过修改函数中参数进行调节图片的大小resize=Resize( (600, 600))
img_resize=resize(img)
plt.imshow(img_resize)
<matplotlib.image.AxesImage at 0x7f6a7c06ed90>
<Figure size 432x288 with 1 Axes>

3 图片二值化,阈值处理(大津法求最优阀值)

In [ ]
#载入原图img_original=cv2.imread('lena.jpg',0)#迭代阈值分割print("请输入阈值0-255")
thresh = int(input())
retval,img_global=cv2.threshold(img_original,thresh,255,cv2.THRESH_BINARY)print(retval) 

#最优阈值ret2,th2 = cv2.threshold(img_original,0,255,cv2.THRESH_OTSU)print(ret2)#显示图片plt.subplot(1,3,1)
plt.imshow(img_original,'gray')
plt.title('Original Image')
plt.subplot(1,3,2)
plt.hist(img_original.ravel(),256)#.ravel方法将矩阵转化为一维plt.subplot(1,3,3)
plt.imshow(th2,'gray')
plt.title('Otsu thresholding')
plt.show()
请输入阈值0-255
111.0
116.0
<Figure size 432x288 with 3 Axes>

4 图片翻转

4.1 水平、垂直翻转

In [ ]
class Flip:
    def __init__(self, mode):
        self.mode=mode    def __call__(self, img):
        return cv2.flip(img, self.mode)# 指定翻转类型(非随机)# mode=0垂直翻转、1水平翻转、-1水平加垂直翻转flip=Flip(mode=0)
img_flip=flip(img)
plt.imshow(img_flip)
<matplotlib.image.AxesImage at 0x7f6a5c32e650>
<Figure size 432x288 with 1 Axes>

4.2 随机水平、垂直翻转

In [ ]
import random# 随机翻转class RandomFlip((object)):  
    def __init__(self, mode=1):
        # 设置一个翻转参数,1、0或-1,默认1
        assert mode in [-1, 0, 1], "mode should be a value in [-1, 0, 1]"
        self.mode = mode    def __call__(self, img):
        # 随机生成0或1(即是否翻转)
        if random.randint(0, 1) == 1:            return cv2.flip(img, self.mode)        else:            return img
In [ ]
randomflip=RandomFlip(0)
img_randomflip=randomflip(img)
plt.imshow(img_randomflip)
<matplotlib.image.AxesImage at 0x7f6a14269990>
<Figure size 432x288 with 1 Axes>

5 图片去噪声

In [ ]
def gasuss_noise(image, mean=0, var=0.001): # 模拟高斯噪声
    ''' 
        添加高斯噪声
        mean : 均值 
        var : 方差
    '''
    image = np.array(image/255, dtype=float)
    noise = np.random.normal(mean, var ** 0.5, image.shape)
    out = image + noise    if out.min() < 0:
        low_clip = -1.
    else:
        low_clip = 0.
    out = np.clip(out, low_clip, 1.0)
    out = np.uint8(out*255)    return out
In [ ]
img_noise = gasuss_noise(img) # 添加噪声dst = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21) # 去噪函数plt.subplot(121),plt.imshow(img_noise) # 含噪声(绿点)图plt.subplot(122),plt.imshow(dst) # 去噪后的图plt.show()
<Figure size 432x288 with 2 Axes>

6 图片的腐蚀膨胀

In [ ]
kernel = np.ones((3, 3), dtype=np.uint8) # 定义3x3卷积核dilate = cv2.dilate(img, kernel, 1) # 1:迭代次数,也就是执行几次膨胀操作erosion = cv2.erode(img, kernel, 1) 

plt.subplot(131),plt.imshow(img)
plt.subplot(132),plt.imshow(dilate) # 膨胀plt.subplot(133),plt.imshow(erosion) # 腐蚀plt.show()
<Figure size 432x288 with 3 Axes>

7 图片旋转

In [ ]
class Rotate:
    def __init__(self, degree,size):
        self.degree=degree
        self.size=size    def __call__(self, img):
        h, w = img.shape[:2]
        center = (w // 2, h // 2) # 采取中心点为轴进行旋转
        M = cv2.getRotationMatrix2D(center,self.degree, self.size)        return cv2.warpAffine(img, M, (w, h))# 参数1是旋转角度,参数2是图像比例rotate=Rotate(45, 0.7)
img_rotating=rotate(img)
plt.imshow(img_rotating)
<matplotlib.image.AxesImage at 0x7f0cdc358990>
<Figure size 432x288 with 1 Axes>

8 图片亮度调节

In [ ]
class Brightness:
    def __init__(self,brightness_factor):
        self.brightness_factor=brightness_factor    def __call__(self, img):
        img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # 通过cv2.cvtColor把图像从BGR转换到HSV
        darker_hsv = img_hsv.copy()
        darker_hsv[:, :, 2] =  self.brightness_factor * darker_hsv[:, :, 2]        return cv2.cvtColor(darker_hsv, cv2.COLOR_HSV2BGR)   
         
brightness=Brightness(0.6)
img2=brightness(img)
plt.imshow(img2)
<matplotlib.image.AxesImage at 0x7f0cdc2c2610>
<Figure size 432x288 with 1 Axes>

9 图片随机裁剪

In [ ]
import randomimport mathclass RandCropImage(object):
    """ random crop image """
    """ 随机裁剪图片 """

    def __init__(self, size, scale=None, ratio=None, interpolation=-1):

        self.interpolation = interpolation if interpolation >= 0 else None
        if type(size) is int:
            self.size = (size, size)  # (h, w)
        else:
            self.size = size

        self.scale = [0.08, 1.0] if scale is None else scale
        self.ratio = [3. / 4., 4. / 3.] if ratio is None else ratio    def __call__(self, img):
        size = self.size
        scale = self.scale
        ratio = self.ratio

        aspect_ratio = math.sqrt(random.uniform(*ratio))
        w = 1. * aspect_ratio
        h = 1. / aspect_ratio

        img_h, img_w = img.shape[:2]

        bound = min((float(img_w) / img_h) / (w**2),
                    (float(img_h) / img_w) / (h**2))
        scale_max = min(scale[1], bound)
        scale_min = min(scale[0], bound)

        target_area = img_w * img_h * random.uniform(scale_min, scale_max)
        target_size = math.sqrt(target_area)
        w = int(target_size * w)
        h = int(target_size * h)

        i = random.randint(0, img_w - w)
        j = random.randint(0, img_h - h)

        img = img[j:j + h, i:i + w, :]        if self.interpolation is None:            return cv2.resize(img, size)        else:            return cv2.resize(img, size, interpolation=self.interpolation)
In [ ]
crop = RandCropImage(350)
plt.imshow(crop(img))
<matplotlib.image.AxesImage at 0x7f559c786150>
<Figure size 432x288 with 1 Axes>

10 图片随机添加蒙版

In [ ]
# 随机裁剪图片class RandomErasing(object):
    def __init__(self, EPSILON=0.5, sl=0.02, sh=0.4, r1=0.3,
                 mean=[0., 0., 0.]):
        self.EPSILON = EPSILON
        self.mean = mean
        self.sl = sl
        self.sh = sh
        self.r1 = r1    def __call__(self, img):
        if random.uniform(0, 1) > self.EPSILON:            return img        for attempt in range(100):
            area = img.shape[0] * img.shape[1]

            target_area = random.uniform(self.sl, self.sh) * area
            aspect_ratio = random.uniform(self.r1, 1 / self.r1)

            h = int(round(math.sqrt(target_area * aspect_ratio)))
            w = int(round(math.sqrt(target_area / aspect_ratio)))            #print(w)

            
            # 此处插入代码
            if w < img.shape[0] and h < img.shape[1]:
                x1 = random.randint(0, img.shape[1] - h)
                y1 = random.randint(0, img.shape[0] - w)                if img.shape[2] == 3:
                    img[ x1:x1 + h, y1:y1 + w, 0] = self.mean[0]
                    img[ x1:x1 + h, y1:y1 + w, 1] = self.mean[1]
                    img[ x1:x1 + h, y1:y1 + w, 2] = self.mean[2]                else:
                    img[x1:x1 + h, y1:y1 + w,0] = self.mean[0]                return img 
        return img

erase = RandomErasing()
img2=erase(img)
plt.imshow(img2)
<matplotlib.image.AxesImage at 0x7f559c777ed0>
<Figure size 432x288 with 1 Axes>

11 图片边缘填充

In [ ]
# 图片边缘填充class Pooling:
    def __init__(self,pooling1,pooling2,pooling3,pooling4):
        self.pooling1=pooling1
        self.pooling2=pooling2
        self.pooling3=pooling3
        self.pooling4=pooling4    def __call__(self, img):

        # 全0填充,若填充其它颜色,需修改下面value中数值即可
        img_pool = cv2.copyMakeBorder(img, self.pooling1, self.pooling2, self.pooling3, self.pooling4, 
                                       cv2.BORDER_CONSTANT, 
                                       value=(0, 0, 0))        return img_pool        
# Pooling()中的4个参数分别是,上下左右填充的像素大小pooling=Pooling(10,20,30,40)
img2=pooling(img)
plt.imshow(img2)
<matplotlib.image.AxesImage at 0x7f0cdc290310>
<Figure size 432x288 with 1 Axes>

12 修改图片饱和度

In [ ]
# 修改图片饱和度class Saturation:
    def __init__(self,saturation_factor):
        self.saturation_factor=saturation_factor    def __call__(self, img):

        img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # 通过cv2.cvtColor把图像从BGR转换到HSV
        colorless_hsv = img_hsv.copy()
        colorless_hsv[:, :, 1] = self.saturation_factor * colorless_hsv[:, :, 1]        return cv2.cvtColor(colorless_hsv, cv2.COLOR_HSV2BGR)

        
saturation=Saturation(0.6)
img2=saturation(img)
plt.imshow(img2)
<matplotlib.image.AxesImage at 0x7f0cdc170ed0>
<Figure size 432x288 with 1 Axes>

13 图片放大、平移

In [ ]
# 放大+平移class AmplificationTranslation:
    def __init__(self,mode1,mode2,mode3):
        self.mode1=mode1
        self.mode2=mode2
        self.mode3=mode3    def __call__(self, img):

        M_crop = np.array([
        [self.mode1, 0, self.mode2],
        [0, self.mode1, self.mode3]
        ], dtype=np.float32)

        img = cv2.warpAffine(img, M_crop, (img.shape[0], img.shape[1]))        return img# 将彩色图的BGR通道顺序转成RGBimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)      
# AmplificationTranslation()中,参数分别是:放大倍数、平移坐标(-150,-240)ATion=AmplificationTranslation(1.6,-150,-240)
img2=ATion(img)
plt.imshow(img2)
<matplotlib.image.AxesImage at 0x7f0cdc0caf10>
<Figure size 432x288 with 1 Axes>

14 x轴的剪切变换,角度15°

In [ ]
class ShearAngle:
    def __init__(self,mode):
        self.mode=mode    def __call__(self, img):

        # x轴的剪切变换,角度15°
        theta = self.mode * np.pi / 180
        M_shear = np.array([
        [1, np.tan(theta), 0],
        [0, 1, 0]
        ], dtype=np.float32)

        img_sheared = cv2.warpAffine(img, M_shear, (img.shape[0], img.shape[1]))        return img_sheared# 将彩色图的BGR通道顺序转成RGBimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)   
     
# ShearAngle()中,参数是:角度SAion=ShearAngle(15)
img2=SAion(img)
plt.imshow(img2)
<matplotlib.image.AxesImage at 0x7f559c426250>
<Figure size 432x288 with 1 Axes>

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

26

2026.03.13

Python异步编程与Asyncio高并发应用实践
Python异步编程与Asyncio高并发应用实践

本专题围绕 Python 异步编程模型展开,深入讲解 Asyncio 框架的核心原理与应用实践。内容包括事件循环机制、协程任务调度、异步 IO 处理以及并发任务管理策略。通过构建高并发网络请求与异步数据处理案例,帮助开发者掌握 Python 在高并发场景中的高效开发方法,并提升系统资源利用率与整体运行性能。

46

2026.03.12

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

178

2026.03.11

Go高并发任务调度与Goroutine池化实践
Go高并发任务调度与Goroutine池化实践

本专题围绕 Go 语言在高并发任务处理场景中的实践展开,系统讲解 Goroutine 调度模型、Channel 通信机制以及并发控制策略。内容包括任务队列设计、Goroutine 池化管理、资源限制控制以及并发任务的性能优化方法。通过实际案例演示,帮助开发者构建稳定高效的 Go 并发任务处理系统,提高系统在高负载环境下的处理能力与稳定性。

51

2026.03.10

Kotlin Android模块化架构与组件化开发实践
Kotlin Android模块化架构与组件化开发实践

本专题围绕 Kotlin 在 Android 应用开发中的架构实践展开,重点讲解模块化设计与组件化开发的实现思路。内容包括项目模块拆分策略、公共组件封装、依赖管理优化、路由通信机制以及大型项目的工程化管理方法。通过真实项目案例分析,帮助开发者构建结构清晰、易扩展且维护成本低的 Android 应用架构体系,提升团队协作效率与项目迭代速度。

92

2026.03.09

JavaScript浏览器渲染机制与前端性能优化实践
JavaScript浏览器渲染机制与前端性能优化实践

本专题围绕 JavaScript 在浏览器中的执行与渲染机制展开,系统讲解 DOM 构建、CSSOM 解析、重排与重绘原理,以及关键渲染路径优化方法。内容涵盖事件循环机制、异步任务调度、资源加载优化、代码拆分与懒加载等性能优化策略。通过真实前端项目案例,帮助开发者理解浏览器底层工作原理,并掌握提升网页加载速度与交互体验的实用技巧。

102

2026.03.06

Rust内存安全机制与所有权模型深度实践
Rust内存安全机制与所有权模型深度实践

本专题围绕 Rust 语言核心特性展开,深入讲解所有权机制、借用规则、生命周期管理以及智能指针等关键概念。通过系统级开发案例,分析内存安全保障原理与零成本抽象优势,并结合并发场景讲解 Send 与 Sync 特性实现机制。帮助开发者真正理解 Rust 的设计哲学,掌握在高性能与安全性并重场景中的工程实践能力。

227

2026.03.05

PHP高性能API设计与Laravel服务架构实践
PHP高性能API设计与Laravel服务架构实践

本专题围绕 PHP 在现代 Web 后端开发中的高性能实践展开,重点讲解基于 Laravel 框架构建可扩展 API 服务的核心方法。内容涵盖路由与中间件机制、服务容器与依赖注入、接口版本管理、缓存策略设计以及队列异步处理方案。同时结合高并发场景,深入分析性能瓶颈定位与优化思路,帮助开发者构建稳定、高效、易维护的 PHP 后端服务体系。

532

2026.03.04

AI安装教程大全
AI安装教程大全

2026最全AI工具安装教程专题:包含各版本AI绘图、AI视频、智能办公软件的本地化部署手册。全篇零基础友好,附带最新模型下载地址、一键安装脚本及常见报错修复方案。每日更新,收藏这一篇就够了,让AI安装不再报错!

171

2026.03.04

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
10分钟--Midjourney创作自己的漫画
10分钟--Midjourney创作自己的漫画

共1课时 | 0.1万人学习

Midjourney 关键词系列整合
Midjourney 关键词系列整合

共13课时 | 0.9万人学习

AI绘画教程
AI绘画教程

共2课时 | 0.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号