opencv图像数据增强笔记


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

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

opencv实现各类图像增广笔记

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

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

定义函数类结构如下:

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)

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)

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

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)

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)

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()

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()

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)

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)

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))

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)

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)

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)

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)

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)


# ai  # red  # opencv  # 图片放大  # 饱和度  # 最优  # 请输入  # 边缘  # 转成  # 高斯  # 迭代  # 几个  # 出了  # 有很多 


相关栏目: 【 Google疑问12 】 【 Facebook疑问10 】 【 网络优化91478 】 【 技术知识72672 】 【 云计算0 】 【 GEO优化84317 】 【 优选文章0 】 【 营销推广36048 】 【 网络运营41350 】 【 案例网站102563 】 【 AI智能45237


相关推荐: AI简历生成工具有哪些_一键生成专业简历的AI工具推荐  QRCODE.AI深度评测:AI驱动的二维码生成器优缺点分析  AI代码助手的崛起:软件工程的未来展望与实用指南  5分钟教你用AI生成短视频分镜脚本,小白也能拍大片  如何用AI一键生成名片设计 AI个人电子名片制作指南【教程】  利用 Google AI 进行图像元数据分析与整理  利用AI快速生成数组和枚举:详细指南与实用技巧  AI面试助手:提升招聘效率的终极工具  Fiverr网站审计终极指南:免费工具、SEO技巧和实战案例  AI驱动法律文件分类:效率提升与战略决策的新纪元  即梦AI怎样生成产品描述_即梦AI产品描述生成与卖点提炼【实操】  Tamilnad Mercantile Bank TMB:如何在线下载账户报表  AISIA O1皮肤检测仪操作指南:安装、使用、疑难解答  AI Buildr: 构建 AI 应用的终极指南  斑马AI怎样注册账号_斑马AI注册流程与儿童信息绑定【教程】  AI视频创作终极指南:文本到视频的免费工具与技巧  如何利用豆包 AI 快速查询当地生活服务资讯  AI驱动合同管理:Microsoft Power Platform实战指南  教你用AI将一篇长文自动拆解成社交媒体帖子,实现一文多发  AI标语生成器:轻松打造品牌口号,提升品牌价值  秀米AI智能排版怎样生成节日专题模板_秀米AI智能排版节日模板调用【技巧】  AI测试面试准备:提升你的面试技巧与知识储备  解读Childish Gambino《This Is America》的深层含义与文化影响  即梦ai能否生成3D建模参考图_即梦ai3D参考图生成与视角设置【方法】  《高龄母亲》:从日本民间故事中汲取的人生智慧与家庭真谛  智行ai抢票怎么设置抢票截止时间_智行ai抢票截止时间设置与确认【步骤】  2025年最佳免费AI艺术生成器:POD终极指南  啦啦队女孩:青春活力与性感魅力的完美结合  揭秘颜值真相:社交实验的背后,你是几分?  普通人如何用DeepSeek月入过万?2026最新赚钱路径全解析!  lovemo官网网页版入口 lovemo官网登录入口  ChatGPT怎样用提示词分步骤提问_ChatGPT分步提问技巧【方法】  探索都市传说:追寻鳄鱼飞机怪物“Bombardino Crocodilo”  批改网AI检测工具怎样开启实时检测_批改网AI检测工具实时检测开启与延迟设置【指南】  百度浏览器侧边栏ai怎么关 百度浏览器ai侧边栏隐藏  如何用AI一键生成手机壁纸?4K高清AI壁纸生成关键词【分享】  教你用AI进行市场调研,快速生成消费者洞察报告  AdobeExpressAI智能排版怎么快速生成Logo_AdobeExpressAI智能排版Logo生成入口【步骤】  掌握写作技巧:小说情节设计的核心要素解析  定价3499炒到1.2万,豆包AI手机遭“封杀”,变革之路何去何从?  怎么用ai制作表情包 AI个性化动态表情包教程【方法】  AI赋能软件测试:自动化、智能化与未来趋势  恐怖游戏惊魂:虚拟主播带你逃离病娇女孩的魔爪  AMD Ryzen 5 2600: 游戏玩家高性价比之选  壹伴AI智能排版如何自动生成文章配图_壹伴AI智能排版配图生成与版权说明【教程】  五大AI视频编辑工具:提升视频创作效率和质量  AI时代生存指南:掌握软实力,成为不可替代的人  CallidusAI:提升合同起草效率的智能Word插件指南  Gemini怎样写描述型提示词_Gemini描述提示词编写【攻略】  AI UGC生成器深度测评:四大工具横向对比分析 

 2025-07-23

了解您产品搜索量及市场趋势,制定营销计划

同行竞争及网站分析保障您的广告效果

点击免费数据支持

提交您的需求,1小时内享受我们的专业解答。

南京市珐之弘网络技术有限公司


南京市珐之弘网络技术有限公司

南京市珐之弘网络技术有限公司专注海外推广十年,是谷歌推广.Facebook广告全球合作伙伴,我们精英化的技术团队为企业提供谷歌海外推广+外贸网站建设+网站维护运营+Google SEO优化+社交营销为您提供一站式海外营销服务。

 87067657

 13565296790

 87067657@qq.com

Notice

We and selected third parties use cookies or similar technologies for technical purposes and, with your consent, for other purposes as specified in the cookie policy.
You can consent to the use of such technologies by closing this notice, by interacting with any link or button outside of this notice or by continuing to browse otherwise.