• python使用openvc库进行图像数据增强


    以下是使用Python和OpenCV库实现图像数据增强的简单示例代码,其中包括常用的数据增强操作:

    import cv2
    import numpy as np
    import os
    
    # 水平翻转
    def horizontal_flip(image):
        return cv2.flip(image, 1)
    
    # 垂直翻转
    def vertical_flip(image):
        return cv2.flip(image, 0)
    
    # 随机旋转
    def random_rotation(image, angle_range=(-10, 10)):
        angle = np.random.randint(angle_range[0], angle_range[1])
        height, width = image.shape[:2]
        rotation_matrix = cv2.getRotationMatrix2D((width / 2, height / 2), angle, 1)
        rotated_image = cv2.warpAffine(image, rotation_matrix, (width, height))
        return rotated_image
    
    # 随机裁剪
    def random_crop(image, crop_size=(224, 224)):
        height, width = image.shape[:2]
        left = np.random.randint(0, width - crop_size[0])
        top = np.random.randint(0, height - crop_size[1])
        right = left + crop_size[0]
        bottom = top + crop_size[1]
        cropped_image = image[top:bottom, left:right]
        return cropped_image
    
    # 添加随机噪声
    def random_noise(image, noise_range=(20, 50)):
        noise = np.random.randint(noise_range[0], noise_range[1], size=image.shape, dtype=np.uint8)
        noisy_image = cv2.add(image, noise)
        return np.clip(noisy_image, 0, 255)
    
    # 设置原始图像路径和增强后图像保存路径
    original_path = "original_images"
    augmented_path = "augmented_images"
    
    # 确保存储路径存在
    os.makedirs(augmented_path, exist_ok=True)
    
    # 遍历原始图像路径下的所有图像
    for filename in os.listdir(original_path):
        if filename.endswith(".jpg") or filename.endswith(".png"):
            image_path = os.path.join(original_path, filename)
            image = cv2.imread(image_path)
    
            # 水平翻转
            h_flip = horizontal_flip(image)
            cv2.imwrite(os.path.join(augmented_path, f"flip_h_{filename}"), h_flip)
    
            # 垂直翻转
            v_flip = vertical_flip(image)
            cv2.imwrite(os.path.join(augmented_path, f"flip_v_{filename}"), v_flip)
    
            # 随机旋转
            rotated = random_rotation(image)
            cv2.imwrite(os.path.join(augmented_path, f"rotated_{filename}"), rotated)
    
            # 随机裁剪
            cropped = random_crop(image)
            cv2.imwrite(os.path.join(augmented_path, f"crop_{filename}"), cropped)
    
            # 添加随机噪声
            noisy = random_noise(image)
            cv2.imwrite(os.path.join(augmented_path, f"noisy_{filename}"), noisy)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68

    在这个示例代码中,我们使用OpenCV库来加载和处理图像。我们定义了几个常用的数据增强操作函数,包括水平翻转、垂直翻转、随机旋转、随机裁剪和添加随机噪声。然后,我们遍历原始图像路径下的所有图像,对每张图像进行数据增强操作,并保存到增强后图像保存路径。

    请注意,为了运行此代码,您需要安装OpenCV库。可以使用pip install opencv-python命令来安装。同时,确保将原始图像放在指定的原始图像路径下,并设置好增强后图像的保存路径。

    # -*- coding: utf-8 -*-
    
    import cv2
    import numpy as np
    import os.path
    import copy
    
    # 椒盐噪声
    
    
    def SaltAndPepper(src, percetage):
        SP_NoiseImg = src.copy()
        SP_NoiseNum = int(percetage*src.shape[0]*src.shape[1])
        for i in range(SP_NoiseNum):
            randR = np.random.randint(0, src.shape[0]-1)
            randG = np.random.randint(0, src.shape[1]-1)
            randB = np.random.randint(0, 3)
            if np.random.randint(0, 1) == 0:
                SP_NoiseImg[randR, randG, randB] = 0
            else:
                SP_NoiseImg[randR, randG, randB] = 255
        return SP_NoiseImg
    
    # 高斯噪声
    
    
    def addGaussianNoise(image, percetage):
        G_Noiseimg = image.copy()
        w = image.shape[1]
        h = image.shape[0]
        G_NoiseNum = int(percetage*image.shape[0]*image.shape[1])
        for i in range(G_NoiseNum):
            temp_x = np.random.randint(0, h)
            temp_y = np.random.randint(0, w)
            G_Noiseimg[temp_x][temp_y][np.random.randint(3)] = np.random.randn(1)[
                0]
        return G_Noiseimg
    
    # 昏暗
    
    
    def darker(image, percetage=0.9):
        image_copy = image.copy()
        w = image.shape[1]
        h = image.shape[0]
        # get darker
        for xi in range(0, w):
            for xj in range(0, h):
                image_copy[xj, xi, 0] = int(image[xj, xi, 0]*percetage)
                image_copy[xj, xi, 1] = int(image[xj, xi, 1]*percetage)
                image_copy[xj, xi, 2] = int(image[xj, xi, 2]*percetage)
        return image_copy
    
    # 亮度
    
    
    def brighter(image, percetage=1.5):
        image_copy = image.copy()
        w = image.shape[1]
        h = image.shape[0]
        # get brighter
        for xi in range(0, w):
            for xj in range(0, h):
                image_copy[xj, xi, 0] = np.clip(
                    int(image[xj, xi, 0]*percetage), a_max=255, a_min=0)
                image_copy[xj, xi, 1] = np.clip(
                    int(image[xj, xi, 1]*percetage), a_max=255, a_min=0)
                image_copy[xj, xi, 2] = np.clip(
                    int(image[xj, xi, 2]*percetage), a_max=255, a_min=0)
        return image_copy
    
    # 旋转
    
    
    def rotate(image, angle, center=None, scale=1.0):
        (h, w) = image.shape[:2]
        # If no rotation center is specified, the center of the image is set as the rotation center
        if center is None:
            center = (w / 2, h / 2)
        m = cv2.getRotationMatrix2D(center, angle, scale)
        rotated = cv2.warpAffine(image, m, (w, h))
        return rotated
    
    # 翻转
    
    
    def flip(image):
        flipped_image = np.fliplr(image)
        return flipped_image
    
    
    # 图片文件夹路径
    file_dir = r'test/img/'
    for img_name in os.listdir(file_dir):
        img_path = file_dir + img_name
        img = cv2.imread(img_path)
        # cv2.imshow("1",img)
        # cv2.waitKey(5000)
        # 旋转
        rotated_90 = rotate(img, 90)
        cv2.imwrite(file_dir + img_name[0:-4] + '_r90.jpg', rotated_90)
        rotated_180 = rotate(img, 180)
        cv2.imwrite(file_dir + img_name[0:-4] + '_r180.jpg', rotated_180)
    
    for img_name in os.listdir(file_dir):
        img_path = file_dir + img_name
        img = cv2.imread(img_path)
        # 镜像
        flipped_img = flip(img)
        cv2.imwrite(file_dir + img_name[0:-4] + '_fli.jpg', flipped_img)
    
        # 增加噪声
        # img_salt = SaltAndPepper(img, 0.3)
        # cv2.imwrite(file_dir + img_name[0:7] + '_salt.jpg', img_salt)
        img_gauss = addGaussianNoise(img, 0.3)
        cv2.imwrite(file_dir + img_name[0:-4] + '_noise.jpg', img_gauss)
    
        # 变亮、变暗
        img_darker = darker(img)
        cv2.imwrite(file_dir + img_name[0:-4] + '_darker.jpg', img_darker)
        img_brighter = brighter(img)
        cv2.imwrite(file_dir + img_name[0:-4] + '_brighter.jpg', img_brighter)
    
        blur = cv2.GaussianBlur(img, (7, 7), 1.5)
        #      cv2.GaussianBlur(图像,卷积核,标准差)
        cv2.imwrite(file_dir + img_name[0:-4] + '_blur.jpg', blur)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
  • 相关阅读:
    一个基于.Net Core开源个人博客网站
    决策树与随机森林
    springboot连接mysql数据库,密码正确却始终报密码错误问题
    OC和Swift的区别,发送消息和执行方法的区别
    在Android Studio中连接字符串之前添加@SuppressLint(“settexti18n”)注释
    动环监控设备维护与故障处理,动环监控系统调试
    Web3数据云OORT推出商用版智能代理构建平台:OORT TDS
    电商API数据采集,教你如何获取商品详情数据
    BI系统打包Docker镜像及容器化部署的具体实现
    C陷阱与缺陷 第3章 语义“陷阱” 3.6 边界计算与不对称边界
  • 原文地址:https://blog.csdn.net/weixin_45277161/article/details/132846106