opencv—图像增强处理1

数据增强的方法很多,有加噪声、旋转、改变饱和度、亮度、对比度、锐度等;可以单一改变一个参数,也可以进行混合调节。
以下一一介绍几种方法:

代码1:改变hsv

def randomHueSaturationValue(image, hue_shift_limit=(-2,8),sat_shift_limit=(-5,50),val_shift_limit=(0,1.5)):
    img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    h, s ,v = img[:,:,0],img[:,:,1],img[:,:,2]
    hue_shift = np.random.uniform(hue_shift_limit[0], hue_shift_limit[1])

     # h= v + val_sh = h + hue_shift

    sat_shift = np.random.uniform(sat_shift_limit[0], sat_shift_limit[1])
    s = s + sat_shift

    val_shift = np.random.uniform(val_shift_limit[0], val_shift_limit[1])
    vhift
    
    img[:,:,0],img[:,:,1],img[:,:,2] = h, s ,v
    image = cv2.cvtColor(img, cv2.COLOR_HSV2BGR)

    # cv2.imshow("a1.jpg",image)
    cv2.imwrite("img2/a"+str(i)+".jpg",image)

代码2:加随机高斯噪声

def noise():
    coutn = 30
    for k in range(0, coutn):
        xi = int(np.random.uniform(0, img_data.shape[1]))
        xj = int(np.random.uniform(0, img_data.shape[0]))
        if img_data.ndim == 2:
            img_data[xj, xi] = 0
        elif img_data.ndim == 3:
            param = 30
            r1 = np.random.random_sample()
            r2 = np.random.random_sample()
            z1 = param * np.cos(2 * np.pi * r2) * np.sqrt((-2) * np.log(r1))
            z2 = param * np.sin(2 * np.pi * r2) * np.sqrt((-2) * np.log(r1))

            img_data[xj, xi, 0] = img_data[xj, xi, 0] + z1
            img_data[xj, xi, 1] = img_data[xj, xi, 1] + z1 / 2 + z2 / 2
            img_data[xj, xi, 2] = img_data[xj, xi, 2] + z2

            if img_data[xj, xi, 0] < 0:
                img_data[xj, xi, 0] = 0
            elif img_data[xj, xi, 0] > 255:
                img_data[xj, xi, 0] = 255

            if img_data[xj, xi, 1] < 0:
                img_data[xj, xi, 1] = 0
            elif img_data[xj, xi, 1] > 255:
                img_data[xj, xi, 1] = 255

            if img_data[xj, xi, 2] < 0:
                img_data[xj, xi, 2] = 0
            elif img_data[xj, xi, 2] > 255:
                img_data[xj, xi, 2] = 255

    cv2.imwrite(file_path + '-noise-' +str(n)+ '.bmp', img_data)

代码3:图片旋转

import cv2
import numpy as np
import random
import os


def rotate1(image, angle, scale=1):
    # if (count%2==0):
    w = image.shape[1]
    h = image.shape[0]
    M = cv2.getRotationMatrix2D((w/2,h/2), angle, scale)

    dst = cv2.warpAffine(image,M,(w,h))   #borderValue=(255,255,255)消除黑边
    cv2.imwrite(save_path+'-rotate-90'+'.jpg',dst)


def rotate2(image, angle, scale=1):
    w = image.shape[1]
    h = image.shape[0]
    M = cv2.getRotationMatrix2D((w/2,h/2), angle, scale)

    dst = cv2.warpAffine(image,M,(w,h))
    cv2.imwrite(save_path+'-rotate-2.jpg',dst)



n=0
path = "D:/work/Test/Test1/test8--数据增强--cv/data/3_mole/"  # 文件夹目录
files = os.listdir(path)  # 得到文件夹下的所有文件名称
for file in files:  # 遍历文件夹
    if file.endswith('.jpg'):
        if not os.path.isdir(file):  # 判断是否是文件夹,不是文件夹才打开
            img = cv2.imread(path + "/" + file,1)   # 打开文件
            n=n+1
            print(file)
            #分离文件后缀,提取文件名,保存到新路径
            save_name=os.path.splitext(file)[0]
            save_path="D:/work/Test/Test1/test8--数据增强--cv/data/3_mole/270/"+save_name
            
            #1.固定旋转
            # a=90
            # rotate1(img,a)
            # b=-6
            # rotate2(img,b)

            # for n in range(1,3):
                # #2.1随机旋转固定值
                # list=[6,-6]
                # a=random.sample(list, 1)[0]
                # rotate1(img1,a)

                # #2.1随机旋转范围值
                # a=random.randint(-180,180)
                # rotate1(img1, a)

另外介绍下旋转后无黑边的方法:
ng = im.transpose(img.ROTATE_90)
ng2 = im.transpose(img.ROTATE_180)
ng3 = im.transpose(img.ROTATE_270)


代码4:饱和度、亮度、对比度、锐度—单一参数调节

def randomColor(root_path,img_name): #随机颜色
    # if (count%2==0):
    # #1、调整图像的饱和度
    # random_factor = np.random.uniform(0.9,1.3)  # 随机因子
    # color_image = ImageEnhance.Color(image).enhance(random_factor)
    # color_image.save(save_path+'-saturation-'+str(n)+'.jpg')

    # if (count%2==1):
    # # 2、调整图像的亮度
    # random_factor = np.random.uniform(0.9,1.2)  # 随机因子
    # brightness_image = ImageEnhance.Brightness(image).enhance(random_factor)
    # # brightness_image.save(save_path)
    # brightness_image.save(save_path+'-bright-'+str(n)+'.jpg')

    # # if (count % 2 == 1):
    # # 3、调整图像对比度
    # random_factor = np.random.uniform(0.9,1.3)  # 随机因子
    # contrast_image = ImageEnhance.Contrast(image).enhance(random_factor)
    # contrast_image.save(save_path+'-contrast-'+str(n)+'.jpg')
    #
    # # if (count % 2==1):
    # 4、调整图像锐度
    random_factor = np.random.uniform(-3,3)  # 随机因子
    Sharpness_image=ImageEnhance.Sharpness(image).enhance(random_factor)
    Sharpness_image.save(save_path+'-Sharpness-'+str(n)+'.jpg')

代码5:饱和度、亮度、对比度、锐度—混合调节

import numpy as np
import skimage
import io,os
import cv2
import matplotlib.pyplot as plt
from PIL import Image,ImageEnhance
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

def randomColor(root_path,img_name): #随机颜色
    
    # 1、调整图像的饱和度
    random_factor = np.random.uniform(0.9,1.3)  # 随机因子
    color_image = ImageEnhance.Color(image).enhance(random_factor)


    # 2、调整图像的亮度
    random_factor = np.random.uniform(0.9,1.2)  # 随机因子
    brightness_image = ImageEnhance.Brightness(color_image).enhance(random_factor)


    # # 3、调整图像对比度
    # random_factor = np.random.uniform(0.8,1.3)  # 随机因子
    # contrast_image = ImageEnhance.Contrast(brightness_image).enhance(random_factor)

    # 4、调整图像锐度
    random_factor = np.random.uniform(-3,3)  # 随机因子
    mix_image = ImageEnhance.Sharpness(brightness_image).enhance(random_factor)

    mix_image.save(save_path + '-mix-' + str(n) + '.jpg')


if __name__ == '__main__':
    root_path = "J:/TF6/tf6-data-clear/45"  # 文件夹目录
    files = os.listdir(root_path)  # 得到文件夹下的所有文件名称
    for file in files:  # 遍历文件夹
        if file.endswith('jpg'):
            if not os.path.isdir(file):  # 判断是否是文件夹,不是文件夹才打开
                image = Image.open(os.path.join(root_path, file))

                #提取文件名,保存到新路径
                save_name=os.path.splitext(file)[0]
                save_path='J:/TF6/tf6-data-add/451/'+save_name

                for n in range(1,2):
                    randomColor(root_path,file)

猜你喜欢

转载自blog.csdn.net/gm_Ergou/article/details/90648300